public bool TargetChanged(object target) { GXDLMSDevice dev = GetDevice(target); if ((running || Record) && Target != dev) { return(false); } Target = dev; return(true); }
private void CreateDeviceMnu_Click(object sender, EventArgs e) { try { if (MetersView.SelectedItems.Count == 1) { ListViewItem li = MetersView.SelectedItems[0]; GXDLMSPlcMeterInfo mi = (GXDLMSPlcMeterInfo)li.Tag; GXDLMSDevice dev = new GXDLMSDevice(); //Set empty name or new device is created. dev.Name = ""; if (media is GXNet) { dev.Media = new GXNet(); } else if (media is GXSerial) { dev.Media = new GXSerial(); } dev.Media.Settings = media.Settings; if (!string.IsNullOrEmpty(Settings.Default.SelectedManufacturer)) { foreach (var it in _parent.Manufacturers) { if (it.Name == Settings.Default.SelectedManufacturer) { dev.Manufacturer = it.Identification; dev.UseLogicalNameReferencing = it.UseLogicalNameReferencing; break; } } } if (string.IsNullOrEmpty(dev.Manufacturer)) { //Select Gurux as default manufacturer. dev.Manufacturer = "grx"; dev.UseLogicalNameReferencing = true; } dev.Conformance = (int)GXDLMSClient.GetInitialConformance(dev.UseLogicalNameReferencing); dev.MacDestinationAddress = mi.SourceAddress; dev.MACSourceAddress = mi.DestinationAddress; dev.InterfaceType = (InterfaceType)Settings.Default.PlcInterface; _parent.AddDevice(dev); } } catch (Exception ex) { MessageBox.Show(_parent, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
/// <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> /// Register selected meters. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void RegisterMnu_Click(object sender, EventArgs e) { try { if (MetersView.SelectedItems.Count == 1) { ListViewItem li = MetersView.SelectedItems[0]; GXDLMSPlcMeterInfo mi = (GXDLMSPlcMeterInfo)li.Tag; GXPlcRegisterDlg dlg = new GXPlcRegisterDlg(GXDLMSTranslator.HexToBytes(Settings.Default.PlcSerialSettingsActiveInitiator), mi.SystemTitle); if (dlg.ShowDialog(this) == DialogResult.OK) { GXDLMSDevice dev = new GXDLMSDevice(media); dev.Comm.client.InterfaceType = (InterfaceType)Settings.Default.PlcInterface; media.Open(); GXReplyData reply = new GXReplyData(); dev.Comm.client.Plc.MacSourceAddress = dlg.MacAddress; Settings.Default.PlcSerialSettingsActiveInitiator = GXDLMSTranslator.ToHex(dlg.ActiveInitiatorSystemTitle); byte[] data = dev.Comm.client.Plc.RegisterRequest(dlg.ActiveInitiatorSystemTitle, dlg.NewSystemTitle); dev.Comm.ReadDLMSPacket(data, reply); data = dev.Comm.client.Plc.DiscoverRequest(); dev.Comm.ReadDLMSPacket(data, reply); } } } catch (Exception ex) { MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { try { media.Close(); } catch (Exception ex) { MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } }
private static GXDLMSDevice GetDevice(object target) { GXDLMSDevice dev = null; if (target is GXDLMSDeviceCollection) { dev = null; } else if (target is GXDLMSDevice) { dev = target as GXDLMSDevice; } else if (target is GXDLMSObject) { dev = (target as GXDLMSObject).Parent.Tag as GXDLMSDevice; } else if (target is GXDLMSObjectCollection) { dev = (target as GXDLMSObjectCollection).Tag as GXDLMSDevice; } return(dev); }
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 RefreshDevice(GXDLMSDevice dev, bool bRefresh) { try { if (bRefresh) { dev.KeepAliveStop(); } TreeNode deviceNode = (TreeNode)ObjectTreeItems[dev]; if (bRefresh) { OnProgress(dev, "Refresh device", 0, 1); UpdateTransaction(true); RemoveObject(dev); while (dev.Objects.Count != 0) { RemoveObject(dev.Objects[0]); } GXManufacturer m = Manufacturers.FindByIdentification(dev.Manufacturer); dev.ObisCodes = m.ObisCodes; //Walk through object tree. dev.UpdateObjects(); //Read registers units and scalers. int cnt = dev.Objects.Count; GXLogWriter.WriteLog("--- Reading scalers and units. ---"); for (int pos = 0; pos != cnt; ++pos) { GXDLMSObject it = dev.Objects[pos]; GXObisCode obj = m.ObisCodes.FindByLN(it.ObjectType, it.LogicalName, null); if (obj != null) { UpdateFromObisCode(it, obj); } else { continue; } } GXLogWriter.WriteLog("--- Reading scalers and units end. ---"); /* TODO: if (!m.UseLogicalNameReferencing) { GXLogWriter.WriteLog("--- Reading Access rights. ---"); try { foreach (GXDLMSAssociationShortName sn in dev.Objects.GetObjects(ObjectType.AssociationShortName)) { dev.Comm.Read(sn, 3); } } catch (Exception ex) { GXLogWriter.WriteLog(ex.Message); } GXLogWriter.WriteLog("--- Reading Access rights end. ---"); } * */ this.OnProgress(dev, "Reading scalers and units.", cnt, cnt); GroupItems(GroupsMnu.Checked); } } catch (ThreadAbortException) { //User has cancel action. Do nothing. } catch (Exception Ex) { throw Ex; } finally { if (bRefresh) { dev.KeepAliveStart(); UpdateTransaction(false); } } }
private bool CheckSnrm(GXDLMSDevice dev, int count, bool reset) { if (media.IsOpen) { List <int> serverAddresses = new List <int>(); //Management Logical Device address. serverAddresses.Add(1); //One byte broadcast address. serverAddresses.Add(0x7f); //Two byte broadcast address. serverAddresses.Add(0x3FFF); BeginInvoke(new ResetProgressEventHandler(OnResetProgress), count * serverAddresses.Count, reset); foreach (int address in serverAddresses) { BeginInvoke(new IncreaseProgressEventHandler(OnIncreaseProgress)); BeginInvoke(new AppendTextEventHandler(OnAppendText), "Try with server address " + address + " (0x" + address.ToString("X") + ")" + Environment.NewLine); dev.Comm.client.ClientAddress = 16; dev.Comm.client.ServerAddress = address; byte[] data = dev.Comm.client.SNRMRequest(); GXReplyData reply = new GXReplyData(); try { //Accept all data. dev.Comm.client.ClientAddress = 0; dev.Comm.client.ServerAddress = 0x7f; dev.Comm.ReadDataBlock(data, "Send SNRM request.", 0, 0, reply); if (media is GXSerial) { BeginInvoke(new AppendTextEventHandler(OnAppendText), "++++++++++++++++++++++++++++++++++++" + Environment.NewLine + "Used baud rate: " + (media as GXSerial).BaudRate + Environment.NewLine + "Client address: " + reply.ClientAddress + " (0x" + reply.ClientAddress.ToString("X") + ")" + Environment.NewLine + "Server address: " + reply.ServerAddress + " (0x" + reply.ServerAddress.ToString("X") + ")" + Environment.NewLine); } else { BeginInvoke(new AppendTextEventHandler(OnAppendText), "++++++++++++++++++++++++++++++++++++" + Environment.NewLine + "Client address: " + reply.ClientAddress + " (0x" + reply.ClientAddress.ToString("X") + ")" + Environment.NewLine + "Server address: " + reply.ServerAddress + " (0x" + reply.ServerAddress.ToString("X") + ")" + Environment.NewLine); } return(true); } catch (TimeoutException) { reply.Clear(); try { dev.Comm.ReadDataBlock(dev.Comm.client.DisconnectRequest(true), "Send Disconnect request.", 0, 0, reply); } catch (Exception) { reply.Clear(); } } catch (Exception) { reply.Clear(); try { dev.Comm.ReadDataBlock(dev.Comm.client.DisconnectRequest(true), "Send Disconnect request.", 0, 0, reply); } catch (Exception) { reply.Clear(); } } if (!media.IsOpen) { break; } } } return(false); }
public GXDLMSCommunicator(GXDLMSDevice parent, Gurux.Common.IGXMedia media) { Parent = parent; Media = media; m_Cosem = new Gurux.DLMS.GXDLMSClient(); }
public DevicePropertiesForm(GXManufacturerCollection manufacturers, GXDLMSDevice dev) { try { InitializeComponent(); SecurityCB.Items.AddRange(new object[] { Security.None, Security.Authentication, Security.Encryption, Security.AuthenticationEncryption }); NetProtocolCB.Items.AddRange(new object[] { NetworkType.Tcp, NetworkType.Udp }); this.ServerAddressTypeCB.SelectedIndexChanged += new System.EventHandler(this.ServerAddressTypeCB_SelectedIndexChanged); NetworkSettingsGB.Width = this.Width - NetworkSettingsGB.Left; SerialSettingsGB.Bounds = TerminalSettingsGB.Bounds = NetworkSettingsGB.Bounds; ServerAddressTypeCB.DrawMode = AuthenticationCB.DrawMode = DrawMode.OwnerDrawFixed; Manufacturers = manufacturers; //OK button is not enabled if there are no manufacturers. if (Manufacturers.Count == 0) { OKBtn.Enabled = false; } //Show supported services tab only when they are read. if (dev == null || dev.Comm.client.SNSettings == null && dev.Comm.client.LNSettings == null) { DeviceTab.TabPages.Remove(SupportedServicesTab); } else { object settings = null; if (dev.Comm.client.UseLogicalNameReferencing) { settings = dev.Comm.client.LNSettings; } else { settings = dev.Comm.client.SNSettings; } if (settings != null) { SupportedServicesGrid.SelectedObject = settings; foreach (PropertyDescriptor it in TypeDescriptor.GetProperties(settings)) { ReadOnlyAttribute att = (ReadOnlyAttribute)it.Attributes[typeof(ReadOnlyAttribute)]; if (att != null) { FieldInfo[] f = att.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance); f[0].SetValue(att, true); } } } } Device = dev; StartProtocolCB.Items.Add(StartProtocolType.IEC); StartProtocolCB.Items.Add(StartProtocolType.DLMS); int pos = 0; foreach (GXManufacturer it in Manufacturers) { int index = this.ManufacturerCB.Items.Add(it); if (it.Name == GXDLMSDirector.Properties.Settings.Default.SelectedManufacturer) { pos = index; } } if (Device == null) { Device = new GXDLMSDevice(null); //Select first manufacturer. if (Manufacturers.Count != 0) { ManufacturerCB.SelectedIndex = pos; } } else { foreach (GXManufacturer it in this.ManufacturerCB.Items) { if (string.Compare(it.Identification, Device.Manufacturer, true) == 0) { this.ManufacturerCB.SelectedItem = it; break; } } this.VerboseModeCB.Checked = dev.Verbose; this.NameTB.Text = dev.Name; SelectedMedia = dev.Media; UseRemoteSerialCB.Checked = Device.UseRemoteSerial; StartProtocolCB.SelectedItem = Device.StartProtocol; PhysicalServerAddressTB.Value = Convert.ToDecimal(Device.PhysicalAddress); LogicalServerAddressTB.Value = Convert.ToDecimal(Device.LogicalAddress); this.ClientAddTB.Value = Convert.ToDecimal(Convert.ToUInt32(Device.ClientAddress)); WaitTimeTB.Value = Device.WaitTime; SecurityCB.SelectedItem = dev.Security; SystemTitleTB.Text = dev.SystemTitle; BlockCipherKeyTB.Text = dev.BlockCipherKey; AuthenticationKeyTB.Text = dev.AuthenticationKey; UseUtcTimeZone.Checked = Device.UtcTimeZone; } ManufacturerCB.DrawMode = MediasCB.DrawMode = DrawMode.OwnerDrawFixed; Gurux.Net.GXNet net = new Gurux.Net.GXNet(); //Initialize network settings. if (SelectedMedia is GXNet) { this.MediasCB.Items.Add(SelectedMedia); net.Protocol = Gurux.Net.NetworkType.Tcp; this.HostNameTB.Text = ((GXNet)SelectedMedia).HostName; this.PortTB.Text = ((GXNet)SelectedMedia).Port.ToString(); NetProtocolCB.SelectedItem = ((GXNet)SelectedMedia).Protocol; } else { NetProtocolCB.SelectedItem = net.Protocol = Gurux.Net.NetworkType.Tcp; this.MediasCB.Items.Add(net); } //Set maximum baud rate. GXSerial serial = new GXSerial(); foreach (int it in serial.GetAvailableBaudRates("")) { if (it != 0) { MaximumBaudRateCB.Items.Add(it); } } if (Device.MaximumBaudRate == 0) { UseMaximumBaudRateCB.Checked = false; UseMaximumBaudRateCB_CheckedChanged(null, null); } else { UseMaximumBaudRateCB.Checked = true; this.MaximumBaudRateCB.SelectedItem = Device.MaximumBaudRate; } if (SelectedMedia is GXSerial) { this.MediasCB.Items.Add(SelectedMedia); string[] ports = GXSerial.GetPortNames(); this.SerialPortCB.Items.AddRange(ports); if (ports.Length != 0) { this.SerialPortCB.SelectedItem = ((GXSerial)SelectedMedia).PortName; } } else { //Initialize serial settings. string[] ports = GXSerial.GetPortNames(); this.SerialPortCB.Items.AddRange(ports); if (ports.Length != 0) { serial.PortName = ports[0]; } if (((GXManufacturer)ManufacturerCB.SelectedItem).StartProtocol == StartProtocolType.DLMS) { serial.BaudRate = 9600; serial.DataBits = 8; serial.Parity = Parity.None; serial.StopBits = StopBits.One; } else { serial.BaudRate = 300; serial.DataBits = 7; serial.Parity = Parity.Even; serial.StopBits = StopBits.One; } this.MediasCB.Items.Add(serial); } if (SelectedMedia is Gurux.Terminal.GXTerminal) { this.MediasCB.Items.Add(SelectedMedia); string[] ports = GXTerminal.GetPortNames(); this.TerminalPortCB.Items.AddRange(ports); if (ports.Length != 0) { this.TerminalPortCB.SelectedItem = ((Gurux.Terminal.GXTerminal)SelectedMedia).PortName; } this.TerminalPhoneNumberTB.Text = ((Gurux.Terminal.GXTerminal)SelectedMedia).PhoneNumber; } else { //Initialize terminal settings. Gurux.Terminal.GXTerminal termial = new Gurux.Terminal.GXTerminal(); string[] ports = GXTerminal.GetPortNames(); this.TerminalPortCB.Items.AddRange(ports); if (ports.Length != 0) { termial.PortName = ports[0]; } termial.BaudRate = 9600; termial.DataBits = 8; termial.Parity = Parity.None; termial.StopBits = StopBits.One; this.TerminalPhoneNumberTB.Text = termial.PhoneNumber; //termial.InitializeCommands = "AT+CBST=71,0,1\r\n"; this.MediasCB.Items.Add(termial); } //Select first media if medis is not selected. if (SelectedMedia == null) { SelectedMedia = (Gurux.Common.IGXMedia) this.MediasCB.Items[0]; } this.MediasCB.SelectedItem = SelectedMedia; if (!string.IsNullOrEmpty(Device.Password)) { this.PasswordTB.Text = ASCIIEncoding.ASCII.GetString(CryptHelper.Decrypt(Device.Password, Password.Key)); } if (dev != null) { this.UseLNCB.Checked = dev.UseLogicalNameReferencing; } this.AuthenticationCB.SelectedIndexChanged += new System.EventHandler(this.AuthenticationCB_SelectedIndexChanged); bool bConnected = Device.Media != null && Device.Media.IsOpen; SerialPortCB.Enabled = AdvancedBtn.Enabled = ManufacturerCB.Enabled = MediasCB.Enabled = AuthenticationCB.Enabled = UseRemoteSerialCB.Enabled = OKBtn.Enabled = !bConnected; HostNameTB.ReadOnly = PortTB.ReadOnly = PasswordTB.ReadOnly = WaitTimeTB.ReadOnly = PhysicalServerAddressTB.ReadOnly = NameTB.ReadOnly = bConnected; } catch (Exception Ex) { GXDLMS.Common.Error.ShowError(this, Ex); } }
public DevicePropertiesForm(GXManufacturerCollection manufacturers, GXDLMSDevice dev) { try { InitializeComponent(); NetProtocolCB.Items.AddRange(new object[] { NetworkType.Tcp, NetworkType.Udp }); this.ServerAddressTypeCB.SelectedIndexChanged += new System.EventHandler(this.ServerAddressTypeCB_SelectedIndexChanged); NetworkSettingsGB.Width = this.Width - NetworkSettingsGB.Left; SerialSettingsGB.Bounds = TerminalSettingsGB.Bounds = NetworkSettingsGB.Bounds; ServerAddressTypeCB.DrawMode = AuthenticationCB.DrawMode = DrawMode.OwnerDrawFixed; Manufacturers = manufacturers; //OK button is not enabled if there are no manufacturers. if (Manufacturers.Count == 0) { OKBtn.Enabled = false; } //Show supported services tab only when they are read. if (dev == null || dev.Comm.client.SNSettings == null && dev.Comm.client.LNSettings == null) { DeviceTab.TabPages.Remove(SupportedServicesTab); } else { object settings = null; if (dev.Comm.client.UseLogicalNameReferencing) { settings = dev.Comm.client.LNSettings; } else { settings = dev.Comm.client.SNSettings; } if (settings != null) { SupportedServicesGrid.SelectedObject = settings; foreach (PropertyDescriptor it in TypeDescriptor.GetProperties(settings)) { ReadOnlyAttribute att = (ReadOnlyAttribute)it.Attributes[typeof(ReadOnlyAttribute)]; if (att != null) { FieldInfo[] f = att.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance); f[0].SetValue(att, true); } } } } Device = dev; StartProtocolCB.Items.Add(StartProtocolType.IEC); StartProtocolCB.Items.Add(StartProtocolType.DLMS); int pos = 0; foreach (GXManufacturer it in Manufacturers) { int index = this.ManufacturerCB.Items.Add(it); if (it.Name == GXDLMSDirector.Properties.Settings.Default.SelectedManufacturer) { pos = index; } } if (Device == null) { Device = new GXDLMSDevice(null); //Select first manufacturer. if (Manufacturers.Count != 0) { ManufacturerCB.SelectedIndex = pos; } } else { foreach (GXManufacturer it in this.ManufacturerCB.Items) { if (string.Compare(it.Identification, Device.Manufacturer, true) == 0) { this.ManufacturerCB.SelectedItem = it; break; } } this.VerboseModeCB.Checked = dev.Verbose; this.NameTB.Text = dev.Name; SelectedMedia = dev.Media; UseRemoteSerialCB.Checked = Device.UseRemoteSerial; StartProtocolCB.SelectedItem = Device.StartProtocol; PhysicalServerAddressTB.Value = Convert.ToDecimal(Device.PhysicalAddress); LogicalServerAddressTB.Value = Convert.ToDecimal(Device.LogicalAddress); this.ClientAddTB.Value = Convert.ToDecimal(Convert.ToUInt32(Device.ClientAddress)); WaitTimeTB.Value = Device.WaitTime; } ManufacturerCB.DrawMode = MediasCB.DrawMode = DrawMode.OwnerDrawFixed; Gurux.Net.GXNet net = new Gurux.Net.GXNet(); //Initialize network settings. if (SelectedMedia is GXNet) { this.MediasCB.Items.Add(SelectedMedia); net.Protocol = Gurux.Net.NetworkType.Tcp; this.HostNameTB.Text = ((GXNet)SelectedMedia).HostName; this.PortTB.Text = ((GXNet)SelectedMedia).Port.ToString(); NetProtocolCB.SelectedItem = ((GXNet)SelectedMedia).Protocol; } else { NetProtocolCB.SelectedItem = net.Protocol = Gurux.Net.NetworkType.Tcp; this.MediasCB.Items.Add(net); } //Set maximum baud rate. GXSerial serial = new GXSerial(); foreach (int it in serial.GetAvailableBaudRates("")) { if (it != 0) { MaximumBaudRateCB.Items.Add(it); } } if (Device.MaximumBaudRate == 0) { UseMaximumBaudRateCB.Checked = false; UseMaximumBaudRateCB_CheckedChanged(null, null); } else { UseMaximumBaudRateCB.Checked = true; this.MaximumBaudRateCB.SelectedItem = Device.MaximumBaudRate; } if (SelectedMedia is GXSerial) { this.MediasCB.Items.Add(SelectedMedia); string[] ports = GXSerial.GetPortNames(); this.SerialPortCB.Items.AddRange(ports); if (ports.Length != 0) { this.SerialPortCB.SelectedItem = ((GXSerial)SelectedMedia).PortName; } } else { //Initialize serial settings. string[] ports = GXSerial.GetPortNames(); this.SerialPortCB.Items.AddRange(ports); if (ports.Length != 0) { serial.PortName = ports[0]; } if (((GXManufacturer)ManufacturerCB.SelectedItem).StartProtocol == StartProtocolType.DLMS) { serial.BaudRate = 9600; serial.DataBits = 8; serial.Parity = Parity.None; serial.StopBits = StopBits.One; } else { serial.BaudRate = 300; serial.DataBits = 7; serial.Parity = Parity.Even; serial.StopBits = StopBits.One; } this.MediasCB.Items.Add(serial); } if (SelectedMedia is Gurux.Terminal.GXTerminal) { this.MediasCB.Items.Add(SelectedMedia); string[] ports = GXTerminal.GetPortNames(); this.TerminalPortCB.Items.AddRange(ports); if (ports.Length != 0) { this.TerminalPortCB.SelectedItem = ((Gurux.Terminal.GXTerminal)SelectedMedia).PortName; } this.TerminalPhoneNumberTB.Text = ((Gurux.Terminal.GXTerminal)SelectedMedia).PhoneNumber; } else { //Initialize terminal settings. Gurux.Terminal.GXTerminal termial = new Gurux.Terminal.GXTerminal(); string[] ports = GXTerminal.GetPortNames(); this.TerminalPortCB.Items.AddRange(ports); if (ports.Length != 0) { termial.PortName = ports[0]; } termial.BaudRate = 9600; termial.DataBits = 8; termial.Parity = Parity.None; termial.StopBits = StopBits.One; this.TerminalPhoneNumberTB.Text = termial.PhoneNumber; //termial.InitializeCommands = "AT+CBST=71,0,1\r\n"; this.MediasCB.Items.Add(termial); } //Select first media if medis is not selected. if (SelectedMedia == null) { SelectedMedia = (Gurux.Common.IGXMedia)this.MediasCB.Items[0]; } this.MediasCB.SelectedItem = SelectedMedia; if (!string.IsNullOrEmpty(Device.Password)) { this.PasswordTB.Text = ASCIIEncoding.ASCII.GetString(CryptHelper.Decrypt(Device.Password, Password.Key)); } if (dev != null) { this.UseLNCB.Checked = dev.UseLogicalNameReferencing; } this.AuthenticationCB.SelectedIndexChanged += new System.EventHandler(this.AuthenticationCB_SelectedIndexChanged); bool bConnected = Device.Media != null && Device.Media.IsOpen; SerialPortCB.Enabled = AdvancedBtn.Enabled = ManufacturerCB.Enabled = MediasCB.Enabled = AuthenticationCB.Enabled = UseRemoteSerialCB.Enabled = OKBtn.Enabled = !bConnected; HostNameTB.ReadOnly = PortTB.ReadOnly = PasswordTB.ReadOnly = WaitTimeTB.ReadOnly = PhysicalServerAddressTB.ReadOnly = NameTB.ReadOnly = bConnected; } catch (Exception Ex) { GXDLMS.Common.Error.ShowError(this, Ex); } }
public 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; } }
TreeNode AddDevice(GXDLMSDevice dev, bool refresh) { if (!refresh) { dev.OnProgress += new ProgressEventHandler(this.OnProgress); dev.OnStatusChanged += new StatusEventHandler(this.OnStatusChanged); GXManufacturer m = Manufacturers.FindByIdentification(dev.Manufacturer); if (m.Extension != null) { Type t = Type.GetType(m.Extension); dev.Extension = Activator.CreateInstance(t) as IGXManufacturerExtension; } } //Add device to device tree. TreeNode node = this.ObjectTree.Nodes[0].Nodes.Add(dev.Name); node.SelectedImageIndex = node.ImageIndex = 2; node.Tag = dev; ObjectTreeItems[dev] = node; //Add device to device list. if (!refresh) { ListViewItem item = DeviceList.Items.Add(dev.Name); item.Tag = dev; DeviceListViewItems[dev] = item; } return node; }
public GXDLMSCommunicator(GXDLMSDevice parent, Gurux.Common.IGXMedia media) { this.parent = parent; this.media = media; client = new GXDLMSSecureClient(); }
/// <summary> /// Try to find client and server address from the meter. /// </summary> private void FindSettings(object sender, GXAsyncWork work, object[] parameters) { GXDLMSDevice dev = new GXDLMSDevice(media); dev.WaitTime = 1; if ((media is GXSerial serial) && Settings.Default.HdlcAddressUseOpticalProbe) { try { string manufactureID; dev.StartProtocol = StartProtocolType.IEC; media.OnMediaStateChange -= OnMediaStateChange; try { dev.Manufacturers = Manufacturers; manufactureID = dev.Comm.InitializeIEC(); } finally { media.OnMediaStateChange += OnMediaStateChange; } BeginInvoke(new AppendTextEventHandler(OnAppendText), "++++++++++++++++++++++++++++++++++++" + Environment.NewLine + "Connect to the meter using IEC handshaking." + Environment.NewLine + "Manufacturer is " + manufactureID + Environment.NewLine + "Baud rate is " + serial.BaudRate + Environment.NewLine); } catch (Exception ex) { BeginInvoke(new AppendTextEventHandler(OnAppendText), "Failed to receive reply from the optical probe." + Environment.NewLine + "++++++++++++++++++++++++++++++++++++" + Environment.NewLine + "Checking device with baud rate " + ex.Message + Environment.NewLine); return; } } if (media is GXSerial && Settings.Default.HdlcAddressScanBaudRates && !Settings.Default.HdlcAddressUseOpticalProbe) { int original = (media as GXSerial).BaudRate; List <string> rates = new List <string>(Settings.Default.HdlcAddressBaudRates.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries)); int count = rates.Count; bool first = true; foreach (string it in rates) { int rate = int.Parse(it); if (rate != 0) { (media as GXSerial).BaudRate = rate; Thread.Sleep(1000); BeginInvoke(new AppendTextEventHandler(OnAppendText), "++++++++++++++++++++++++++++++++++++" + Environment.NewLine + "Checking device with baud rate " + rate + Environment.NewLine); if (CheckSnrm(dev, rates.Count, first)) { break; } first = false; } --count; } (media as GXSerial).BaudRate = original; } else { CheckSnrm(dev, 1, true); } }
void ReadDevice(GXDLMSDevice dev) { try { dev.Comm.OnBeforeRead += new ReadEventHandler(OnBeforeRead); dev.Comm.OnAfterRead += new ReadEventHandler(OnAfterRead); dev.KeepAliveStop(); int cnt = dev.Objects.Count; if (cnt == 0) { RefreshDevice(dev, true); //Do not try to refresh and read values at the same time. return; } int pos = 0; foreach (GXDLMSObject it in dev.Objects) { OnProgress(dev, "Reading " + it.LogicalName + "...", ++pos, cnt); dev.Comm.Read(this, it, 0); DLMSItemOnChange(it, false, 0, null); } } catch (Exception Ex) { throw Ex; } finally { dev.Comm.OnBeforeRead -= new ReadEventHandler(OnBeforeRead); dev.Comm.OnAfterRead -= new ReadEventHandler(OnAfterRead); dev.KeepAliveStart(); } }
private void MainForm_Load(object sender, EventArgs e) { try { //Find medias. DirectoryInfo di = new DirectoryInfo(Directory.GetCurrentDirectory()); foreach (FileInfo file in di.GetFiles("*.dll")) { try { Assembly.LoadFile(file.FullName); } catch { continue; } } Application.EnableVisualStyles(); ObjectValueView.Columns.Clear(); ObjectValueView.Columns.Add("Name"); ObjectValueView.Columns.Add("Object Type"); ObjectValueView.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize); LoadXmlPositioning(); //Create empty device to find all object types. GXDLMSDevice dev = new GXDLMSDevice(); foreach (Type type in this.GetType().Assembly.GetTypes()) { GXDLMSViewAttribute[] att = (GXDLMSViewAttribute[]) type.GetCustomAttributes(typeof(GXDLMSViewAttribute), true); if (!type.IsAbstract && att != null && att.Length != 0) { IGXDLMSView view = Activator.CreateInstance(type) as IGXDLMSView; Form f = view as Form; f.TopLevel = false; f.TopMost = false; f.FormBorderStyle = FormBorderStyle.None; f.Dock = DockStyle.Fill; f.Width = ObjectPanelFrame.Width; f.Height = ObjectPanelFrame.Height; Views.Add(att[0].DLMSType, view); } } Gurux.Common.CheckUpdatesEventHandler p = (Gurux.Common.CheckUpdatesEventHandler)this.OnCheckUpdatesEnabled; ThreadPool.QueueUserWorkItem(Gurux.Common.GXUpdateChecker.CheckUpdates, p); if (GXManufacturerCollection.IsFirstRun()) { if (MessageBox.Show(this, GXDLMSDirector.Properties.Resources.InstallManufacturersOnlineTxt, GXDLMSDirector.Properties.Resources.GXDLMSDirectorTxt, MessageBoxButtons.YesNoCancel) == DialogResult.Yes) { GXManufacturerCollection.UpdateManufactureSettings(); } } Manufacturers = new GXManufacturerCollection(); GXManufacturerCollection.ReadManufacturerSettings(Manufacturers); ThreadPool.QueueUserWorkItem(new WaitCallback(CheckUpdates), this); } catch (Exception Ex) { GXDLMS.Common.Error.ShowError(this, Ex); } }
/// <summary> /// Try to find client and server address from the meter. /// </summary> private void FindSettings(object sender, GXAsyncWork work, object[] parameters) { GXDLMSDevice dev = new GXDLMSDevice(media); dev.Comm.client.UseLogicalNameReferencing = dev.UseLogicalNameReferencing = true; dev.Conformance = (int)new GXDLMSClient(true).ProposedConformance; dev.WaitTime = -Properties.Settings.Default.HdlcSearchWaitTime; if ((media is GXSerial serial) && Settings.Default.HdlcAddressUseOpticalProbe) { try { int baudRate = serial.BaudRate; string manufactureID; dev.StartProtocol = StartProtocolType.IEC; dev.InterfaceType = InterfaceType.HdlcWithModeE; media.OnMediaStateChange -= OnMediaStateChange; try { dev.Manufacturers = Manufacturers; manufactureID = dev.Comm.InitializeIEC(); media.Trace = TraceLevel.Verbose; } finally { media.OnMediaStateChange += OnMediaStateChange; } BeginInvoke(new AppendTextEventHandler(OnAppendText), "++++++++++++++++++++++++++++++++++++" + Environment.NewLine + "Connect to the meter using IEC handshaking." + Environment.NewLine + "Manufacturer is " + manufactureID + Environment.NewLine + "Baud rate is " + baudRate + Environment.NewLine); } catch (Exception ex) { BeginInvoke(new AppendTextEventHandler(OnAppendText), "Failed to receive reply from the optical probe." + Environment.NewLine + "++++++++++++++++++++++++++++++++++++" + Environment.NewLine + "Checking device with baud rate " + ex.Message + Environment.NewLine); return; } } if (media is GXSerial && Settings.Default.HdlcAddressScanBaudRates && !Settings.Default.HdlcAddressUseOpticalProbe) { int original = (media as GXSerial).BaudRate; List <string> rates = new List <string>(Settings.Default.HdlcAddressBaudRates.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries)); int count = rates.Count; bool first = true; foreach (string it in rates) { int rate = int.Parse(it); if (rate != 0) { (media as GXSerial).BaudRate = rate; BeginInvoke(new AppendTextEventHandler(OnAppendText), "++++++++++++++++++++++++++++++++++++" + Environment.NewLine + "Checking device with baud rate " + rate + Environment.NewLine); if (CheckSnrm(dev, rates.Count, first)) { return; } first = false; if (Settings.Default.HdlcConnectionDelay != 0) { BeginInvoke(new AppendTextEventHandler(OnAppendText), string.Format("Waiting {0} seconds before the new try.", Settings.Default.HdlcConnectionDelay) + Environment.NewLine); Thread.Sleep(Settings.Default.HdlcConnectionDelay * 1000); } } --count; } (media as GXSerial).BaudRate = original; } else { if (!CheckSnrm(dev, 1, true)) { BeginInvoke(new ChangeAddressEventHandler(OnChangeAddress), 0, true); } } }
private bool CheckSnrm(GXDLMSDevice dev, int count, bool reset) { if (media.IsOpen) { int[] serverAddresses = Properties.Settings.Default.HdlcServerAddresses.Split(',').Select(int.Parse).ToArray(); int[] clientAddresses = Properties.Settings.Default.HdlcClientAddresses.Split(',').Select(int.Parse).ToArray(); BeginInvoke(new ResetProgressEventHandler(OnResetProgress), count * serverAddresses.Length, reset); StringBuilder sb = new StringBuilder(); bool serverFound = false; foreach (int server in serverAddresses) { BeginInvoke(new IncreaseProgressEventHandler(OnIncreaseProgress)); foreach (int client in clientAddresses) { BeginInvoke(new AppendTextEventHandler(OnAppendText), "Try with server address " + server + " (0x" + server.ToString("X") + ") and client " + client + " (0x" + client.ToString("X") + ")" + Environment.NewLine); dev.Comm.client.ClientAddress = client; dev.Comm.client.ServerAddress = server; byte[] data = dev.Comm.client.SNRMRequest(); GXReplyData reply = new GXReplyData(); try { //Accept all data. dev.Comm.client.ClientAddress = 0; dev.Comm.client.ServerAddress = 0x7f; dev.WaitTime = -Properties.Settings.Default.HdlcSearchWaitTime; dev.Comm.ReadDataBlock(data, "Send SNRM request.", 0, 0, reply); //Try to establish the connection to the meter. int logical, physical; GXDLMSTranslator.GetLogicalAndPhysicalAddress(reply.SourceAddress, out logical, out physical); dev.Comm.client.ParseUAResponse(reply.Data); if (serverAddresses[0] != reply.SourceAddress) { BeginInvoke(new ChangeAddressEventHandler(OnChangeAddress), reply.SourceAddress, true); } serverFound = true; sb.AppendLine("++++++++++++++++++++++++++++++++++++"); reply.Clear(); dev.Comm.client.ClientAddress = client; dev.Comm.client.ServerAddress = server; dev.WaitTime = Properties.Settings.Default.HdlcSearchInitialWaitTime; data = dev.Comm.client.AARQRequest()[0]; dev.Comm.ReadDataBlock(data, "Send AARQ request.", 0, 0, reply); try { dev.Comm.client.ParseAAREResponse(reply.Data); } catch (GXDLMSException ex) { sb.AppendLine("Meter returned an exception:"); sb.AppendLine(ex.Message); if (ex.Result == AssociationResult.PermanentRejected) { BeginInvoke(new ChangeAddressEventHandler(OnChangeAddress), clientAddresses[0], false); } } catch (Exception ex) { sb.AppendLine("Meter returned an exception:"); sb.AppendLine(ex.Message); } if (media is GXSerial) { sb.AppendLine("Used baud rate: " + (media as GXSerial).BaudRate); } sb.AppendLine("Client address: " + reply.TargetAddress + " (0x" + reply.TargetAddress.ToString("X") + ")"); sb.AppendLine("Server address: " + reply.SourceAddress + " (0x" + reply.SourceAddress.ToString("X") + ")"); sb.Append("Logical address: " + logical + " (0x" + logical.ToString("X") + ") "); sb.AppendLine("Physical address: " + physical + " (0x" + physical.ToString("X") + ")"); BeginInvoke(new AppendTextEventHandler(OnAppendText), sb.ToString()); try { dev.Comm.ReadDataBlock(dev.Comm.client.DisconnectRequest(true), "Send Disconnect request.", 0, 0, reply); } catch (Exception) { reply.Clear(); } return(serverFound); } catch (TimeoutException) { if (serverFound && clientAddresses[0] == reply.TargetAddress) { BeginInvoke(new ChangeAddressEventHandler(OnChangeAddress), clientAddresses[0], false); } reply.Clear(); } catch (Exception ex) { //If user has close the media. if (!media.IsOpen) { return(true); } if (serverFound && clientAddresses[0] == reply.TargetAddress) { BeginInvoke(new ChangeAddressEventHandler(OnChangeAddress), clientAddresses[0], false); } int logical, physical; GXDLMSTranslator.GetLogicalAndPhysicalAddress(reply.SourceAddress, out logical, out physical); sb.AppendLine("Meter returned an exception:"); sb.AppendLine(ex.Message); sb.AppendLine("Try to change the client address:"); if (media is GXSerial) { sb.AppendLine("Used baud rate: " + (media as GXSerial).BaudRate); } sb.AppendLine("Client address: " + reply.TargetAddress + " (0x" + reply.TargetAddress.ToString("X") + ")"); sb.AppendLine("Server address: " + reply.SourceAddress + " (0x" + reply.SourceAddress.ToString("X") + ")"); sb.Append("Logical address: " + logical + " (0x" + logical.ToString("X") + ") "); sb.AppendLine("Physical address: " + physical + " (0x" + physical.ToString("X") + ")"); BeginInvoke(new AppendTextEventHandler(OnAppendText), sb.ToString()); reply.Clear(); try { dev.Comm.ReadDataBlock(dev.Comm.client.DisconnectRequest(true), "Send Disconnect request.", 0, 0, reply); } catch (Exception) { reply.Clear(); } return(serverFound); } if (!media.IsOpen) { break; } } } } return(false); }
void RemoveDevice(GXDLMSDevice dev) { dev.Disconnect(); dev.OnProgress -= new ProgressEventHandler(this.OnProgress); dev.OnStatusChanged -= new StatusEventHandler(this.OnStatusChanged); Devices.Remove(dev); TreeNode node = (TreeNode)ObjectTreeItems[dev]; node.Remove(); ObjectTreeItems.Remove(dev); ListViewItem item = (ListViewItem)DeviceListViewItems[dev]; DeviceList.Items.Remove(item); DeviceListViewItems.Remove(dev); while (dev.Objects.Count != 0) { RemoveObject(dev.Objects[0]); } }
void UpdateDeviceUI(GXDLMSDevice device, DeviceState state) { ConnectCMnu.Enabled = ConnectBtn.Enabled = ConnectMnu.Enabled = (state & DeviceState.Initialized) != 0; ReadCMnu.Enabled = ReadBtn.Enabled = RefreshMnu.Enabled = ReadMnu.Enabled = (state & DeviceState.Connected) == DeviceState.Connected; DisconnectCMnu.Enabled = DisconnectMnu.Enabled = ConnectBtn.Checked = (state & DeviceState.Connected) == DeviceState.Connected; DeleteCMnu.Enabled = DeleteMnu.Enabled = DeleteBtn.Enabled = OptionsBtn.Enabled = state == DeviceState.Initialized; UpdateWriteEnabled(); }
/// <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; }