public void UpdateColumns(GXDLMSProfileGeneric item, GXManufacturer man) { if (Comm.parentForm.InvokeRequired) { Comm.parentForm.Invoke(new UpdateColumnsEventHandler(UpdateColumns), item, man); return; } try { item.Buffer.Clear(); item.CaptureObjects.Clear(); List <GXKeyValuePair <GXDLMSObject, GXDLMSCaptureObject> > cols = null; List <DataColumn> columns = new List <DataColumn>(); if (this.Extension != null) { cols = this.Extension.Refresh(item, this.Comm); } if (cols == null) { Comm.GetProfileGenericColumns(item); } } catch (Exception ex) { MessageBox.Show(ex.Message); } }
private void ManufacturerCB_DrawItem(object sender, DrawItemEventArgs e) { // If the index is invalid then simply exit. if (e.Index == -1 || e.Index >= ManufacturerCB.Items.Count) { return; } // Draw the background of the item. e.DrawBackground(); // Should we draw the focus rectangle? if ((e.State & DrawItemState.Focus) != 0) { e.DrawFocusRectangle(); } Font f = new Font(e.Font, FontStyle.Regular); // Create a new background brush. Brush b = new SolidBrush(e.ForeColor); // Draw the item. GXManufacturer target = (GXManufacturer)ManufacturerCB.Items[e.Index]; if (target == null) { return; } string name = target.Name; SizeF s = e.Graphics.MeasureString(name, f); e.Graphics.DrawString(name, f, b, e.Bounds); }
ListViewItem AddManufacturer(GXManufacturer manufacturer) { ListViewItem it = ManufacturersList.Items.Add(manufacturer.Name); it.Tag = manufacturer; return(it); }
public AuthenticationGmacForm(GXManufacturer target) { InitializeComponent(); SecurityCB.Items.AddRange(new object[] { Security.None, Security.Authentication, Security.Encryption, Security.AuthenticationEncryption }); Target = target; this.Text = " Security connection settings"; this.SecurityCB.SelectedItem = target.Security; //Update default values. if (target.SystemTitle == null && target.BlockCipherKey == null && target.AuthenticationKey == null) { this.SystemTitleTB.Text = GXCommon.ToHex(ASCIIEncoding.ASCII.GetBytes("ABCDEFGH"), true); this.BlockCipherKeyTB.Text = "00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F"; this.AuthenticationKeyTB.Text = "D0 D1 D2 D3 D4 D5 D6 D7 D8 D9 DA DB DC DD DE DF"; AsciiRB.Enabled = false; } else { this.SystemTitleTB.Text = GXCommon.ToHex(target.SystemTitle, true); this.BlockCipherKeyTB.Text = GXCommon.ToHex(target.BlockCipherKey, true); this.AuthenticationKeyTB.Text = GXCommon.ToHex(target.AuthenticationKey, true); } if (!IsPrintable(target.SystemTitle) || !IsPrintable(target.BlockCipherKey) || !IsPrintable(target.AuthenticationKey)) { AsciiRB.Enabled = false; } }
public void UpdateManufactureSettings(string id) { if (Manufacturer != null && string.Compare(Manufacturer.Identification, id, true) != 0) { throw new Exception(string.Format("Manufacturer type does not match. Manufacturer is {0} and it should be {1}.", id, Manufacturer.Identification)); } m_Parser.InterfaceType = InterfaceType.General; m_Parser.UseLogicalNameReferencing = Manufacturer.UseLN; //If network media is used check is manufacturer supporting IEC 62056-47 GXServerAddress server = Manufacturer.GetServer(HDLCAddressing); if (this.Media is GXNet && Manufacturer.UseIEC47) { m_Parser.InterfaceType = InterfaceType.Net; m_Parser.ClientID = Convert.ToUInt16(Manufacturer.GetAuthentication(m_Parser.Authentication).ClientID); m_Parser.ServerID = Convert.ToUInt16(server.PhysicalAddress); } else { if (HDLCAddressing == HDLCAddressType.Custom) { m_Parser.ClientID = Manufacturer.GetAuthentication(m_Parser.Authentication).ClientID; } else { m_Parser.ClientID = (byte)(Convert.ToByte(Manufacturer.GetAuthentication(m_Parser.Authentication).ClientID) << 1 | 0x1); } m_Parser.ServerID = GXManufacturer.CountServerAddress(HDLCAddressing, server.Formula, server.PhysicalAddress, server.LogicalAddress); } }
public void UpdateColumns(GXDLMSProfileGeneric item, GXManufacturer man) { if (Comm.parentForm.InvokeRequired) { try { Comm.parentForm.Invoke(new UpdateColumnsEventHandler(UpdateColumns), item, man); } catch (Exception ex) { MessageBox.Show(ex.Message); } return; } try { item.Buffer.Clear(); item.CaptureObjects.Clear(); List <GXKeyValuePair <GXDLMSObject, GXDLMSCaptureObject> > cols = null; List <DataColumn> columns = new List <DataColumn>(); try { Comm.GetProfileGenericColumns(item); if (Standard == Standard.Italy && item.CaptureObjects.Count == 0) { cols = GetColumns(Comm.client.Objects, Comm.client.CustomObisCodes, item.LogicalName); GXDLMSConverter c = new GXDLMSConverter(Standard); foreach (var it in cols) { c.UpdateOBISCodeInformation(it.Key); } item.CaptureObjects.AddRange(cols); } } catch (GXDLMSException ex) { if (Standard == Standard.Italy) { cols = GetColumns(Comm.client.Objects, Comm.client.CustomObisCodes, item.LogicalName); item.CaptureObjects.Clear(); GXDLMSConverter c = new GXDLMSConverter(Standard); foreach (var it in cols) { c.UpdateOBISCodeInformation(it.Key); } item.CaptureObjects.AddRange(cols); } if (cols == null || cols.Count == 0) { throw ex; } } } catch (Exception ex) { MessageBox.Show(ex.Message); } }
public void PreAction(GXActionArgs arg) { GXDLMSImageTransfer it = Target as GXDLMSImageTransfer; if (arg.Action == ActionType.Action) { if (arg.Index == 1) { if (arg.Tag is GXImageUpdateStatus status) { //Initiate the Image transfer process. arg.Value = it.ImageTransferInitiate(arg.Client, status.ImageIdentifier, status.Image.Length); } else { //Check that delay is correct and save it. GetDelay(arg); if (arg.Exception != null) { return; } GXManufacturerCollection manufacturers = new GXManufacturerCollection(); GXManufacturerCollection.ReadManufacturerSettings(manufacturers); GXManufacturer man = manufacturers.FindByIdentification(arg.Client.ManufacturerId); Properties.Settings.Default.ImageDelay = (int)arg.Value / 1000; GXImageDlg dlg = new GXImageDlg(man.ManucatureSettings, arg.Client); OnImageDialog(dlg, arg); if (arg.Action == ActionType.None) { return; } arg.Index = 5; arg.Action = ActionType.Read; return; } } else if (arg.Index == 2) { //Start image block transfer. GXImageUpdateStatus status = (GXImageUpdateStatus)arg.Tag; int imageBlockCount; arg.Value = it.ImageBlockTransfer(arg.Client, status.Image, status.ImageStartIndex, out imageBlockCount); OnDescription("Sending " + imageBlockCount + " blocks."); } else if (arg.Index == 3) { arg.Value = it.ImageVerify(arg.Client); OnDescription("Verifying image."); } else if (arg.Index == 4) { arg.Value = it.ImageActivate(arg.Client); OnDescription("Activating image."); } } }
private void ReadCMnu_Click(object sender, EventArgs e) { try { if (Devices.SelectedNode != null) { GXDLMSMeter dev = Devices.SelectedNode.Tag as GXDLMSMeter; List <KeyValuePair <GXDLMSObject, byte> > objects = new List <KeyValuePair <GXDLMSObject, byte> >(); //Read association view if there are no objects on the meter. if (dev.Objects.Count == 0) { objects.Add(new KeyValuePair <GXDLMSObject, byte>(new GXDLMSAssociationLogicalName(), 2)); } target.ReadObjects(new GXDLMSMeter[] { dev }, objects); if (dev.Objects.Count == 0) { //Add all objects. TreeNode n = nodes[dev]; List <TreeNode> list = new List <TreeNode>(); foreach (GXDLMSObject it in (objects[0].Key as GXDLMSAssociationLogicalName).ObjectList) { GXManufacturer m = Manufacturers.FindByIdentification(dev.Manufacturer); if (m.ObisCodes != null) { GXDLMSConverter c = new GXDLMSConverter(); GXObisCode oc = m.ObisCodes.FindByLN(it.ObjectType, it.LogicalName, null); if (string.IsNullOrEmpty(it.Description)) { it.Description = c.GetDescription(it.LogicalName, it.ObjectType)[0]; } if (oc != null) { MainForm.UpdateAttributes(it, oc); } } TreeNode t = new TreeNode(it.LogicalName + " " + it.Description); t.Tag = it; list.Add(t); } n.Nodes.AddRange(list.ToArray()); } } } catch (Exception ex) { MessageBox.Show(this, ex.Message); } }
/// <summary> /// Find correct DLMS class by Interface Type from the assembly. /// </summary> /// <param name="device"></param> /// <param name="it"></param> /// <returns></returns> public static GXDLMSObject ConvertObject2Class(GXDLMSDevice device, Gurux.DLMS.ObjectType objectType, string logicalName) { GXDLMSObject obj = Gurux.DLMS.GXDLMSClient.CreateObject(objectType); if (obj != null) { GXManufacturer m = device.Manufacturers.FindByIdentification(device.Manufacturer); GXObisCode item = m.ObisCodes.FindByLN(obj.ObjectType, logicalName, null); obj.LogicalName = logicalName; if (item != null) { obj.Description = item.Description; } } return(obj); }
/// <summary> /// Edit selected manufacturer's settings. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void EditBtn_Click(object sender, EventArgs e) { try { GXManufacturer m = (GXManufacturer)ManufacturersList.SelectedItems[0].Tag; ManufacturerForm dlg = new ManufacturerForm(Manufacturers, m); if (dlg.ShowDialog(this) == DialogResult.OK) { ManufacturersList.SelectedItems[0].Text = m.Name; UpdateValues(); } } catch (Exception Ex) { GXDLMS.Common.Error.ShowError(this, Ex); } }
private void EditBtn_Click(object sender, EventArgs e) { try { GXObisCode item = (GXObisCode)OBISCodesList.SelectedItems[0].Tag; GXManufacturer man = (GXManufacturer)ManufacturersList.SelectedItems[0].Tag; OBISCodeForm dlg = new OBISCodeForm(new GXDLMSConverter(man.Standard), null, man.ObisCodes, item); if (dlg.ShowDialog(this) == DialogResult.OK) { OBISCodesList.SelectedItems[0].Text = item.LogicalName + " " + item.Description; } } catch (Exception Ex) { GXDLMS.Common.Error.ShowError(this, Ex); } }
public void UpdateManufactureSettings(string id) { if (!string.IsNullOrEmpty(this.Parent.Manufacturer) && string.Compare(this.Parent.Manufacturer, id, true) != 0) { throw new Exception(string.Format("Manufacturer type does not match. Manufacturer is {0} and it should be {1}.", id, this.Parent.Manufacturer)); } GXManufacturer manufacturer = this.Parent.Manufacturers.FindByIdentification(id); if (manufacturer == null) { throw new Exception("Unknown manufacturer " + id); } this.Parent.Manufacturer = manufacturer.Identification; m_Cosem.Authentication = this.Parent.Authentication; m_Cosem.InterfaceType = InterfaceType.General; if (!string.IsNullOrEmpty(this.Parent.Password)) { m_Cosem.Password = CryptHelper.Decrypt(this.Parent.Password, Password.Key); } m_Cosem.UseLogicalNameReferencing = this.Parent.UseLogicalNameReferencing; //If network media is used check is manufacturer supporting IEC 62056-47 if (!Parent.UseRemoteSerial && this.Media is GXNet && manufacturer.UseIEC47) { m_Cosem.InterfaceType = InterfaceType.Net; m_Cosem.ClientID = Convert.ToUInt16(Parent.ClientID); m_Cosem.ServerID = Convert.ToUInt16((Parent.LogicalAddress << 9) | Convert.ToUInt16(Parent.PhysicalAddress)); } else { if (Parent.HDLCAddressing == HDLCAddressType.Custom) { m_Cosem.ClientID = Parent.ClientID; } else { m_Cosem.ClientID = (byte)(Convert.ToByte(Parent.ClientID) << 1 | 0x1); } string formula = null; GXServerAddress server = manufacturer.GetServer(Parent.HDLCAddressing); if (server != null) { formula = server.Formula; } m_Cosem.ServerID = GXManufacturer.CountServerAddress(Parent.HDLCAddressing, formula, Parent.PhysicalAddress, Parent.LogicalAddress); } }
/// <summary> /// Add new manufacturer. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void NewBtn_Click(object sender, EventArgs e) { try { GXManufacturer m = new GXManufacturer(); ManufacturerForm dlg = new ManufacturerForm(Manufacturers, m); if (dlg.ShowDialog(this) == DialogResult.OK) { Manufacturers.Add(m); AddManufacturer(m).Selected = true; } } catch (Exception Ex) { GXDLMS.Common.Error.ShowError(this, Ex); } }
/// <summary> /// Remove selected manufacturer. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void RemoveBtn_Click(object sender, EventArgs e) { try { while (ManufacturersList.SelectedItems.Count != 0) { GXManufacturer m = (GXManufacturer)ManufacturersList.SelectedItems[0].Tag; ManufacturersList.SelectedItems[0].Remove(); Items.Remove(m); m.Removed = true; } } catch (Exception Ex) { GXDLMS.Common.Error.ShowError(this, Ex); } }
private void NewBtn_Click(object sender, EventArgs e) { try { GXObisCode item = new GXObisCode(); GXManufacturer man = (GXManufacturer)ManufacturersList.SelectedItems[0].Tag; OBISCodeForm dlg = new OBISCodeForm(new GXDLMSConverter(man.Standard), null, man.ObisCodes, item); if (dlg.ShowDialog(this) == DialogResult.OK) { AddItem(item); ((GXManufacturer)ManufacturersList.SelectedItems[0].Tag).ObisCodes.Add(item); } } catch (Exception Ex) { GXDLMS.Common.Error.ShowError(this, Ex); } }
void UpdateStartProtocol() { //If IEC47 is used DLMS is only protocol. GXManufacturer man = this.ManufacturerCB.SelectedItem as GXManufacturer; this.UseLNCB.Checked = man.UseLogicalNameReferencing; if (SelectedMedia is GXNet && man != null) { StartProtocolCB.Enabled = !man.UseIEC47; } else { StartProtocolCB.Enabled = true; } if (!StartProtocolCB.Enabled) { StartProtocolCB.SelectedItem = StartProtocolType.DLMS; } }
void UpdateValues() { bool bEnabled = ManufacturersList.SelectedItems.Count == 1; RemoveBtn.Enabled = EditBtn.Enabled = bEnabled; if (bEnabled) { GXManufacturer m = (GXManufacturer)ManufacturersList.SelectedItems[0].Tag; NameTB.Text = m.Name; ManufacturerIdTB.Text = m.Identification; UseLNCB.Checked = m.UseLogicalNameReferencing; UseIEC47CB.Checked = m.UseIEC47; StartProtocolTB.Text = m.StartProtocol.ToString(); } else { StartProtocolTB.Text = NameTB.Text = ManufacturerIdTB.Text = ""; UseLNCB.Checked = UseIEC47CB.Checked = false; } }
private void ManufacturerCB_SelectedIndexChanged(object sender, EventArgs e) { try { GXManufacturer man = (GXManufacturer)ManufacturerCB.SelectedItem; StartProtocolCB.SelectedItem = man.StartProtocol; this.ClientAddTB.Value = Convert.ToDecimal(Convert.ToUInt32(man.GetActiveAuthentication().ClientID)); AuthenticationCB.Items.Clear(); foreach (GXAuthentication it in man.Settings) { int pos = AuthenticationCB.Items.Add(it); if (it.Type == Device.Authentication) { this.AuthenticationCB.SelectedIndex = pos; } } ServerAddressTypeCB.Items.Clear(); HDLCAddressType type = Device.HDLCAddressing; //If we are creating new device. if (Device.Name == null) { type = man.GetActiveServer().HDLCAddress; } foreach (GXServerAddress it in ((GXManufacturer)ManufacturerCB.SelectedItem).ServerSettings) { ServerAddressTypeCB.Items.Add(it); if (it.HDLCAddress == type) { ServerAddressTypeCB.SelectedItem = it; } } UpdateStartProtocol(); } catch (Exception Ex) { GXDLMS.Common.Error.ShowError(this, Ex); } }
public GXGraphItemForm(GXGraphItemCollection items, List <GXKeyValuePair <GXDLMSObject, GXDLMSCaptureObject> > columns, GXDLMSDevice device) { InitializeComponent(); GraphItemEditor_SizeChanged(null, null); GraphItemList.OwnerDraw = true; Items = items; int pos = 0; List <string> colors = GetColors(); GXManufacturer man = device.Manufacturers.FindByIdentification(device.Manufacturer); foreach (var it in columns) { GXDLMSObject obj = it.Key; int index = it.Value.AttributeIndex; if (!GXHelpers.IsNumeric(obj.GetDataType(index)) || (index > 0 && ((index & 0x8) != 0 || (index & 0x10) != 0))) { continue; } GXGraphItem item = items.Find(obj.LogicalName, index); if (item == null) { item = new GXGraphItem(); item.LogicalName = obj.LogicalName; item.Color = Color.FromName(colors[pos++]); item.AttributeIndex = index; items.Add(item); } string desc = obj.Description; GXObisCode code = man.ObisCodes.FindByLN(obj.ObjectType, obj.LogicalName, null); if (code != null) { desc = code.Description; } ListViewItem tmp = GraphItemList.Items.Add(obj.LogicalName + " " + desc); tmp.Tag = item; } }
void UpdateValues() { bool bEnabled = ManufacturersList.SelectedItems.Count == 1; RemoveBtn.Enabled = EditBtn.Enabled = bEnabled; SupportedInterfacesTb.Text = ""; if (bEnabled) { GXManufacturer m = (GXManufacturer)ManufacturersList.SelectedItems[0].Tag; NameTB.Text = m.Name; ManufacturerIdTB.Text = m.Identification; UseLNCB.Checked = m.UseLogicalNameReferencing; if (m.SupporterdInterfaces != 0) { UpdatateInterface((m.SupporterdInterfaces & (1 << (int)InterfaceType.HDLC)) != 0, InterfaceType.HDLC); UpdatateInterface((m.SupporterdInterfaces & (1 << (int)InterfaceType.HdlcWithModeE)) != 0, InterfaceType.HdlcWithModeE); UpdatateInterface((m.SupporterdInterfaces & (1 << (int)InterfaceType.WRAPPER)) != 0, InterfaceType.WRAPPER); UpdatateInterface((m.SupporterdInterfaces & (1 << (int)InterfaceType.WirelessMBus)) != 0, InterfaceType.WirelessMBus); UpdatateInterface((m.SupporterdInterfaces & (1 << (int)InterfaceType.Plc)) != 0, InterfaceType.Plc); UpdatateInterface((m.SupporterdInterfaces & (1 << (int)InterfaceType.PlcHdlc)) != 0, InterfaceType.PlcHdlc); UpdatateInterface((m.SupporterdInterfaces & (1 << (int)InterfaceType.LPWAN)) != 0, InterfaceType.LPWAN); UpdatateInterface((m.SupporterdInterfaces & (1 << (int)InterfaceType.WiSUN)) != 0, InterfaceType.WiSUN); } else { //Select default interfaces. UpdatateInterface(true, InterfaceType.HDLC); UpdatateInterface(true, InterfaceType.HdlcWithModeE); UpdatateInterface(true, InterfaceType.WRAPPER); } } else { NameTB.Text = ManufacturerIdTB.Text = ""; UseLNCB.Checked = false; } }
public ManufacturerForm(GXManufacturerCollection manufacturers, GXManufacturer manufacturer) { InitializeComponent(); foreach (object it in Enum.GetValues(typeof(Standard))) { StandardCb.Items.Add(it); } StandardCb.SelectedItem = manufacturer.Standard; SecurityCB.Items.AddRange(new object[] { Security.None, Security.Authentication, Security.Encryption, Security.AuthenticationEncryption }); Manufacturers = manufacturers; Manufacturer = manufacturer; if (manufacturer.Settings.Count == 0) { manufacturer.Settings.Add(new GXAuthentication(Authentication.None, (byte)0x10)); manufacturer.Settings.Add(new GXAuthentication(Authentication.Low, (byte)0x11)); manufacturer.Settings.Add(new GXAuthentication(Authentication.High, (byte)0x12)); manufacturer.Settings.Add(new GXAuthentication(Authentication.HighMD5, (byte)0x13)); manufacturer.Settings.Add(new GXAuthentication(Authentication.HighSHA1, (byte)0x14)); manufacturer.Settings.Add(new GXAuthentication(Authentication.HighGMAC, (byte)0x14)); manufacturer.Settings.Add(new GXAuthentication(Authentication.HighSHA256, (byte)0x14)); manufacturer.Settings.Add(new GXAuthentication(Authentication.HighECDSA, (byte)0x14)); GXAuthentication gmac = new GXAuthentication(Authentication.HighGMAC, (byte)0x15); } GXAuthentication authentication = manufacturer.GetActiveAuthentication(); foreach (GXAuthentication it in manufacturer.Settings) { AuthenticationCB.Items.Add(it); } AuthenticationCB.SelectedItem = authentication; this.AuthenticationCB.SelectedIndexChanged += new System.EventHandler(this.AuthenticationCB_SelectedIndexChanged); if (manufacturer.ServerSettings.Count == 0) { manufacturer.ServerSettings.Add(new GXServerAddress(HDLCAddressType.Default, (byte)1, true)); manufacturer.ServerSettings.Add(new GXServerAddress(HDLCAddressType.SerialNumber, (byte)1, false)); manufacturer.ServerSettings.Add(new GXServerAddress(HDLCAddressType.Custom, (byte)1, false)); } foreach (GXServerAddress it in manufacturer.ServerSettings) { ServerAddressTypeCB.Items.Add(it); } GXServerAddress server = manufacturer.GetActiveServer(); ServerAddressTypeCB.SelectedItem = server; RefreshServer(server); this.ServerAddressTypeCB.SelectedIndexChanged += new System.EventHandler(this.ServerAddressTypeCB_SelectedIndexChanged); ServerAddressTypeCB.DrawMode = AuthenticationCB.DrawMode = DrawMode.OwnerDrawFixed; ClientAddTB.Value = authentication.ClientAddress; StartProtocolCB.Items.Add(StartProtocolType.IEC); StartProtocolCB.Items.Add(StartProtocolType.DLMS); NameTB.Text = manufacturer.Name; ManufacturerIdTB.Text = manufacturer.Identification; UseLNCB.Checked = manufacturer.UseLogicalNameReferencing; UseIEC47CB.Checked = manufacturer.UseIEC47; StartProtocolCB.SelectedItem = manufacturer.StartProtocol; //Manufacturer ID can not change after creation. ManufacturerIdTB.Enabled = string.IsNullOrEmpty(manufacturer.Identification); WebAddressTB.Text = Manufacturer.WebAddress; if (!string.IsNullOrEmpty(Manufacturer.Info)) { try { InfoTB.Text = ASCIIEncoding.UTF8.GetString(Convert.FromBase64String(Manufacturer.Info)); } catch (Exception) { InfoTB.Text = ""; } } SecurityCB.SelectedItem = manufacturer.Security; if (DevicePropertiesForm.IsAscii(manufacturer.SystemTitle)) { SystemTitleAsciiCb.Checked = true; SystemTitleTB.Text = ASCIIEncoding.ASCII.GetString((manufacturer.SystemTitle)); } else { SystemTitleTB.Text = GXCommon.ToHex(manufacturer.SystemTitle, true); } if (DevicePropertiesForm.IsAscii(manufacturer.BlockCipherKey)) { BlockCipherKeyAsciiCb.Checked = true; BlockCipherKeyTB.Text = ASCIIEncoding.ASCII.GetString(manufacturer.BlockCipherKey); } else { BlockCipherKeyTB.Text = GXCommon.ToHex(manufacturer.BlockCipherKey, true); } if (DevicePropertiesForm.IsAscii(manufacturer.AuthenticationKey)) { AuthenticationKeyAsciiCb.Checked = true; AuthenticationKeyTB.Text = ASCIIEncoding.ASCII.GetString(manufacturer.AuthenticationKey); } else { AuthenticationKeyTB.Text = GXCommon.ToHex(manufacturer.AuthenticationKey, true); } }
void InitializeIEC() { GXManufacturer manufacturer = this.Parent.Manufacturers.FindByIdentification(Parent.Manufacturer); if (manufacturer == null) { throw new Exception("Unknown manufacturer " + Parent.Manufacturer); } GXSerial serial = Media as GXSerial; byte Terminator = (byte)0x0A; if (serial != null && Parent.StartProtocol == StartProtocolType.IEC) { serial.BaudRate = 300; serial.DataBits = 7; serial.Parity = Parity.Even; serial.StopBits = StopBits.One; } Media.Open(); //Query device information. if (Media != null && Parent.StartProtocol == StartProtocolType.IEC) { string data = "/?!\r\n"; if (this.Parent.HDLCAddressing == HDLCAddressType.SerialNumber) { data = "/?" + this.Parent.PhysicalAddress + "!\r\n"; } GXLogWriter.WriteLog("HDLC sending:" + data); ReceiveParameters <string> p = new ReceiveParameters <string>() { AllData = false, Eop = Terminator, WaitTime = Parent.WaitTime * 1000 }; lock (Media.Synchronous) { Media.Send(data, null); if (!Media.Receive(p)) { //Try to move away from mode E. try { this.ReadDLMSPacket(this.DisconnectRequest(), 1); } catch (Exception ex) { } data = (char)0x01 + "B0" + (char)0x03 + "\r\n"; Media.Send(data, null); p.Count = 1; Media.Receive(p); data = "Failed to receive reply from the device in given time."; GXLogWriter.WriteLog(data); throw new Exception(data); } //If echo is used. if (p.Reply == data) { p.Reply = null; if (!Media.Receive(p)) { //Try to move away from mode E. this.ReadDLMSPacket(this.DisconnectRequest(), 1); if (serial != null) { data = (char)0x01 + "B0" + (char)0x03 + "\r\n"; Media.Send(data, null); p.Count = 1; if (!Media.Receive(p)) { } serial.DtrEnable = serial.RtsEnable = false; serial.BaudRate = 9600; serial.DtrEnable = serial.RtsEnable = true; data = (char)0x01 + "B0" + (char)0x03 + "\r\n"; Media.Send(data, null); p.Count = 1; Media.Receive(p); } data = "Failed to receive reply from the device in given time."; GXLogWriter.WriteLog(data); throw new Exception(data); } } } GXLogWriter.WriteLog("HDLC received: " + p.Reply); if (p.Reply[0] != '/') { p.WaitTime = 100; Media.Receive(p); throw new Exception("Invalid responce."); } string manufactureID = p.Reply.Substring(1, 3); UpdateManufactureSettings(manufactureID); char baudrate = p.Reply[4]; int BaudRate = 0; switch (baudrate) { case '0': BaudRate = 300; break; case '1': BaudRate = 600; break; case '2': BaudRate = 1200; break; case '3': BaudRate = 2400; break; case '4': BaudRate = 4800; break; case '5': BaudRate = 9600; break; case '6': BaudRate = 19200; break; default: throw new Exception("Unknown baud rate."); } GXLogWriter.WriteLog("BaudRate is : " + BaudRate.ToString()); //Send ACK //Send Protocol control character byte controlCharacter = (byte)'2';// "2" HDLC protocol procedure (Mode E) //Send Baud rate character //Mode control character byte ModeControlCharacter = (byte)'2';//"2" //(HDLC protocol procedure) (Binary mode) //Set mode E. byte[] arr = new byte[] { 0x06, controlCharacter, (byte)baudrate, ModeControlCharacter, 13, 10 }; GXLogWriter.WriteLog("Moving to mode E.", arr); lock (Media.Synchronous) { Media.Send(arr, null); System.Threading.Thread.Sleep(500); serial.BaudRate = BaudRate; p.Reply = null; p.WaitTime = 100; //Note! All meters do not echo this. Media.Receive(p); if (p.Reply != null) { GXLogWriter.WriteLog("Received: " + p.Reply); } serial.Close(); serial.DataBits = 8; serial.Parity = Parity.None; serial.StopBits = StopBits.One; serial.Open(); System.Threading.Thread.Sleep(500); } } }
public ManufacturerForm(GXManufacturerCollection manufacturers, GXManufacturer manufacturer) { InitializeComponent(); Manufacturers = manufacturers; Manufacturer = manufacturer; if (manufacturer.Settings.Count == 0) { manufacturer.Settings.Add(new GXAuthentication(Authentication.None, (byte)0x10)); manufacturer.Settings.Add(new GXAuthentication(Authentication.Low, (byte)0x11)); manufacturer.Settings.Add(new GXAuthentication(Authentication.High, (byte)0x12)); manufacturer.Settings.Add(new GXAuthentication(Authentication.HighMD5, (byte)0x13)); manufacturer.Settings.Add(new GXAuthentication(Authentication.HighSHA1, (byte)0x14)); GXAuthentication gmac = new GXAuthentication(Authentication.HighGMAC, (byte)0x15); } GXAuthentication authentication = manufacturer.GetActiveAuthentication(); foreach (GXAuthentication it in manufacturer.Settings) { AuthenticationCB.Items.Add(it); } AuthenticationCB.SelectedItem = authentication; AdvancedBtn.Enabled = authentication.Type == Authentication.HighGMAC; this.AuthenticationCB.SelectedIndexChanged += new System.EventHandler(this.AuthenticationCB_SelectedIndexChanged); if (manufacturer.ServerSettings.Count == 0) { manufacturer.ServerSettings.Add(new GXServerAddress(HDLCAddressType.Default, (byte)1, true)); manufacturer.ServerSettings.Add(new GXServerAddress(HDLCAddressType.SerialNumber, (byte)1, false)); manufacturer.ServerSettings.Add(new GXServerAddress(HDLCAddressType.Custom, (byte)1, false)); } foreach (GXServerAddress it in manufacturer.ServerSettings) { ServerAddressTypeCB.Items.Add(it); } GXServerAddress server = manufacturer.GetActiveServer(); ServerAddressTypeCB.SelectedItem = server; RefreshServer(server); this.ServerAddressTypeCB.SelectedIndexChanged += new System.EventHandler(this.ServerAddressTypeCB_SelectedIndexChanged); ServerAddressTypeCB.DrawMode = AuthenticationCB.DrawMode = DrawMode.OwnerDrawFixed; ClientAddTB.Value = authentication.ClientAddress; InactivityModeCB.Items.Add(InactivityMode.None); InactivityModeCB.Items.Add(InactivityMode.KeepAlive); InactivityModeCB.Items.Add(InactivityMode.Reopen); InactivityModeCB.Items.Add(InactivityMode.ReopenActive); InactivityModeCB.Items.Add(InactivityMode.Disconnect); StartProtocolCB.Items.Add(StartProtocolType.IEC); StartProtocolCB.Items.Add(StartProtocolType.DLMS); NameTB.Text = manufacturer.Name; ManufacturerIdTB.Text = manufacturer.Identification; ForceKeepAliveCB.Checked = manufacturer.ForceInactivity; UseLNCB.Checked = manufacturer.UseLogicalNameReferencing; UseIEC47CB.Checked = manufacturer.UseIEC47; StartProtocolCB.SelectedItem = manufacturer.StartProtocol; InactivityModeCB.SelectedItem = Manufacturer.InactivityMode; //Manufacturer ID can not change after creation. ManufacturerIdTB.Enabled = string.IsNullOrEmpty(manufacturer.Identification); KeepAliveIntervalTB.Value = Manufacturer.KeepAliveInterval / 1000; AdvancedBtn.Enabled = SecuredConnectionCB.Checked = manufacturer.SystemTitle != null; WebAddressTB.Text = Manufacturer.WebAddress; if (!string.IsNullOrEmpty(Manufacturer.Info)) { try { InfoTB.Text = ASCIIEncoding.UTF8.GetString(Convert.FromBase64String(Manufacturer.Info)); } catch (Exception) { InfoTB.Text = ""; } } }
public ManufacturerForm(GXManufacturerCollection manufacturers, GXManufacturer manufacturer) { InitializeComponent(); Manufacturers = manufacturers; Manufacturer = manufacturer; if (manufacturer.Settings.Count == 0) { manufacturer.Settings.Add(new GXAuthentication(Gurux.DLMS.Authentication.None, (byte)0x10)); manufacturer.Settings.Add(new GXAuthentication(Gurux.DLMS.Authentication.Low, (byte)0x11)); manufacturer.Settings.Add(new GXAuthentication(Gurux.DLMS.Authentication.High, (byte)0x12)); manufacturer.Settings.Add(new GXAuthentication(Gurux.DLMS.Authentication.HighMD5, (byte)0x13)); manufacturer.Settings.Add(new GXAuthentication(Gurux.DLMS.Authentication.HighSHA1, (byte)0x14)); GXAuthentication gmac = new GXAuthentication(Gurux.DLMS.Authentication.HighGMAC, (byte)0x15); gmac.BlockCipherKey = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F }; gmac.AuthenticationKey = new byte[] { 0xD0, 0xD1, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, 0xD8, 0xD9, 0xDA, 0xDB, 0xDC, 0xDD, 0xDE, 0xDF }; manufacturer.Settings.Add(gmac); } GXAuthentication authentication = manufacturer.GetActiveAuthentication(); foreach (GXAuthentication it in manufacturer.Settings) { AuthenticationCB.Items.Add(it); } AuthenticationCB.SelectedItem = authentication; if (authentication.Type == Gurux.DLMS.Authentication.High || authentication.Type == Gurux.DLMS.Authentication.HighSHA1 || authentication.Type == Gurux.DLMS.Authentication.HighGMAC) { AdvancedBtn.Enabled = true; } this.AuthenticationCB.SelectedIndexChanged += new System.EventHandler(this.AuthenticationCB_SelectedIndexChanged); if (manufacturer.ServerSettings.Count == 0) { manufacturer.ServerSettings.Add(new GXServerAddress(HDLCAddressType.Default, (byte)1, true)); manufacturer.ServerSettings.Add(new GXServerAddress(HDLCAddressType.SerialNumber, (byte)1, false)); manufacturer.ServerSettings.Add(new GXServerAddress(HDLCAddressType.Custom, (byte)1, false)); } foreach (GXServerAddress it in manufacturer.ServerSettings) { ServerAddressTypeCB.Items.Add(it); } ServerAddTypeCB.Items.Add(typeof(byte)); ServerAddTypeCB.Items.Add(typeof(ushort)); ServerAddTypeCB.Items.Add(typeof(uint)); GXServerAddress server = manufacturer.GetActiveServer(); ServerAddressTypeCB.SelectedItem = server; RefreshServer(server); this.ServerAddressTypeCB.SelectedIndexChanged += new System.EventHandler(this.ServerAddressTypeCB_SelectedIndexChanged); ServerAddressTypeCB.DrawMode = AuthenticationCB.DrawMode = ClientAddTypeCB.DrawMode = ServerAddTypeCB.DrawMode = DrawMode.OwnerDrawFixed; ClientAddTypeCB.Items.Add(typeof(byte)); ClientAddTypeCB.Items.Add(typeof(ushort)); ClientAddTypeCB.Items.Add(typeof(uint)); if (authentication.ClientID != null) { ClientAddTB.Value = Convert.ToDecimal(authentication.ClientID); ClientAddTypeCB.SelectedItem = authentication.ClientID.GetType(); } RefreshAuthentication(authentication); InactivityModeCB.Items.Add(InactivityMode.None); InactivityModeCB.Items.Add(InactivityMode.KeepAlive); InactivityModeCB.Items.Add(InactivityMode.Reopen); InactivityModeCB.Items.Add(InactivityMode.ReopenActive); InactivityModeCB.Items.Add(InactivityMode.Disconnect); StartProtocolCB.Items.Add(StartProtocolType.IEC); StartProtocolCB.Items.Add(StartProtocolType.DLMS); NameTB.Text = manufacturer.Name; ManufacturerIdTB.Text = manufacturer.Identification; ForceKeepAliveCB.Checked = manufacturer.ForceInactivity; UseLNCB.Checked = manufacturer.UseLogicalNameReferencing; UseIEC47CB.Checked = manufacturer.UseIEC47; StartProtocolCB.SelectedItem = manufacturer.StartProtocol; InactivityModeCB.SelectedItem = Manufacturer.InactivityMode; //Manufacturer ID can not change after creation. ManufacturerIdTB.Enabled = string.IsNullOrEmpty(manufacturer.Identification); KeepAliveIntervalTB.Value = Manufacturer.KeepAliveInterval / 1000; }
public void UpdateColumns(GXDLMSProfileGeneric item, GXManufacturer man) { if (Comm.parentForm.InvokeRequired) { try { Comm.parentForm.Invoke(new UpdateColumnsEventHandler(UpdateColumns), item, man); } catch (Exception ex) { MessageBox.Show(ex.Message); } return; } try { item.Buffer.Clear(); item.CaptureObjects.Clear(); List <GXKeyValuePair <GXDLMSObject, GXDLMSCaptureObject> > cols = null; List <DataColumn> columns = new List <DataColumn>(); try { Comm.GetProfileGenericColumns(item); if (Standard == Standard.Italy && item.CaptureObjects.Count == 0) { cols = GetColumns(Comm.client.Objects, Comm.client.CustomObisCodes, item.LogicalName, 0); GXDLMSConverter c = new GXDLMSConverter(Standard); foreach (var it in cols) { c.UpdateOBISCodeInformation(it.Key); } item.CaptureObjects.AddRange(cols); } } catch (GXDLMSException ex) { if (Standard == Standard.Italy) { GXDLMSData obj = Comm.client.Objects.FindByLN(ObjectType.Data, "0.0.96.1.3.255") as GXDLMSData; int type = 0; if (obj != null) { if (obj.Value == null) { try { Comm.ReadValue(obj, 2); type = Convert.ToInt16(obj.Value); } catch (Exception) { type = 0; } } else { type = Convert.ToInt16(obj.Value); } } cols = GetColumns(Comm.client.Objects, Comm.client.CustomObisCodes, item.LogicalName, type); item.CaptureObjects.Clear(); GXDLMSConverter c = new GXDLMSConverter(Standard); foreach (var it in cols) { c.UpdateOBISCodeInformation(it.Key); } item.CaptureObjects.AddRange(cols); } if (cols == null || cols.Count == 0) { throw ex; } } } catch (Exception ex) { MessageBox.Show(ex.Message); } }
private void ManufacturerCB_SelectedIndexChanged(object sender, EventArgs e) { try { GXManufacturer man = (GXManufacturer)ManufacturerCB.SelectedItem; StartProtocolCB.SelectedItem = man.StartProtocol; this.ClientAddTB.Value = man.GetActiveAuthentication().ClientAddress; AuthenticationCB.Items.Clear(); foreach (GXAuthentication it in man.Settings) { int pos = AuthenticationCB.Items.Add(it); if (it.Type == Device.Authentication) { this.AuthenticationCB.SelectedIndex = pos; } } ServerAddressTypeCB.Items.Clear(); HDLCAddressType type = Device.HDLCAddressing; //If we are creating new device. if (Device.Name == null) { type = man.GetActiveServer().HDLCAddress; } foreach (GXServerAddress it in ((GXManufacturer)ManufacturerCB.SelectedItem).ServerSettings) { ServerAddressTypeCB.Items.Add(it); if (it.HDLCAddress == type) { ServerAddressTypeCB.SelectedItem = it; } } UpdateStartProtocol(); SecurityCB.SelectedItem = man.Security; if (man.SystemTitle != null || man.BlockCipherKey != null || man.AuthenticationKey != null) { SystemTitleTB.Text = GXCommon.ToHex(man.SystemTitle, true); BlockCipherKeyTB.Text = GXCommon.ToHex(man.BlockCipherKey, true); AuthenticationKeyTB.Text = GXCommon.ToHex(man.AuthenticationKey, true); if (!DeviceTab.TabPages.Contains(CipheringTab)) { DeviceTab.TabPages.Add(CipheringTab); if (DeviceTab.TabPages.Contains(SupportedServicesTab)) { DeviceTab.TabPages.Remove(SupportedServicesTab); DeviceTab.TabPages.Add(SupportedServicesTab); } } if (!IsPrintable(man.SystemTitle) || !IsPrintable(man.BlockCipherKey) || !IsPrintable(man.AuthenticationKey)) { AsciiRB.Enabled = false; } else { AsciiRB.Enabled = true; } } else if (DeviceTab.TabPages.Contains(CipheringTab)) { DeviceTab.TabPages.Remove(CipheringTab); } } catch (Exception Ex) { GXDLMS.Common.Error.ShowError(this, Ex); } }
static void Main(string[] args) { IGXMedia media = null; GXCommunicatation comm = null; try { TextWriter logFile = new StreamWriter(File.Open("LogFile.txt", FileMode.Create)); //////////////////////////////////////// //Handle command line parameters. String id = "", host = "", port = "", pw = ""; bool trace = false, iec = true; Authentication auth = Authentication.None; foreach (string it in args) { String item = it.Trim().ToLower(); if (string.Compare(item, "/u", true) == 0)//Update { //Get latest manufacturer settings from Gurux web server. GXManufacturerCollection.UpdateManufactureSettings(); } else if (item.StartsWith("/m="))//Manufacturer { id = item.Replace("/m=", ""); } else if (item.StartsWith("/h=")) //Host { host = item.Replace("/h=", ""); } else if (item.StartsWith("/p="))// TCP/IP Port { media = new Gurux.Net.GXNet(); port = item.Replace("/p=", ""); } else if (item.StartsWith("/sp="))//Serial Port { port = item.Replace("/sp=", ""); media = new GXSerial(); } else if (item.StartsWith("/t"))//Are messages traced. { trace = true; } else if (item.StartsWith("/s="))//Start { String tmp = item.Replace("/s=", ""); iec = string.Compare(tmp, "dlms", true) != 0; } else if (item.StartsWith("/a="))//Authentication { auth = (Authentication)Enum.Parse(typeof(Authentication), it.Trim().Replace("/a=", "")); } else if (item.StartsWith("/pw="))//Password { pw = it.Trim().Replace("/pw=", ""); } else { ShowHelp(); return; } } if (string.IsNullOrEmpty(id) || string.IsNullOrEmpty(port) || (media is GXNet && string.IsNullOrEmpty(host))) { ShowHelp(); return; } //////////////////////////////////////// //Initialize connection settings. if (media is GXSerial) { GXSerial serial = media as GXSerial; serial.PortName = port; if (iec) { serial.BaudRate = 300; serial.DataBits = 7; serial.Parity = System.IO.Ports.Parity.Even; serial.StopBits = System.IO.Ports.StopBits.One; } else { serial.BaudRate = 9600; serial.DataBits = 8; serial.Parity = System.IO.Ports.Parity.None; serial.StopBits = System.IO.Ports.StopBits.One; } } else if (media is GXNet) { Gurux.Net.GXNet net = media as GXNet; net.Port = Convert.ToInt32(port); net.HostName = host; net.Protocol = Gurux.Net.NetworkType.Tcp; } else { throw new Exception("Unknown media type."); } //////////////////////////////////////// //Update manufacturer depended settings. GXManufacturerCollection Manufacturers = new GXManufacturerCollection(); GXManufacturerCollection.ReadManufacturerSettings(Manufacturers); GXManufacturer man = Manufacturers.FindByIdentification(id); if (man == null) { throw new Exception("Unknown manufacturer: " + id); } GXDLMSClient dlms = new GXDLMSClient(); //Update Obis code list so we can get right descriptions to the objects. dlms.CustomObisCodes = man.ObisCodes; comm = new GXCommunicatation(dlms, media, iec, auth, pw); comm.Trace = trace; comm.InitializeConnection(man); GXDLMSObjectCollection objects = null; string path = host.Replace('.', '_') + "_" + port.ToString() + ".xml"; List <Type> extraTypes = new List <Type>(Gurux.DLMS.GXDLMSClient.GetObjectTypes()); extraTypes.Add(typeof(GXDLMSAttributeSettings)); extraTypes.Add(typeof(GXDLMSAttribute)); XmlSerializer x = new XmlSerializer(typeof(GXDLMSObjectCollection), extraTypes.ToArray()); //You can save association view, but make sure that it is not change. //Save Association view to the cache so it is not needed to retrieve every time. /* * if (File.Exists(path)) * { * try * { * using (Stream stream = File.Open(path, FileMode.Open)) * { * Console.WriteLine("Get available objects from the cache."); * objects = x.Deserialize(stream) as GXDLMSObjectCollection; * stream.Close(); * } * } * catch (Exception ex) * { * if (File.Exists(path)) * { * File.Delete(path); * } * throw ex; * } * } * else */ { Console.WriteLine("Get available objects from the device."); objects = comm.GetAssociationView(); GXDLMSObjectCollection objs = objects.GetObjects(new ObjectType[] { ObjectType.Register, ObjectType.ExtendedRegister, ObjectType.DemandRegister }); Console.WriteLine("Read scalers and units from the device."); Thread.Sleep(1000); foreach (GXDLMSObject it in objs) { if (it is GXDLMSRegister) { Console.WriteLine(it.Name); comm.Read(it, 3); } if (it is GXDLMSDemandRegister) { Console.WriteLine(it.Name); comm.Read(it, 4); } } Thread.Sleep(1000); //Read Profile Generic columns first. foreach (GXDLMSObject it in objects.GetObjects(ObjectType.ProfileGeneric)) { try { Console.WriteLine(it.Name); comm.Read(it, 3); GXDLMSObject[] cols = (it as GXDLMSProfileGeneric).GetCaptureObject(); TraceLine(logFile, "Profile Generic " + it.Name + " Columns:"); StringBuilder sb = new StringBuilder(); bool First = true; foreach (GXDLMSObject col in cols) { if (!First) { sb.Append(" | "); } First = false; sb.Append(col.Name); sb.Append(" "); sb.Append(col.Description); } TraceLine(logFile, sb.ToString()); } catch (Exception ex) { TraceLine(logFile, "Err! Failed to read columns:" + ex.Message); //Continue reading. } } try { using (Stream stream = File.Open(path, FileMode.Create)) { TextWriter writer = new StreamWriter(stream); x.Serialize(writer, objects); writer.Close(); stream.Close(); } } catch (Exception ex) { if (File.Exists(path)) { File.Delete(path); } throw ex; } Console.WriteLine("--- Available objects ---"); foreach (GXDLMSObject it in objects) { Console.WriteLine(it.Name + " " + it.Description); } } Thread.Sleep(1000); foreach (GXDLMSObject it in objects) { // Profile generics are read later because they are special cases. // (There might be so lots of data and we so not want waste time to read all the data.) if (it is GXDLMSProfileGeneric) { continue; } if (!(it is IGXDLMSBase)) { //If interface is not implemented. //Example manufacturer spesific interface. Console.WriteLine("Unknown Interface: " + it.ObjectType.ToString()); continue; } TraceLine(logFile, "-------- Reading " + it.GetType().Name + " " + it.Name + " " + it.Description); foreach (int pos in (it as IGXDLMSBase).GetAttributeIndexToRead()) { try { object val = comm.Read(it, pos); //If data is array. if (val is byte[]) { val = GXCommon.ToHex((byte[])val, true); } else if (val is Array) { string str = ""; for (int pos2 = 0; pos2 != (val as Array).Length; ++pos2) { if (str != "") { str += ", "; } if ((val as Array).GetValue(pos2) is byte[]) { str += GXCommon.ToHex((byte[])(val as Array).GetValue(pos2), true); } else { str += (val as Array).GetValue(pos2).ToString(); } } val = str; } else if (val is System.Collections.IList) { string str = "["; bool empty = true; foreach (object it2 in val as System.Collections.IList) { if (!empty) { str += ", "; } empty = false; if (it2 is byte[]) { str += GXCommon.ToHex((byte[])it2, true); } else { str += it2.ToString(); } } str += "]"; val = str; } TraceLine(logFile, "Index: " + pos + " Value: " + val); } catch (Exception ex) { TraceLine(logFile, "Error! Index: " + pos + " " + ex.Message); } } } Thread.Sleep(1000); //Find profile generics and read them. foreach (GXDLMSObject it in objects.GetObjects(ObjectType.ProfileGeneric)) { TraceLine(logFile, "-------- Reading " + it.GetType().Name + " " + it.Name + " " + it.Description); long entriesInUse = Convert.ToInt64(comm.Read(it, 7)); long entries = Convert.ToInt64(comm.Read(it, 8)); TraceLine(logFile, "Entries: " + entriesInUse + "/" + entries); //If there are no columns or rows. if (entriesInUse == 0 || (it as GXDLMSProfileGeneric).CaptureObjects.Count == 0) { continue; } try { //Read first row from Profile Generic. object[] rows = comm.ReadRowsByEntry(it as GXDLMSProfileGeneric, 0, 1); StringBuilder sb = new StringBuilder(); foreach (object[] row in rows) { foreach (object cell in row) { if (cell is byte[]) { sb.Append(GXCommon.ToHex((byte[])cell, true)); } else { sb.Append(Convert.ToString(cell)); } sb.Append(" | "); } sb.Append("\r\n"); } Trace(logFile, sb.ToString()); } catch (Exception ex) { TraceLine(logFile, "Error! Failed to read first row: " + ex.Message); //Continue reading. } try { //Read last day from Profile Generic. object[] rows = comm.ReadRowsByRange(it as GXDLMSProfileGeneric, DateTime.Now.Date, DateTime.MaxValue); StringBuilder sb = new StringBuilder(); foreach (object[] row in rows) { foreach (object cell in row) { if (cell is byte[]) { sb.Append(GXCommon.ToHex((byte[])cell, true)); } else { sb.Append(Convert.ToString(cell)); } sb.Append(" | "); } sb.Append("\r\n"); } Trace(logFile, sb.ToString()); } catch (Exception ex) { TraceLine(logFile, "Error! Failed to read last day: " + ex.Message); //Continue reading. } } logFile.Flush(); logFile.Close(); } catch (Exception ex) { if (comm != null) { comm.Close(); } Console.WriteLine(ex.Message); if (!System.Diagnostics.Debugger.IsAttached) { Console.ReadKey(); } } finally { if (comm != null) { comm.Close(); } if (System.Diagnostics.Debugger.IsAttached) { Console.WriteLine("Ended. Press any key to continue."); Console.ReadKey(); } } }
public void InitializeConnection(GXManufacturer man) { Manufacturer = man; UpdateManufactureSettings(man.Identification); if (Media is GXSerial) { Console.WriteLine("Initializing serial connection."); InitSerial(); } else if (Media is GXNet) { Console.WriteLine("Initializing Network connection."); InitNet(); //Some Electricity meters need some time before first message can be send. System.Threading.Thread.Sleep(500); } else { throw new Exception("Unknown media type."); } GXReplyData reply = new GXReplyData(); byte[] data; data = Client.SNRMRequest(); if (data != null) { if (Trace) { Console.WriteLine("Send SNRM request." + GXCommon.ToHex(data, true)); } ReadDLMSPacket(data, reply); if (Trace) { Console.WriteLine("Parsing UA reply." + reply.ToString()); } //Has server accepted client. Client.ParseUAResponse(reply.Data); Console.WriteLine("Parsing UA reply succeeded."); } //Generate AARQ request. //Split requests to multiple packets if needed. //If password is used all data might not fit to one packet. reply.Clear(); ReadDataBlock(Client.AARQRequest(), reply); try { //Parse reply. Client.ParseAAREResponse(reply.Data); reply.Clear(); } catch (Exception Ex) { reply.Clear(); ReadDLMSPacket(Client.DisconnectRequest(), reply); throw Ex; } //Get challenge Is HLS authentication is used. if (Client.IsAuthenticationRequired) { foreach (byte[] it in Client.GetApplicationAssociationRequest()) { reply.Clear(); ReadDLMSPacket(it, reply); } Client.ParseApplicationAssociationResponse(reply.Data); } Console.WriteLine("Parsing AARE reply succeeded."); }
/// <summary> /// Apply new settings from property pages. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void OKBtn_Click(object sender, EventArgs e) { try { string name = NameTB.Text.Trim(); if (name.Length == 0) { throw new Exception("Invalid name."); } GXServerAddress server = (GXServerAddress)ServerAddressTypeCB.SelectedItem; if (server.HDLCAddress == HDLCAddressType.SerialNumber && PhysicalServerAddressTB.Value == 0) { throw new Exception("Invalid Serial Number."); } GXManufacturer man = (GXManufacturer)ManufacturerCB.SelectedItem; Device.Authentication = ((GXAuthentication)this.AuthenticationCB.SelectedItem).Type; if (Device.Authentication != Authentication.None) { Device.Password = CryptHelper.Encrypt(this.PasswordTB.Text, Password.Key); } else { Device.Password = ""; } Device.Name = name; Device.Media = SelectedMedia; Device.Manufacturer = man.Identification; Device.WaitTime = Convert.ToInt32(WaitTimeTB.Value); Device.Verbose = VerboseModeCB.Checked; Device.MaximumBaudRate = 0; Device.UtcTimeZone = UseUtcTimeZone.Checked; if (SelectedMedia is GXSerial) { Device.UseRemoteSerial = false; if (this.SerialPortCB.Text.Length == 0) { throw new Exception("Invalid serial port."); } ((GXSerial)SelectedMedia).PortName = this.SerialPortCB.Text; if (UseMaximumBaudRateCB.Checked) { Device.MaximumBaudRate = (int)MaximumBaudRateCB.SelectedItem; } } else if (SelectedMedia is GXNet) { if (this.HostNameTB.Text.Length == 0) { throw new Exception("Invalid host name."); } ((GXNet)SelectedMedia).HostName = this.HostNameTB.Text; int port; if (!Int32.TryParse(this.PortTB.Text, out port)) { throw new Exception("Invalid port number."); } ((GXNet)SelectedMedia).Port = port; Device.UseRemoteSerial = UseRemoteSerialCB.Checked; ((GXNet)SelectedMedia).Protocol = (NetworkType)NetProtocolCB.SelectedItem; } else if (SelectedMedia is Gurux.Terminal.GXTerminal) { if (this.TerminalPortCB.Text.Length == 0) { throw new Exception("Invalid serial port."); } if (this.TerminalPhoneNumberTB.Text.Length == 0) { throw new Exception("Invalid phone number."); } Gurux.Terminal.GXTerminal terminal = SelectedMedia as Gurux.Terminal.GXTerminal; terminal.ConfigurableSettings = Gurux.Terminal.AvailableMediaSettings.All & ~Gurux.Terminal.AvailableMediaSettings.Server; Device.UseRemoteSerial = false; terminal.PortName = this.TerminalPortCB.Text; terminal.PhoneNumber = this.TerminalPhoneNumberTB.Text; } GXAuthentication authentication = (GXAuthentication)AuthenticationCB.SelectedItem; Device.HDLCAddressing = ((GXServerAddress)ServerAddressTypeCB.SelectedItem).HDLCAddress; Device.ClientAddress = Convert.ToInt32(ClientAddTB.Value); if (Device.HDLCAddressing == HDLCAddressType.SerialNumber) { Device.PhysicalAddress = PhysicalServerAddressTB.Value; } else { Device.PhysicalAddress = Convert.ChangeType(PhysicalServerAddressTB.Value, server.PhysicalAddress.GetType()); } Device.UseLogicalNameReferencing = this.UseLNCB.Checked; Device.LogicalAddress = Convert.ToInt32(LogicalServerAddressTB.Value); Device.StartProtocol = (StartProtocolType)this.StartProtocolCB.SelectedItem; GXDLMSDirector.Properties.Settings.Default.SelectedManufacturer = man.Name; Device.Security = (Security)SecurityCB.SelectedItem; Device.SystemTitle = SystemTitleTB.Text; Device.BlockCipherKey = BlockCipherKeyTB.Text; Device.AuthenticationKey = AuthenticationKeyTB.Text; } catch (Exception Ex) { this.DialogResult = DialogResult.None; GXDLMS.Common.Error.ShowError(this, Ex); } }
public ManufacturerForm(GXManufacturerCollection manufacturers, GXManufacturer manufacturer) { InitializeComponent(); #if !GURUX_LPWAN LpWanCb.Visible = WiSunCb.Visible = false; #endif //GURUX_LPWAN foreach (object it in Enum.GetValues(typeof(Standard))) { StandardCb.Items.Add(it); } StandardCb.SelectedItem = manufacturer.Standard; SecurityCB.Items.AddRange(new object[] { Security.None, Security.Authentication, Security.Encryption, Security.AuthenticationEncryption }); Manufacturers = manufacturers; Manufacturer = manufacturer; if (manufacturer.Settings.Count == 0) { manufacturer.Settings.Add(new GXAuthentication(Authentication.None, (byte)0x10)); manufacturer.Settings.Add(new GXAuthentication(Authentication.Low, (byte)0x11)); manufacturer.Settings.Add(new GXAuthentication(Authentication.High, (byte)0x12)); manufacturer.Settings.Add(new GXAuthentication(Authentication.HighMD5, (byte)0x13)); manufacturer.Settings.Add(new GXAuthentication(Authentication.HighSHA1, (byte)0x14)); manufacturer.Settings.Add(new GXAuthentication(Authentication.HighGMAC, (byte)0x14)); manufacturer.Settings.Add(new GXAuthentication(Authentication.HighSHA256, (byte)0x14)); manufacturer.Settings.Add(new GXAuthentication(Authentication.HighECDSA, (byte)0x14)); GXAuthentication gmac = new GXAuthentication(Authentication.HighGMAC, (byte)0x15); } GXAuthentication authentication = manufacturer.GetActiveAuthentication(); foreach (GXAuthentication it in manufacturer.Settings) { AuthenticationCB.Items.Add(it); } AuthenticationCB.SelectedItem = authentication; this.AuthenticationCB.SelectedIndexChanged += new System.EventHandler(this.AuthenticationCB_SelectedIndexChanged); if (manufacturer.ServerSettings.Count == 0) { manufacturer.ServerSettings.Add(new GXServerAddress(HDLCAddressType.Default, (byte)1, true)); manufacturer.ServerSettings.Add(new GXServerAddress(HDLCAddressType.SerialNumber, (byte)1, false)); manufacturer.ServerSettings.Add(new GXServerAddress(HDLCAddressType.Custom, (byte)1, false)); } foreach (GXServerAddress it in manufacturer.ServerSettings) { ServerAddressTypeCB.Items.Add(it); } GXServerAddress server = manufacturer.GetActiveServer(); ServerAddressTypeCB.SelectedItem = server; RefreshServer(server); this.ServerAddressTypeCB.SelectedIndexChanged += new System.EventHandler(this.ServerAddressTypeCB_SelectedIndexChanged); ServerAddressTypeCB.DrawMode = AuthenticationCB.DrawMode = DrawMode.OwnerDrawFixed; ClientAddTB.Value = authentication.ClientAddress; NameTB.Text = manufacturer.Name; ManufacturerIdTB.Text = manufacturer.Identification; UseLNCB.Checked = manufacturer.UseLogicalNameReferencing; //Manufacturer ID can not change after creation. ManufacturerIdTB.Enabled = string.IsNullOrEmpty(manufacturer.Identification); WebAddressTB.Text = Manufacturer.WebAddress; if (!string.IsNullOrEmpty(Manufacturer.Info)) { try { InfoTB.Text = ASCIIEncoding.UTF8.GetString(Convert.FromBase64String(Manufacturer.Info)); } catch (Exception) { InfoTB.Text = ""; } } SecurityCB.SelectedItem = manufacturer.Security; if (DevicePropertiesForm.IsAscii(manufacturer.SystemTitle)) { SystemTitleAsciiCb.Checked = true; SystemTitleTB.Text = ASCIIEncoding.ASCII.GetString((manufacturer.SystemTitle)); } else { SystemTitleTB.Text = GXCommon.ToHex(manufacturer.SystemTitle, true); } if (DevicePropertiesForm.IsAscii(manufacturer.BlockCipherKey)) { BlockCipherKeyAsciiCb.Checked = true; BlockCipherKeyTB.Text = ASCIIEncoding.ASCII.GetString(manufacturer.BlockCipherKey); } else { BlockCipherKeyTB.Text = GXCommon.ToHex(manufacturer.BlockCipherKey, true); } if (DevicePropertiesForm.IsAscii(manufacturer.AuthenticationKey)) { AuthenticationKeyAsciiCb.Checked = true; AuthenticationKeyTB.Text = ASCIIEncoding.ASCII.GetString(manufacturer.AuthenticationKey); } else { AuthenticationKeyTB.Text = GXCommon.ToHex(manufacturer.AuthenticationKey, true); } UseUtcTimeZone.Checked = manufacturer.UtcTimeZone; if (manufacturer.SupporterdInterfaces != 0) { HdlcCb.Checked = (manufacturer.SupporterdInterfaces & (1 << (int)InterfaceType.HDLC)) != 0; HdlcWithModeECb.Checked = (manufacturer.SupporterdInterfaces & (1 << (int)InterfaceType.HdlcWithModeE)) != 0; WrapperCb.Checked = (manufacturer.SupporterdInterfaces & (1 << (int)InterfaceType.WRAPPER)) != 0; WirelessMBusCb.Checked = (manufacturer.SupporterdInterfaces & (1 << (int)InterfaceType.WirelessMBus)) != 0; PlcCb.Checked = (manufacturer.SupporterdInterfaces & (1 << (int)InterfaceType.Plc)) != 0; PlcHdlcCb.Checked = (manufacturer.SupporterdInterfaces & (1 << (int)InterfaceType.PlcHdlc)) != 0; LpWanCb.Checked = (manufacturer.SupporterdInterfaces & (1 << (int)InterfaceType.LPWAN)) != 0; WiSunCb.Checked = (manufacturer.SupporterdInterfaces & (1 << (int)InterfaceType.WiSUN)) != 0; } else { //Select default interfaces. HdlcCb.Checked = HdlcWithModeECb.Checked = WrapperCb.Checked = true; } }