Ejemplo n.º 1
0
 /// <summary>
 /// Download latest versions from Gurux www-page.
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void DownloadLatestBtn_Click(object sender, EventArgs e)
 {
     try
     {
         try
         {
             if (MessageBox.Show(this, GXDLMSDirector.Properties.Resources.UpdateManufacturersOnline2Txt, GXDLMSDirector.Properties.Resources.GXDLMSDirectorTxt, MessageBoxButtons.YesNoCancel) == DialogResult.Yes)
             {
                 GXManufacturerCollection.UpdateManufactureSettings();
                 Manufacturers = new GXManufacturerCollection();
                 GXManufacturerCollection.ReadManufacturerSettings(Manufacturers);
             }
         }
         catch (Exception Ex)
         {
             GXDLMS.Common.Error.ShowError(this, Ex);
         }
     }
     catch (Exception Ex)
     {
         GXDLMS.Common.Error.ShowError(this, Ex);
     }
 }
Ejemplo n.º 2
0
        static void Main(string[] args)
        {
            IGXMedia          media = null;
            GXCommunicatation comm  = null;

            try
            {
                ////////////////////////////////////////
                //Handle command line parameters.
                String         id = "", host = "", port = "", pw = "";
                bool           trace = false, iec = true, isSerial = false;
                Authentication auth = Authentication.High;

                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=", "");
                        isSerial = true;
                        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) || (!isSerial && string.IsNullOrEmpty(host)))
                //{
                // ShowHelp();
                // return;
                //}
                ////////////////////////////////////////
                //Initialize connection settings.
                if (isSerial)
                {
                    GXSerial serial = media as GXSerial;
                    string[] t      = GXSerial.GetPortNames();
                    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
                {
                    Gurux.Net.GXNet net = media as Gurux.Net.GXNet;
                    net.Port     = Convert.ToInt32(port);
                    net.HostName = host;
                    net.Protocol = Gurux.Net.NetworkType.Tcp;
                }
                ////////////////////////////////////////
                //Update manufacturer debended settings.
                GXManufacturerCollection Manufacturers = new GXManufacturerCollection();
                GXManufacturerCollection.ReadManufacturerSettings(Manufacturers);
                GXManufacturer man = Manufacturers.FindByIdentification(id);
                if (man == null)
                {
                    throw new Exception("Unknown manufacturer: " + id);
                }
                Gurux.DLMS.GXDLMS dlms = new Gurux.DLMS.GXDLMS();
                //Update Obis code list so we can get right descriptions to the objects.
                dlms.ObisCodes = man.ObisCodes;
                comm           = new GXCommunicatation(dlms, media, iec, auth, pw);
                comm.Trace     = trace;
                comm.InitializeConnection(man);

                //Save Association view to the cache so it is not needed to retreave every time.
                string path = man.Identification + ".xml";
                Gurux.DLMS.GXDLMSObjectCollection objects = null;
                Type[]        extraTypes = new Type[] { typeof(GXManufacturerCollection), typeof(GXManufacturer), typeof(GXObisCodeCollection), typeof(GXObisCode), typeof(GXObisValueItem), typeof(GXObisValueItemCollection), typeof(GXDLMSProfileGenericObject) };
                XmlSerializer x          = new XmlSerializer(typeof(GXDLMSObjectCollection), extraTypes);
                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 Gurux.DLMS.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();
                    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 (Gurux.DLMS.GXDLMSObject it in objects)
                    {
                        Console.WriteLine(it.Name + " " + it.Description);
                    }
                }
                //Read available clock and data objects.
                foreach (Gurux.DLMS.GXDLMSObject it in objects.GetObjects(new ObjectType[] { ObjectType.Clock, ObjectType.Data }))
                {
                    object value = comm.Read(it, 2);
                    Console.WriteLine(it.Name + " " + it.Description + " " + value);
                }
                //Read Profile Generic columns.
                GXDLMSObjectCollection cols = null;
                foreach (Gurux.DLMS.GXDLMSObject it in objects.GetObjects(ObjectType.ProfileGeneric))
                {
                    Console.WriteLine("Profile Generic " + it.Name + " Columns:");
                    cols = comm.GetColumns(it);
                    foreach (GXDLMSObject col in cols)
                    {
                        Console.Write(col.Name + " | ");
                    }
                    Console.WriteLine("");
                    //Read first row from Profile Generic.
                    Console.WriteLine("Profile Generic " + it.Name + " Columns:");
                    object[] rows = comm.ReadRowsByEntry(it, 0, 1, cols);
                    foreach (object[] row in rows)
                    {
                        foreach (object cell in row)
                        {
                            Console.Write(cell + " | ");
                        }
                        Console.WriteLine("");
                    }
                    //Read last dayfrom Profile Generic.
                    Console.WriteLine("Profile Generic " + it.Name + " Columns:");
                    rows = comm.ReadRowsByRange(it, DateTime.Now.Date, DateTime.MaxValue, cols);
                    foreach (object[] row in rows)
                    {
                        foreach (object cell in row)
                        {
                            Console.Write(cell + " | ");
                        }
                        Console.WriteLine("");
                    }
                }
            }
            catch (Exception ex)
            {
                if (comm != null)
                {
                    comm.Close();
                }
                Console.WriteLine(ex.Message);
                if (!System.Diagnostics.Debugger.IsAttached)
                {
                    Console.ReadKey();
                }
            }
            finally
            {
                comm.Close();
                if (System.Diagnostics.Debugger.IsAttached)
                {
                    Console.ReadKey();
                }
            }
        }
Ejemplo n.º 3
0
        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();
                }
            }
        }
Ejemplo n.º 4
0
        public GXProperties(GXSettings settings)
        {
            Target = settings;
            Target.client.UseLogicalNameReferencing = false;
            InitializeComponent();
            LNSettings.Dock = SNSettings.Dock = DockStyle.Fill;
            SecurityCB.Items.AddRange(new object[] { Security.None, Security.Authentication,
                                                     Security.Encryption, Security.AuthenticationEncryption });
            NetProtocolCB.Items.AddRange(new object[] { NetworkType.Tcp, NetworkType.Udp });
            ServerAddressTypeCB.SelectedIndexChanged += new System.EventHandler(this.ServerAddressTypeCB_SelectedIndexChanged);
            NetworkSettingsGB.Width = this.Width - NetworkSettingsGB.Left;
            CustomSettings.Bounds   = SerialSettingsGB.Bounds = TerminalSettingsGB.Bounds = NetworkSettingsGB.Bounds;
            ManufacturerCB.DrawMode = MediasCB.DrawMode = ServerAddressTypeCB.DrawMode = AuthenticationCB.DrawMode = DrawMode.OwnerDrawFixed;
            StartProtocolCB.Items.Add(StartProtocolType.IEC);
            StartProtocolCB.Items.Add(StartProtocolType.DLMS);

            GXNet net = new GXNet()
            {
                Protocol = NetworkType.Tcp
            };
            GXSerial serial = new GXSerial();

            MediasCB.Items.Add(net);
            MediasCB.Items.Add(serial);

            //Initialize serial settings.
            string[] ports = GXSerial.GetPortNames();
            this.SerialPortCB.Items.AddRange(ports);

            GXManufacturerCollection Manufacturers = new GXManufacturerCollection();

            if (GXManufacturerCollection.IsFirstRun())
            {
                if (MessageBox.Show(this, Properties.Resources.InstallManufacturersOnlineTxt, Properties.Resources.CTT, MessageBoxButtons.YesNoCancel) == DialogResult.Yes)
                {
                    GXManufacturerCollection.UpdateManufactureSettings();
                }
            }
            GXManufacturerCollection.ReadManufacturerSettings(Manufacturers);
            int pos = 0;

            foreach (GXManufacturer it in Manufacturers)
            {
                int index = this.ManufacturerCB.Items.Add(it);
                if (it.Identification == Properties.Settings.Default.SelectedManufacturer)
                {
                    pos = index;
                }
            }
            ManufacturerCB.SelectedIndex = pos;
            if (Properties.Settings.Default.WaitTime != 0)
            {
                WaitTimeTB.Value = Properties.Settings.Default.WaitTime;
            }

            if (Properties.Settings.Default.Media == "Net")
            {
                MediasCB.SelectedIndex = 0;
                net.Settings           = Properties.Settings.Default.MediaSettings;
            }
            else
            {
                MediasCB.SelectedIndex = 1;
                serial.Settings        = Properties.Settings.Default.MediaSettings;
            }
            if (SerialPortCB.Items.Count != 0)
            {
                SerialPortCB.SelectedItem = serial.PortName;
            }
            HostNameTB.Text            = net.HostName;
            PortTB.Text                = net.Port.ToString();
            NetProtocolCB.SelectedItem = net.Protocol;
            ShowConformance(Target.client.ProposedConformance);
        }