Exemplo n.º 1
0
        static public string ReadValue(Gurux.Common.IGXMedia media, int wt, string data, int level)
        {
            string dec = GetDescription(data.Substring(0, data.IndexOf('(')));

            if (dec != "")
            {
                System.Diagnostics.Debug.WriteLine("Reading property " + dec);
            }
            data = (char)1 + "R" + level.ToString() + (char)2 + data + (char)3;
            List <byte> bytes = new List <byte>(ASCIIEncoding.ASCII.GetBytes(data));

            bytes.RemoveAt(0);
            char checksum = (char)CalculateChecksum(bytes, 0, bytes.Count);

            data += checksum;
            List <byte> reply = new List <byte>();

            byte[] tmp = Read(media, data, '\0', wt, true);
            reply.AddRange(tmp);
            string header, frame;

            GetPacket(reply, true, out header, out frame);
            int start = frame.IndexOf('(') + 1;
            int end   = frame.LastIndexOf(')');

            return(frame.Substring(start, end - start));
        }
        /// <summary>
        /// Draw media name to media compobox.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MediasCB_DrawItem(object sender, DrawItemEventArgs e)
        {
            // If the index is invalid then simply exit.
            if (e.Index == -1 || e.Index >= MediasCB.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.
            Gurux.Common.IGXMedia target = (Gurux.Common.IGXMedia)MediasCB.Items[e.Index];
            if (target == null)
            {
                return;
            }
            string name = target.MediaType;
            SizeF  s    = e.Graphics.MeasureString(name, f);

            e.Graphics.DrawString(name, f, b, e.Bounds);
        }
Exemplo n.º 3
0
 public void Initialize(IGXMedia media, TraceLevel trace, string path, UInt32 sn)
 {
     serialNumber = sn;
     objectsFile  = path;
     Media        = media;
     Trace        = trace;
     Init();
 }
Exemplo n.º 4
0
 public void Initialize(IGXMedia media, TraceLevel trace, string path, UInt32 sn, bool exclusive)
 {
     serialNumber = sn;
     objectsFile  = path;
     Media        = media;
     Trace        = trace;
     Exclusive    = exclusive;
     Init(exclusive);
 }
Exemplo n.º 5
0
        /// <summary>
        /// Read table data from the meter.
        /// </summary>
        /// <remarks>
        /// With commmand R6 data can be read one row at the time and it is parsed on the fly.
        /// With other commands all data must first read before data can be parse.
        /// </remarks>
        /// <param name="media"></param>
        /// <param name="wt"></param>
        /// <param name="name"></param>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <param name="level"></param>
        /// <returns></returns>
        public static object[][] ReadTable(Gurux.Common.IGXMedia media, int wt, string name, DateTime start, DateTime end, string parameters, int level, int count, out string[] columns)
        {
            columns = null;
            List <byte> reply = new List <byte>();
            string      header, frame;
            //Read CRC.
            ReceiveParameters <byte[]> crc = new ReceiveParameters <byte[]>()
            {
                Count    = 1,
                WaitTime = wt
            };
            List <byte> data = new List <byte>();

            data.Add(1);
            data.AddRange(GenerateReadTable(name, start, end, parameters, level, count));
            data.Add(3);
            data.Add(CalculateChecksum(data, 1, data.Count - 1));
            lock (media.Synchronous)
            {
                do
                {
                    List <byte> tmp = new List <byte>(SendData(media, data == null ? null : data.ToArray(), '\0', wt, true, level == 6, false));
                    data = null;
                    if (level != 6 && tmp[tmp.Count - 1] == 0x3)
                    {
                        crc.Count = 1;
                        if (!media.Receive(crc))
                        {
                            throw new Exception("Failed to receive reply from the device in given time.");
                        }
                        tmp.AddRange(crc.Reply);
                    }
                    else if (level == 6)
                    {
                        if (GetPacket(tmp, true, out header, out frame) == null)
                        {
                            throw new Exception("Failed to receive reply from the device in given time.");
                        }
                        if (tmp[tmp.Count - 2] == 0x4)
                        {
                            //Send ACK if more data is left.
                            data = new List <byte>();
                            data.Add(6);
                            System.Threading.Thread.Sleep(200);
                        }
                    }
                    reply.AddRange(tmp);
                }while (reply[reply.Count - 2] != 0x3);
            }
            int      status = 0;
            DateTime tm     = DateTime.MinValue;
            int      add    = 0;

            return(ParseTableData(reply.ToArray(), ref columns, ref status, ref tm, ref add, name));
        }
Exemplo n.º 6
0
 /// <summary>
 /// Constructor.
 /// </summary>
 public GXDLMSDevice(Gurux.Common.IGXMedia media) : base()
 {
     communicator             = new GXDLMSCommunicator(this, media);
     Objects                  = communicator.client.Objects;
     Objects.Tag              = this;
     communicator.OnProgress += new ProgressEventHandler(this.NotifyProgress);
     this.KeepAlive           = new System.Timers.Timer();
     this.KeepAlive.Interval  = 40000;
     this.KeepAlive.Elapsed  += new System.Timers.ElapsedEventHandler(KeepAlive_Elapsed);
     m_Status                 = DeviceState.Initialized;
 }
 private void MediasCB_SelectedIndexChanged(object sender, EventArgs e)
 {
     try
     {
         SelectedMedia = (Gurux.Common.IGXMedia)MediasCB.SelectedItem;
         this.SerialSettingsGB.Visible   = SelectedMedia is GXSerial;
         this.NetworkSettingsGB.Visible  = SelectedMedia is GXNet;
         this.TerminalSettingsGB.Visible = SelectedMedia is GXTerminal;
         if (SelectedMedia is GXNet && this.PortTB.Text == "")
         {
             this.PortTB.Text = "4059";
         }
         UpdateStartProtocol();
     }
     catch (Exception Ex)
     {
         GXDLMS.Common.Error.ShowError(this, Ex);
     }
 }
Exemplo n.º 8
0
 /// <summary>
 /// Constructor.
 /// </summary>
 public GXDLMSDevice(Gurux.Common.IGXMedia media)
 {
     StartProtocol            = StartProtocolType.IEC;
     ClientAddress            = 0x10; // Public client (lowest security level).
     PhysicalAddress          = 1;
     Password                 = "";
     Authentication           = Authentication.None;
     communicator             = new GXDLMSCommunicator(this, media);
     m_Objects                = communicator.client.Objects;
     m_Objects.Tag            = this;
     communicator.OnProgress += new ProgressEventHandler(this.NotifyProgress);
     this.KeepAlive           = new System.Timers.Timer();
     this.KeepAlive.Interval  = 40000;
     this.KeepAlive.Elapsed  += new System.Timers.ElapsedEventHandler(KeepAlive_Elapsed);
     m_Status                 = DeviceState.Initialized;
     WaitTime                 = 5;
     InactivityTimeout        = 120;
     WindowSizeRX             = WindowSizeTX = 1;
     MaxInfoRX                = MaxInfoTX = 128;
     PduSize      = 0xFFFF;
     ServiceClass = ServiceClass.Confirmed;
     Priority     = Priority.High;
 }
Exemplo n.º 9
0
 /// <summary>
 /// Show media settings.
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void MediaCB_SelectedIndexChanged(object sender, EventArgs e)
 {
     try
     {
         MediaFrame.Controls.Clear();
         string mediaName = Convert.ToString(MediaCB.SelectedItem);
         if (!string.IsNullOrEmpty(mediaName))
         {
             Media = Client.SelectMedia(mediaName);
             if (Media == null)
             {
                 throw new Exception(MediaCB.Text + " media not found.");
             }
             if (Media is GXSerial)
             {
                 foreach (GXAmiDataCollector it in Collectors)
                 {
                     (Media as GXSerial).AvailablePorts = it.SerialPorts;
                 }
             }
             PropertiesForm = Media.PropertiesForm;
             ((IGXPropertyPage)PropertiesForm).Initialize();
             while (PropertiesForm.Controls.Count != 0)
             {
                 Control ctr = PropertiesForm.Controls[0];
                 if (ctr is Panel)
                 {
                     if (!ctr.Enabled)
                     {
                         PropertiesForm.Controls.RemoveAt(0);
                         continue;
                     }
                 }
                 MediaFrame.Controls.Add(ctr);
             }
         }
     }
     catch (Exception ex)
     {
         GXCommon.ShowError(this, ex);
     }
 }
 public GXDLMSCommunicator(GXDLMSDevice parent, Gurux.Common.IGXMedia media)
 {
     Parent  = parent;
     Media   = media;
     m_Cosem = new Gurux.DLMS.GXDLMSClient();
 }
 /// <summary>
 /// Show settings of selected media.
 /// </summary>
 private void MediaCB_SelectedIndexChanged(object sender, EventArgs e)
 {
     try
     {
         MediaFrame.Controls.Clear();
         //If new media is selected or media is changed.
         if (Device.GXClient.Media == null || Device.GXClient.Media.MediaType != MediaCB.Text)
         {
             SelectedMedia = Device.GXClient.SelectMedia(MediaCB.Text);
             Gurux.Device.GXMediaTypeCollection mediatypes = Device.GetAllowedMediaTypes();
             Gurux.Device.GXMediaType tp = mediatypes[SelectedMedia.MediaType];
             if (tp != null)
             {
                 SelectedMedia.Settings = tp.DefaultMediaSettings;
             }
             if (SelectedMedia is GXAmiGateway)
             {
                 GXAmiGateway gw = SelectedMedia as GXAmiGateway;
                 gw.Host = Gurux.DeviceSuite.Properties.Settings.Default.AmiHostName;
                 gw.UserName = Gurux.DeviceSuite.Properties.Settings.Default.AmiUserName;
                 gw.Password = Gurux.DeviceSuite.Properties.Settings.Default.AmiPassword;
                 gw.GXClient = Device.GXClient;
             }
         }
         else
         {
             SelectedMedia = Device.GXClient.Media;
         }
         if (SelectedMedia == null)
         {
             throw new Exception(MediaCB.Text + " media not found.");
         }                
         PropertiesForm = SelectedMedia.PropertiesForm;
         ((IGXPropertyPage)PropertiesForm).Initialize();
         while (PropertiesForm.Controls.Count != 0)
         {
             Control ctr = PropertiesForm.Controls[0];
             if (ctr is Panel)
             {
                 if (!ctr.Enabled)
                 {
                     PropertiesForm.Controls.RemoveAt(0);
                     continue;
                 }
             }
             MediaFrame.Controls.Add(ctr);
         }
         UpdateResendCnt(Device.ResendCount);
         UpdateWaitTime(Device.WaitTime);
     }
     catch (Exception ex)
     {                
         GXCommon.ShowError(this, ex);
     }
 }
Exemplo n.º 12
0
        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);
            }
        }
Exemplo n.º 13
0
        public override void ImportFromDevice(Control[] addinPages, GXDevice device, Gurux.Common.IGXMedia media)
        {
            GXIEC62056Device   dev = (GXIEC62056Device)device;
            ImportSelectionDlg dlg = addinPages[1] as ImportSelectionDlg;
            string             deviceSerialNumber = dlg.DeviceSerialNumber;
            int waittime = dev.WaitTime;

            media.Open();
            try
            {
                string data  = "/?" + deviceSerialNumber + "!\r\n";
                byte[] reply = IEC62056Parser.Identify(media, data, '\0', waittime);
                if (reply[0] != '/')
                {
                    throw new Exception("Invalid reply.");
                }
                char     baudRate   = (char)reply[4];
                string   CModeBauds = "0123456789";
                string   BModeBauds = "ABCDEFGHI";
                Protocol mode;
                if (CModeBauds.IndexOf(baudRate) != -1)
                {
                    mode = Protocol.ModeC;
                }
                else if (BModeBauds.IndexOf(baudRate) != -1)
                {
                    mode = Protocol.ModeB;
                }
                else
                {
                    mode     = Protocol.ModeA;
                    baudRate = '0';
                }
                if (reply[0] != '/')
                {
                    throw new Exception("Import failed. Invalid reply.");
                }
                //If mode is not given.
                if (dev.Mode == Protocol.None)
                {
                    dev.Mode = mode;
                }
                data = ASCIIEncoding.ASCII.GetString(reply.ToArray());
                string manufacturer = new string(new char[] { (char)reply[1], (char)reply[2], (char)reply[3] });
                if (dev.Mode == Protocol.ModeA)
                {
                    data = (char)0x06 + "0" + baudRate + "0\r\n";
                }
                else
                {
                    data = (char)0x06 + "0" + baudRate + "1\r\n";
                }
                //Note this sleep is in standard. Do not remove.
                if (media.MediaType == "Serial")
                {
                    System.Threading.Thread.Sleep(200);
                }
                reply = IEC62056Parser.ParseHandshake(media, data, baudRate, waittime);
                string header, frame;
                IEC62056Parser.GetPacket(new List <byte>(reply), true, out header, out frame);
                System.Diagnostics.Debug.WriteLine(frame);
                if (header == "B0")
                {
                    throw new Exception("Connection failed. Meter do not accept connection at the moment.");
                }
                //Password is asked.
                if (header == "P0")
                {
                    System.Diagnostics.Debug.WriteLine("Password is asked.");
                }
                //Note this sleep is in standard. Do not remove.
                if (media.MediaType == "Serial")
                {
                    System.Threading.Thread.Sleep(200);
                }
                if (dev.Mode == Protocol.ModeA)
                {
                    GXCategory defaultCategory = new GXIEC62056ReadoutCategory();
                    defaultCategory.Name = "Readout";
                    device.Categories.Add(defaultCategory);
                }
                else
                {
                    GXCategory defaultCategory = null;
                    defaultCategory      = new GXIEC62056Category();
                    defaultCategory.Name = "Properties";
                    device.Categories.Add(defaultCategory);
                    foreach (string it in IEC62056Parser.GetGeneralOBISCodes())
                    {
                        try
                        {
                            //Note this sleep is in standard. Do not remove.
                            if (media is Gurux.Serial.GXSerial)
                            {
                                System.Threading.Thread.Sleep(200);
                            }
                            if (!it.StartsWith("P."))
                            {
                                string value = IEC62056Parser.ReadValue(media, waittime, it + "()", 2);
                                if (!Convert.ToString(value).StartsWith("ER"))
                                {
                                    GXIEC62056Property prop = new GXIEC62056Property();
                                    prop.AccessMode = AccessMode.Read;
                                    prop.ReadMode   = dev.ReadMode;
                                    prop.WriteMode  = dev.WriteMode;
                                    prop.Name       = IEC62056Parser.GetDescription(it);
                                    prop.Data       = it;
                                    prop.DataType   = IEC62056Parser.GetDataType(it);
                                    if (prop.DataType == DataType.DateTime ||
                                        prop.DataType == DataType.Date ||
                                        prop.DataType == DataType.Time)
                                    {
                                        prop.ValueType = typeof(DateTime);
                                    }
                                    defaultCategory.Properties.Add(prop);
                                    TraceLine("Property " + prop.Name + " added.");
                                }
                            }
                            else
                            {
                                object[][] rows;
                                //Try to read last hour first.
                                TimeSpan add     = new TimeSpan(1, 0, 0);
                                DateTime start   = DateTime.Now.Add(-add);
                                string[] columns = null;
                                do
                                {
                                    try
                                    {
                                        rows = IEC62056Parser.ReadTable(media, waittime, it, start, DateTime.Now, null, 5, 1, out columns);
                                    }
                                    catch
                                    {
                                        //If media is closed.
                                        if (!media.IsOpen)
                                        {
                                            break;
                                        }
                                        rows = new object[0][];
                                    }
                                    if (rows.Length == 0)
                                    {
                                        if (add.TotalHours == 1)
                                        {
                                            //Try to read last day.
                                            add   = new TimeSpan(1, 0, 0, 0);
                                            start = DateTime.Now.Add(-add).Date;
                                        }
                                        else if (add.TotalHours == 24)
                                        {
                                            //Try to read last week.
                                            add   = new TimeSpan(7, 0, 0, 0);
                                            start = DateTime.Now.Add(-add).Date;
                                        }
                                        else if (add.TotalDays == 7)
                                        {
                                            //Try to read last month.
                                            add   = new TimeSpan(31, 0, 0, 0);
                                            start = DateTime.Now.Add(-add).Date;
                                        }
                                        else if (add.TotalDays == 31)
                                        {
                                            //Read all.
                                            add   = new TimeSpan(100, 0, 0, 0);
                                            start = DateTime.MinValue;
                                        }
                                        else
                                        {
                                            break;
                                        }
                                        //Note this sleep is in standard. Do not remove.
                                        if (media is Gurux.Serial.GXSerial)
                                        {
                                            System.Threading.Thread.Sleep(200);
                                        }
                                    }
                                    else
                                    {
                                        GXIEC62056Table table = new GXIEC62056Table();
                                        table.Name       = IEC62056Parser.GetDescription(it);
                                        table.AccessMode = AccessMode.Read;
                                        table.Data       = it;
                                        table.ReadMode   = 6;
                                        int index = -1;
                                        foreach (string col in columns)
                                        {
                                            GXIEC62056Property prop = new GXIEC62056Property();
                                            prop.Name = col;
                                            //Mikko prop.Name = IEC62056Parser.GetDescription(col);
                                            prop.Data      = col;
                                            prop.ValueType = rows[0][++index].GetType();
                                            table.Columns.Add(prop);
                                        }
                                        device.Tables.Add(table);
                                        TraceLine("Property " + table.Name + " added.");
                                        break;
                                    }
                                }while (rows.Length == 0);
                            }
                        }
                        catch (Exception ex)
                        {
                            System.Diagnostics.Debug.WriteLine(ex.Message);
                        }
                    }
                }
            }
            finally
            {
                if (media.MediaType == "Serial" || media.MediaType == "Terminal")
                {
                    IEC62056Parser.Disconnect(media, 2);
                }
                media.Close();
            }
        }
 /// <summary>
 /// New media is selected.
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void MediasCB_SelectedIndexChanged(object sender, System.EventArgs e)
 {
     try
     {
         if (MediasCB.SelectedIndex == -1)
         {
             return;
         }
         MediaFrame.Controls.Clear();                
         string mediaName = MediasCB.Items[MediasCB.SelectedIndex].ToString();
         if (!AvailableMedias.ContainsKey(mediaName))
         {
             SelectedMedia = m_GXDevice.GXClient.SelectMedia(mediaName);
             if (SelectedMedia == null)
             {
                 throw new Exception(mediaName + " media not found.");
             }
         }
         else
         {
             SelectedMedia = AvailableMedias[mediaName];
             SelectedMedia.Close();
         }
         if (m_GXDevice.GXClient.PacketParser != null)
         {
             m_GXDevice.GXClient.PacketParser.InitializeMedia(m_GXDevice.GXClient, SelectedMedia);
         }
         PropertiesForm = SelectedMedia.PropertiesForm;
         Gurux.Device.GXMediaTypeCollection mediatypes = m_GXDevice.AllowedMediaTypes;                
         Gurux.Device.GXMediaType tp = mediatypes[SelectedMedia.MediaType];
         try
         {
             string settings = null;
             //Find used media.
             if (Gurux.DeviceSuite.Properties.Settings.Default.EditorSelectedMedia != null &&
                 Gurux.DeviceSuite.Properties.Settings.Default.EditorSelectedMediaSettings != null)
             {
                 string newKey = m_GXDevice.ProtocolName + m_GXDevice.DeviceProfile;
                 newKey = newKey.GetHashCode().ToString();
                 foreach (string it in Gurux.DeviceSuite.Properties.Settings.Default.EditorSelectedMedia)
                 {
                     string[] tmp = it.Split(new char[] { '=' });
                     string key = tmp[0];                            
                     if (string.Compare(newKey, key) == 0)
                     {
                         newKey = m_GXDevice.ProtocolName + m_GXDevice.DeviceProfile + SelectedMedia.MediaType;
                         newKey = newKey.GetHashCode().ToString();
                         //Update media settings.
                         foreach (string it2 in Gurux.DeviceSuite.Properties.Settings.Default.EditorSelectedMediaSettings)
                         {
                             tmp = it2.Split(new char[] { '=' });
                             key = tmp[0];
                             if (string.Compare(newKey, key) == 0)
                             {
                                 settings = tmp[1];
                                 break;
                             }
                         }
                         break;
                     }
                 }
             }
             if (settings == null && tp != null)
             {
                 settings = tp.DefaultMediaSettings;
             }
             //Set default settings if set.
             if (settings != null)
             {
                 SelectedMedia.Settings = settings;
             }                   
         }
         catch
         {
             //It's OK if this fails.
         }
         ((IGXPropertyPage)PropertiesForm).Initialize();
         while (PropertiesForm.Controls.Count != 0)
         {
             Control ctr = PropertiesForm.Controls[0];
             if (ctr is Panel)
             {
                 if (!ctr.Enabled)
                 {
                     PropertiesForm.Controls.RemoveAt(0);
                     continue;
                 }
             }
             MediaFrame.Controls.Add(ctr);
         }
     }
     catch (Exception Ex)
     {
         GXCommon.ShowError(this.Parent, Ex);
     }
 }
Exemplo n.º 15
0
 public GXDLMSCommunicator(GXDLMSDevice parent, Gurux.Common.IGXMedia media)
 {
     Parent = parent;
     Media = media;
     m_Cosem = new Gurux.DLMS.GXDLMSClient();
 }
Exemplo n.º 16
0
        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);
            }
        }
Exemplo n.º 17
0
 private void MediasCB_SelectedIndexChanged(object sender, EventArgs e)
 {
     try
     {
         SelectedMedia = (Gurux.Common.IGXMedia)MediasCB.SelectedItem;
         this.SerialSettingsGB.Visible = SelectedMedia is GXSerial;
         this.NetworkSettingsGB.Visible = SelectedMedia is GXNet;
         this.TerminalSettingsGB.Visible = SelectedMedia is GXTerminal;
         if (SelectedMedia is GXNet && this.PortTB.Text == "")
         {
             this.PortTB.Text = "4059";
         }
         UpdateStartProtocol();
     }
     catch (Exception Ex)
     {
         GXDLMS.Common.Error.ShowError(this, Ex);
     }
 }
        /// <summary>
        /// Show settings of selected media.
        /// </summary>
        private void MediaCB_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                MediaFrame.Controls.Clear();
                string mediaName = null;
                if (MediaConnections.Count != 0)
                {
                    mediaName = MediaConnections[0].Name;
                }
                if (string.IsNullOrEmpty(mediaName) || mediaName != MediaCB.Text)
                {
                    GXAmiMediaType mt = MediaCB.SelectedItem as GXAmiMediaType;
                    SelectedMedia = UIDevice.GXClient.SelectMedia(mt.Name);
                    SelectedMedia.Settings = mt.Settings;                   
                }
                else
                {
                    SelectedMedia = UIDevice.GXClient.SelectMedia(mediaName);
                    SelectedMedia.Settings = MediaConnections[0].Settings;
                }
                if (SelectedMedia == null)
                {
                    throw new Exception(MediaCB.Text + " media not found.");
                }
                if (UIDevice.GXClient.PacketParser != null)
                {
                    UIDevice.GXClient.PacketParser.InitializeMedia(UIDevice.GXClient, SelectedMedia);
                }

                if (SelectedMedia is GXSerial)
                {
                    foreach (GXAmiDataCollector it in DataCollectors)
                    {
                        (SelectedMedia as GXSerial).AvailablePorts = it.SerialPorts;
                    }
                }
                (SelectedMedia as IGXVirtualMedia).Virtual = true;
                PropertiesForm = SelectedMedia.PropertiesForm;
                ((IGXPropertyPage)PropertiesForm).Initialize();
                while (PropertiesForm.Controls.Count != 0)
                {
                    Control ctr = PropertiesForm.Controls[0];
                    if (ctr is Panel)
                    {
                        if (!ctr.Enabled)
                        {
                            PropertiesForm.Controls.RemoveAt(0);
                            continue;
                        }
                    }
                    MediaFrame.Controls.Add(ctr);
                }
                UpdateResendCnt(Device.ResendCount);
                UpdateWaitTime(Device.WaitTime);
            }
            catch (Exception ex)
            {                
                GXCommon.ShowError(this, ex);
            }
        }
Exemplo n.º 19
0
 public GXDLMSCommunicator(GXDLMSDevice parent, Gurux.Common.IGXMedia media)
 {
     this.parent = parent;
     this.media = media;
     client = new GXDLMSSecureClient();
 }
Exemplo n.º 20
0
 public GXDLMSCommunicator(GXDLMSDevice parent, Gurux.Common.IGXMedia media)
 {
     this.parent = parent;
     this.media  = media;
     client      = new GXDLMSSecureClient();
 }