コード例 #1
8
ファイル: Program.cs プロジェクト: Gurux/Gurux.DLMS.Net
        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 sn, client = "", server = "", id = "", host = "", port = "", pw = "";
                bool trace = false, iec = true;
                bool hdlc = true, ln = 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("/sn="))//Serial number.
                    {
                        sn = item.Replace("/sn=", "");
                    }
                    else if (string.Compare(item, "/wrapper", true) == 0)//Wrapper is used.
                    {
                        hdlc = false;
                    }
                    else if (item.StartsWith("/r="))//referencing
                    {
                        id = item.Replace("/r=", "");
                    }
                    else if (item.StartsWith("/m="))//Manufacturer
                    {
                        id = item.Replace("/m=", "");
                    }
                    else if (item.StartsWith("/client="))//Client address
                    {
                        client = item.Replace("/client=", "");
                    }
                    else if (item.StartsWith("/server="))//Server address
                    {
                        server = item.Replace("/server=", "");
                    }
                    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);
                }
                GXDLMSSecureClient dlms = new GXDLMSSecureClient();
                //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.");
                    List<KeyValuePair<GXDLMSObject, int>> list = new List<KeyValuePair<GXDLMSObject, int>>();
                    try
                    {
                        foreach (GXDLMSObject it in objs)
                        {
                            if (it is GXDLMSRegister)
                            {
                                list.Add(new KeyValuePair<GXDLMSObject, int>(it, 3));
                            }
                            if (it is GXDLMSDemandRegister)
                            {
                                list.Add(new KeyValuePair<GXDLMSObject, int>(it, 4));
                            }
                        }
                        comm.ReadList(list);
                    }
                    catch
                    {
                        //If this fails meter is not supporting reading read by list method.
                        //Read values one by one.
                        foreach (GXDLMSObject it in objs)
                        {
                            try
                            {
                                if (it is GXDLMSRegister)
                                {
                                    Console.WriteLine(it.Name);
                                    comm.Read(it, 3);
                                }
                                if (it is GXDLMSDemandRegister)
                                {
                                    Console.WriteLine(it.Name);
                                    comm.Read(it, 4);
                                }
                            }
                            catch
                            {
                                //Actaric SL7000 can return error here. Continue reading.
                            }
                        }
                    }
                    //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);
                    }
                }
                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);
                        }
                    }
                }
                //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, 1, 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();
                }
            }
        }
コード例 #2
0
 public GXPlcDiscover(MainForm parent)
 {
     InitializeComponent();
     MetersView_SelectedIndexChanged(null, null);
     _parent = parent;
     try
     {
         if (Settings.Default.PlcInterface == (int)InterfaceType.PlcHdlc)
         {
             SFskMnu.Checked = true;
         }
         else
         {
             LlcMnu.Checked = true;
         }
         if (Settings.Default.PlcMedia == "GXSerial" && GXSerial.GetPortNames().Length != 0)
         {
             OnMediaTypeChanged(SerialMnu, null);
         }
         else
         {
             OnMediaTypeChanged(NetworkMnu, null);
         }
     }
     catch (Exception ex)
     {
         MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
         Close();
     }
 }
コード例 #3
0
 private void StartProtocolCB_SelectedIndexChanged(object sender, EventArgs e)
 {
     try
     {
         foreach (object it in this.MediasCB.Items)
         {
             if (it is GXSerial)
             {
                 //Initialize serial settings.
                 GXSerial serial = (GXSerial)it;
                 if ((StartProtocolType)StartProtocolCB.SelectedItem == 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;
                 }
                 break;
             }
         }
     }
     catch (Exception Ex)
     {
         GXDLMS.Common.Error.ShowError(this, Ex);
     }
 }
コード例 #4
0
 public GXSerialMonitor()
 {
     InitializeComponent();
     try
     {
         serial                     = new GXSerial();
         serial.Settings            = Properties.Settings.Default.SerialMonitorSettings;
         serial.OnMediaStateChange += Serial_OnMediaStateChange;
         serial.OnReceived         += Serial_OnReceived;
         foreach (string it in GXSerial.GetPortNames())
         {
             PortCb.Items.Add(it);
         }
         if (!string.IsNullOrEmpty(serial.PortName))
         {
             PortCb.SelectedItem = serial.PortName;
         }
         if (PortCb.Items.Count == 0)
         {
             SettingsBtn.Enabled = OpenBtn.Enabled = false;
         }
     }
     catch (Exception ex)
     {
         MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
         Close();
     }
 }
コード例 #5
0
 public GXHdlcAddressResolver()
 {
     InitializeComponent();
     try
     {
         GXSerial             s     = new GXSerial();
         List <ToolStripItem> rates = new List <ToolStripItem>();
         List <string>        list  = new List <string>(Settings.Default.HdlcAddressBaudRates.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries));
         bool addAll = list.Count == 0;
         foreach (int rate in s.GetAvailableBaudRates(null))
         {
             if (rate != 0)
             {
                 ToolStripMenuItem it = new ToolStripMenuItem();
                 it.Checked         = list.Count == 0 || list.Contains(rate.ToString());
                 it.CheckOnClick    = true;
                 it.CheckedChanged += It_CheckedChanged;
                 it.Text            = it.Name = rate.ToString();
                 rates.Add(it);
                 if (addAll)
                 {
                     Settings.Default.HdlcAddressBaudRates += ";" + rate.ToString();
                 }
             }
         }
         ScanBaudRateMnu.DropDownItems.AddRange(rates.ToArray());
         if (Settings.Default.HdlcAddressMedia == "GXSerial" && GXSerial.GetPortNames().Length != 0)
         {
             OnMediaTypeChanged(SerialMnu, null);
         }
         else
         {
             OnMediaTypeChanged(NetworkMnu, null);
         }
         if (Settings.Default.HdlcAddressUseOpticalProbe && media is GXSerial)
         {
             UseOpticalProbeMnu_Click(null, null);
         }
         if (Settings.Default.HdlcAddressScanBaudRates)
         {
             ScanBaudRateMnu_Click(null, null);
         }
         Manufacturers = new GXManufacturerCollection();
         GXManufacturerCollection.ReadManufacturerSettings(Manufacturers);
     }
     catch (Exception ex)
     {
         MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
         Close();
     }
 }
コード例 #6
0
ファイル: Program.cs プロジェクト: nnikos123/Gurux.DLMS.Net
 /// <summary>
 /// Read simulated values from the meter.
 /// </summary>
 static void ReadSimulatedValues(Settings settings)
 {
     Reader.GXDLMSReader reader = null;
     try
     {
         ////////////////////////////////////////
         //Initialize connection settings.
         if (settings.media is GXSerial)
         {
             GXSerial serial = settings.media as GXSerial;
             if (settings.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 (settings.media is GXNet)
         {
         }
         else
         {
             throw new Exception("Unknown media type.");
         }
         ////////////////////////////////////////
         reader = new Reader.GXDLMSReader(settings.client, settings.media, settings.trace, settings.invocationCounter, settings.iec);
         settings.media.Open();
         //Some meters need a break here.
         Thread.Sleep(1000);
         reader.ReadAll(settings.outputFile);
     }
     finally
     {
         if (reader != null)
         {
             reader.Close();
         }
     }
 }
コード例 #7
0
 /// <summary>
 /// Media type is changed.
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void OnMediaTypeChanged(object sender, EventArgs e)
 {
     try
     {
         if (media != null)
         {
             media.OnMediaStateChange -= OnMediaStateChange;
             media.OnReceived         -= OnReceived;
             media.OnTrace            -= MediaOnTrace;
         }
         bool isSerial = sender == SerialMnu || sender == SerialBtn;
         if (isSerial)
         {
             media                     = new GXSerial();
             media.Settings            = Settings.Default.HdlcAddressSerialSettings;
             media.OnMediaStateChange += OnMediaStateChange;
             media.OnReceived         += OnReceived;
             media.OnTrace            += MediaOnTrace;
             media.Trace               = TraceLevel.Verbose;
             if (GXSerial.GetPortNames().Length == 0)
             {
                 MediaSettingsMnu.Enabled = MediaSettingsMnu.Enabled = false;
             }
             Settings.Default.HdlcAddressMedia = "GXSerial";
         }
         else
         {
             media = new GXNet();
             (media as GXNet).ConfigurableSettings = Gurux.Net.AvailableMediaSettings.All & ~Gurux.Net.AvailableMediaSettings.Server;
             media.Settings            = Settings.Default.HdlcAddressNetworkSettings;
             media.OnMediaStateChange += OnMediaStateChange;
             media.OnReceived         += OnReceived;
             media.OnTrace            += MediaOnTrace;
             media.Trace = TraceLevel.Verbose;
             MediaSettingsMnu.Enabled          = MediaSettingsMnu.Enabled = true;
             Settings.Default.HdlcAddressMedia = "GXNet";
         }
         UpdateStatus("Ready.");
         SerialBtn.Checked        = UseOpticalProbeMnu.Enabled = SerialMnu.Checked = isSerial;
         NetworkBtn.Checked       = NetworkMnu.Checked = !isSerial;
         ScanBaudRatesBtn.Enabled = ScanBaudRateMnu.Enabled = OpticalProbeBtn.Enabled = UseOpticalProbeMnu.Enabled = isSerial;
     }
     catch (Exception ex)
     {
         MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
 }
コード例 #8
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);
        }
コード例 #9
0
ファイル: Settings.cs プロジェクト: davudjokar63/Gurux.Serial
 /// <summary>
 /// Constructor.
 /// </summary>
 public Settings(GXSerial target)
 {
     InitializeComponent();
     this.target = target;
 }
コード例 #10
0
ファイル: GXBridge.cs プロジェクト: lwbjun/Gurux.MQTT
        private static void InitializeIEC(TraceLevel trace, Media media)
        {
            GXSerial serial = (GXSerial)media.Target;

            serial.BaudRate = 300;
            serial.DataBits = 7;
            serial.Parity   = Parity.Even;
            serial.StopBits = StopBits.One;
            byte Terminator = (byte)0x0A;

            //Some meters need a little break.
            Thread.Sleep(1000);
            //Query device information.
            string data = "/?!\r\n";

            WriteLog(trace, "IEC Sending:" + data);
            if (media.WaitTime == 0)
            {
                media.WaitTime = 5;
            }
            ReceiveParameters <string> p = new ReceiveParameters <string>()
            {
                AllData  = false,
                Eop      = Terminator,
                WaitTime = media.WaitTime * 1000
            };

            lock (media.Target.Synchronous)
            {
                media.Target.Send(data, null);
                if (!media.Target.Receive(p))
                {
                    DiscIEC(media);
                    string str = "Failed to receive reply from the device in given time.";
                    WriteLog(trace, str);
                    media.Target.Send(data, null);
                    if (!media.Target.Receive(p))
                    {
                        throw new Exception(str);
                    }
                }
                //If echo is used.
                if (p.Reply == data)
                {
                    p.Reply = null;
                    if (!media.Target.Receive(p))
                    {
                        data = "Failed to receive reply from the device in given time.";
                        WriteLog(trace, data);
                        throw new Exception(data);
                    }
                }
            }
            WriteLog(trace, "IEC received: " + p.Reply);
            if (p.Reply[0] != '/')
            {
                p.WaitTime = 100;
                media.Target.Receive(p);
                throw new Exception("Invalid responce.");
            }
            string manufactureID = p.Reply.Substring(1, 3);
            char   baudrate      = p.Reply[4];
            int    BaudRate;

            switch (baudrate)
            {
            case '0':
                BaudRate = 300;
                break;

            case '1':
                BaudRate = 600;
                break;

            case '2':
                BaudRate = 1200;
                break;

            case '3':
                BaudRate = 2400;
                break;

            case '4':
                BaudRate = 4800;
                break;

            case '5':
                BaudRate = 9600;
                break;

            case '6':
                BaudRate = 19200;
                break;

            default:
                throw new Exception("Unknown baud rate.");
            }
            if (media.MaximumBaudRate != 0)
            {
                BaudRate = media.MaximumBaudRate;
                baudrate = GetIecBaudRate(BaudRate);
                WriteLog(trace, "Maximum BaudRate is set to : " + BaudRate.ToString());
            }
            WriteLog(trace, "BaudRate is : " + BaudRate.ToString());
            //Send ACK
            //Send Protocol control character
            // "2" HDLC protocol procedure (Mode E)
            byte controlCharacter = (byte)'2';
            //Send Baud rate character
            //Mode control character
            byte ModeControlCharacter = (byte)'2';

            //"2" //(HDLC protocol procedure) (Binary mode)
            //Set mode E.
            byte[] arr = new byte[] { 0x06, controlCharacter, (byte)baudrate, ModeControlCharacter, 13, 10 };
            WriteLog(trace, "Moving to mode E. " + GXCommon.ToHex(arr));
            lock (media.Target.Synchronous)
            {
                p.Reply = null;
                media.Target.Send(arr, null);
                p.WaitTime = 2000;
                //Note! All meters do not echo this.
                media.Target.Receive(p);
                if (p.Reply != null)
                {
                    WriteLog(trace, "Received: " + p.Reply);
                }
                media.Target.Close();
                serial.BaudRate = BaudRate;
                serial.DataBits = 8;
                serial.Parity   = Parity.None;
                serial.StopBits = StopBits.One;
                serial.Open();
                //Some meters need this sleep. Do not remove.
                Thread.Sleep(1000);
            }
        }
コード例 #11
0
ファイル: Settings.cs プロジェクト: giapdangle/Gurux.Serial
		/// <summary>
		/// Constructor.
		/// </summary>
        public Settings(GXSerial target)
        {
            InitializeComponent();
            Target = target;
        }
コード例 #12
0
        internal static int GetParameters(string[] args, GXSettings settings)
        {
            List <GXCmdParameter> parameters = GXCommon.GetParameters(args, "bh:p:c:s:r:it:a:p:wP:x:S:e:C:");
            GXNet net = null;

            foreach (GXCmdParameter it in parameters)
            {
                switch (it.Tag)
                {
                case 'w':
                    settings.client.InterfaceType = InterfaceType.WRAPPER;
                    break;

                case 'r':
                    if (string.Compare(it.Value, "sn", true) == 0)
                    {
                        settings.client.UseLogicalNameReferencing = false;
                    }
                    else if (string.Compare(it.Value, "ln", true) == 0)
                    {
                        settings.client.UseLogicalNameReferencing = true;
                    }
                    else
                    {
                        throw new ArgumentException("Invalid reference option.");
                    }
                    break;

                case 'h':
                    //Host address.
                    if (settings.media == null)
                    {
                        settings.media = new GXNet();
                    }
                    net          = settings.media as GXNet;
                    net.HostName = it.Value;
                    break;

                case 't':
                    //Trace.
                    try
                    {
                        settings.trace = (TraceLevel)Enum.Parse(typeof(TraceLevel), it.Value);
                    }
                    catch (Exception)
                    {
                        throw new ArgumentException("Invalid Authentication option. (Error, Warning, Info, Verbose, Off)");
                    }
                    break;

                case 'p':
                    //Port.
                    if (settings.media == null)
                    {
                        settings.media = new GXNet();
                    }
                    net      = settings.media as GXNet;
                    net.Port = int.Parse(it.Value);
                    break;

                case 'P':    //Password
                    settings.client.Password = ASCIIEncoding.ASCII.GetBytes(it.Value);
                    break;

                case 'i':
                    //IEC.
                    settings.iec = true;
                    break;

                case 'e':
                    //Exclude object type.
                    foreach (string ot in it.Value.Split(','))
                    {
                        settings.excludedObjects.Add((ObjectType)Enum.Parse(typeof(ObjectType), ot));
                    }
                    break;

                case 'S':    //Serial Port
                    settings.media = new GXSerial();
                    GXSerial serial = settings.media as GXSerial;
                    string[] tmp    = it.Value.Split(':');
                    serial.PortName = tmp[0];
                    if (tmp.Length > 1)
                    {
                        serial.BaudRate = int.Parse(tmp[1]);
                        serial.DataBits = int.Parse(tmp[2].Substring(0, 1));
                        serial.Parity   = (Parity)Enum.Parse(typeof(Parity), tmp[2].Substring(1, tmp[2].Length - 2));
                        serial.StopBits = (StopBits)int.Parse(tmp[2].Substring(tmp[2].Length - 1, 1));
                    }
                    else
                    {
                        serial.BaudRate = 9600;
                        serial.DataBits = 8;
                        serial.Parity   = Parity.None;
                        serial.StopBits = StopBits.One;
                    }
                    break;

                case 'a':
                    try
                    {
                        settings.client.Authentication = (Authentication)Enum.Parse(typeof(Authentication), it.Value);
                    }
                    catch (Exception)
                    {
                        throw new ArgumentException("Invalid Authentication option. (None, Low, High, HighMd5, HighSha1, HighGmac, HighSha256)");
                    }
                    break;

                case 'C':
                    settings.tests = 0;
                    foreach (string ot in it.Value.Split(','))
                    {
                        settings.tests |= (ConformanceTest)Enum.Parse(typeof(ConformanceTest), ot);
                    }
                    break;

                case 'o':
                    break;

                case 'c':
                    settings.client.ClientAddress = int.Parse(it.Value);
                    break;

                case 's':
                    settings.client.ServerAddress = int.Parse(it.Value);
                    break;

                case 'x':
                    settings.path = it.Value;
                    break;

                case '?':
                    switch (it.Tag)
                    {
                    case 'c':
                        throw new ArgumentException("Missing mandatory client option.");

                    case 's':
                        throw new ArgumentException("Missing mandatory server option.");

                    case 'h':
                        throw new ArgumentException("Missing mandatory host name option.");

                    case 'p':
                        throw new ArgumentException("Missing mandatory port option.");

                    case 'r':
                        throw new ArgumentException("Missing mandatory reference option.");

                    case 'a':
                        throw new ArgumentException("Missing mandatory authentication option.");

                    case 'S':
                        throw new ArgumentException("Missing mandatory Serial port option.\n");

                    case 't':
                        throw new ArgumentException("Missing mandatory trace option.\n");

                    case 'e':
                        throw new ArgumentException("Missing mandatory exclude object type option.\n");

                    default:
                        ShowHelp();
                        return(1);
                    }

                default:
                    ShowHelp();
                    return(1);
                }
            }
            if (settings.media == null)
            {
                ShowHelp();
                return(1);
            }
            return(0);
        }
コード例 #13
0
ファイル: Program.cs プロジェクト: IPresnyakov/Gurux.DLMS.Net
        static int Main(string[] args)
        {
            Settings settings = new Settings();

            Reader.GXDLMSReader reader = null;
            try
            {
                ////////////////////////////////////////
                //Handle command line parameters.
                int ret = GetParameters(args, settings);
                if (ret != 0)
                {
                    return(ret);
                }

                ////////////////////////////////////////
                //Initialize connection settings.
                if (settings.media is GXSerial)
                {
                    GXSerial serial = settings.media as GXSerial;
                    if (settings.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 (settings.media is GXNet)
                {
                }
                else
                {
                    throw new Exception("Unknown media type.");
                }
                ////////////////////////////////////////
                reader = new Reader.GXDLMSReader(settings.client, settings.media, settings.trace);
                settings.media.Open();
                if (settings.readObjects.Count != 0)
                {
                    reader.InitializeConnection();
                    reader.GetAssociationView(false);
                    foreach (KeyValuePair <string, int> it in settings.readObjects)
                    {
                        object val = reader.Read(settings.client.Objects.FindByLN(ObjectType.None, it.Key), it.Value);
                        reader.ShowValue(val, it.Value);
                    }
                }
                else
                {
                    reader.ReadAll(false);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.ToString());
                if (System.Diagnostics.Debugger.IsAttached)
                {
                    Console.ReadKey();
                }
                return(1);
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }
                if (System.Diagnostics.Debugger.IsAttached)
                {
                    Console.WriteLine("Ended. Press any key to continue.");
                    Console.ReadKey();
                }
            }
            return(0);
        }
コード例 #14
0
ファイル: Program.cs プロジェクト: IPresnyakov/Gurux.DLMS.Net
        static int GetParameters(string[] args, Settings settings)
        {
            List <GXCmdParameter> parameters = GXCommon.GetParameters(args, "h:p:c:s:r:it:a:p:wP:g:");
            GXNet net = null;

            foreach (GXCmdParameter it in parameters)
            {
                switch (it.Tag)
                {
                case 'w':
                    settings.client.InterfaceType = InterfaceType.WRAPPER;
                    break;

                case 'r':
                    if (string.Compare(it.Value, "sn", true) == 0)
                    {
                        settings.client.UseLogicalNameReferencing = false;
                    }
                    else if (string.Compare(it.Value, "ln", true) == 0)
                    {
                        settings.client.UseLogicalNameReferencing = true;
                    }
                    else
                    {
                        throw new ArgumentException("Invalid reference option.");
                    }
                    break;

                case 'h':
                    //Host address.
                    if (settings.media == null)
                    {
                        settings.media = new GXNet();
                    }
                    net          = settings.media as GXNet;
                    net.HostName = it.Value;
                    break;

                case 't':
                    //Trace.
                    try
                    {
                        settings.trace = (TraceLevel)Enum.Parse(typeof(TraceLevel), it.Value);
                    }
                    catch (Exception)
                    {
                        throw new ArgumentException("Invalid Authentication option. (Error, Warning, Info, Verbose, Off)");
                    }
                    break;

                case 'p':
                    //Port.
                    if (settings.media == null)
                    {
                        settings.media = new GXNet();
                    }
                    net      = settings.media as GXNet;
                    net.Port = int.Parse(it.Value);
                    break;

                case 'P':    //Password
                    settings.client.Password = ASCIIEncoding.ASCII.GetBytes(it.Value);
                    break;

                case 'i':
                    //IEC.
                    settings.iec = true;
                    break;

                case 'g':
                    //Get (read) selected objects.
                    foreach (string o in it.Value.Split(new char[] { ';', ',' }))
                    {
                        string[] tmp = o.Split(new char[] { ':' });
                        if (tmp.Length != 2)
                        {
                            throw new ArgumentOutOfRangeException("Invalid Logical name or attribute index.");
                        }
                        settings.readObjects.Add(new KeyValuePair <string, int>(tmp[0].Trim(), int.Parse(tmp[1].Trim())));
                    }
                    break;

                case 'S':    //Serial Port
                    settings.media = new GXSerial();
                    GXSerial serial = settings.media as GXSerial;
                    serial.PortName = it.Value;
                    break;

                case 'a':
                    try
                    {
                        if (string.Compare("None", it.Value, true) == 0)
                        {
                            settings.client.Authentication = Authentication.None;
                        }
                        else if (string.Compare("Low", it.Value, true) == 0)
                        {
                            settings.client.Authentication = Authentication.Low;
                        }
                        else if (string.Compare("High", it.Value, true) == 0)
                        {
                            settings.client.Authentication = Authentication.High;
                        }
                        else if (string.Compare("HighMd5", it.Value, true) == 0)
                        {
                            settings.client.Authentication = Authentication.HighMD5;
                        }
                        else if (string.Compare("HighSha1", it.Value, true) == 0)
                        {
                            settings.client.Authentication = Authentication.HighSHA1;
                        }
                        else if (string.Compare("HighSha256", it.Value, true) == 0)
                        {
                            settings.client.Authentication = Authentication.HighSHA256;
                        }
                        else if (string.Compare("HighGMac", it.Value, true) == 0)
                        {
                            settings.client.Authentication = Authentication.HighGMAC;
                        }
                        else
                        {
                            throw new ArgumentException("Invalid Authentication option: '" + it.Value + "'. (None, Low, High, HighMd5, HighSha1, HighGMac, HighSha256)");
                        }
                    }
                    catch (Exception)
                    {
                        throw new ArgumentException("Invalid Authentication option: '" + it.Value + "'. (None, Low, High, HighMd5, HighSha1, HighGMac, HighSha256)");
                    }
                    break;

                case 'o':
                    break;

                case 'c':
                    settings.client.ClientAddress = int.Parse(it.Value);
                    break;

                case 's':
                    settings.client.ServerAddress = int.Parse(it.Value);
                    break;

                case '?':
                    switch (it.Tag)
                    {
                    case 'c':
                        throw new ArgumentException("Missing mandatory client option.");

                    case 's':
                        throw new ArgumentException("Missing mandatory server option.");

                    case 'h':
                        throw new ArgumentException("Missing mandatory host name option.");

                    case 'p':
                        throw new ArgumentException("Missing mandatory port option.");

                    case 'r':
                        throw new ArgumentException("Missing mandatory reference option.");

                    case 'a':
                        throw new ArgumentException("Missing mandatory authentication option.");

                    case 'S':
                        throw new ArgumentException("Missing mandatory Serial port option.");

                    case 't':
                        throw new ArgumentException("Missing mandatory trace option.");

                    case 'g':
                        throw new ArgumentException("Missing mandatory OBIS code option.");

                    default:
                        ShowHelp();
                        return(1);
                    }

                default:
                    ShowHelp();
                    return(1);
                }
            }
            if (settings.media == null)
            {
                ShowHelp();
                return(1);
            }
            return(0);
        }
コード例 #15
0
        public static int GetParameters(string[] args, Settings settings)
        {
            string[] tmp;
            List <GXCmdParameter> parameters = GXCommon.GetParameters(args, "h:p:c:s:r:i:It:a:P:g:S:C:n:v:o:T:A:B:D:d:l:F:K:k:m:");
            GXNet net = null;

            foreach (GXCmdParameter it in parameters)
            {
                switch (it.Tag)
                {
                case 'r':
                    if (string.Compare(it.Value, "sn", true) == 0)
                    {
                        settings.client.UseLogicalNameReferencing = false;
                    }
                    else if (string.Compare(it.Value, "ln", true) == 0)
                    {
                        settings.client.UseLogicalNameReferencing = true;
                    }
                    else
                    {
                        throw new ArgumentException("Invalid reference option.");
                    }
                    break;

                case 'h':
                    //Host address.
                    if (settings.media == null)
                    {
                        settings.media = new GXNet();
                    }
                    net          = settings.media as GXNet;
                    net.HostName = it.Value;
                    break;

                case 't':
                    //Trace.
                    try
                    {
                        settings.trace = (TraceLevel)Enum.Parse(typeof(TraceLevel), it.Value);
                    }
                    catch (Exception)
                    {
                        throw new ArgumentException("Invalid trace level option. (Error, Warning, Info, Verbose, Off)");
                    }
                    break;

                case 'p':
                    //Port.
                    if (settings.media == null)
                    {
                        settings.media = new GXNet();
                    }
                    net      = settings.media as GXNet;
                    net.Port = int.Parse(it.Value);
                    break;

                case 'P':    //Password
                    settings.client.Password = ASCIIEncoding.ASCII.GetBytes(it.Value);
                    break;

                case 'i':
                    try
                    {
                        settings.client.InterfaceType = (InterfaceType)Enum.Parse(typeof(InterfaceType), it.Value);
                        settings.client.Plc.Reset();
                    }
                    catch (Exception)
                    {
                        throw new ArgumentException("Invalid interface type option. (HDLC, WRAPPER, HdlcWithModeE, Plc, PlcHdlc)");
                    }
                    break;

                case 'I':
                    //AutoIncreaseInvokeID.
                    settings.client.AutoIncreaseInvokeID = true;
                    break;

                case 'v':
                    settings.invocationCounter = it.Value.Trim();
                    Objects.GXDLMSObject.ValidateLogicalName(settings.invocationCounter);
                    break;

                case 'g':
                    //Get (read) selected objects.
                    foreach (string o in it.Value.Split(new char[] { ';', ',' }))
                    {
                        tmp = o.Split(new char[] { ':' });
                        if (tmp.Length != 2)
                        {
                            throw new ArgumentOutOfRangeException("Invalid Logical name or attribute index.");
                        }
                        settings.readObjects.Add(new KeyValuePair <string, int>(tmp[0].Trim(), int.Parse(tmp[1].Trim())));
                    }
                    break;

                case 'S':    //Serial Port
                    settings.media = new GXSerial();
                    GXSerial serial = settings.media as GXSerial;
                    tmp             = it.Value.Split(':');
                    serial.PortName = tmp[0];
                    if (tmp.Length > 1)
                    {
                        serial.BaudRate = int.Parse(tmp[1]);
                        serial.DataBits = int.Parse(tmp[2].Substring(0, 1));
                        serial.Parity   = (Parity)Enum.Parse(typeof(Parity), tmp[2].Substring(1, tmp[2].Length - 2));
                        serial.StopBits = (StopBits)int.Parse(tmp[2].Substring(tmp[2].Length - 1, 1));
                    }
                    else
                    {
                        if (settings.client.InterfaceType == InterfaceType.HdlcWithModeE)
                        {
                            serial.BaudRate = 300;
                            serial.DataBits = 7;
                            serial.Parity   = Parity.Even;
                            serial.StopBits = StopBits.One;
                        }
                        else
                        {
                            serial.BaudRate = 9600;
                            serial.DataBits = 8;
                            serial.Parity   = Parity.None;
                            serial.StopBits = StopBits.One;
                        }
                    }
                    break;

                case 'a':
                    try
                    {
                        if (string.Compare("None", it.Value, true) == 0)
                        {
                            settings.client.Authentication = Authentication.None;
                        }
                        else if (string.Compare("Low", it.Value, true) == 0)
                        {
                            settings.client.Authentication = Authentication.Low;
                        }
                        else if (string.Compare("High", it.Value, true) == 0)
                        {
                            settings.client.Authentication = Authentication.High;
                        }
                        else if (string.Compare("HighMd5", it.Value, true) == 0)
                        {
                            settings.client.Authentication = Authentication.HighMD5;
                        }
                        else if (string.Compare("HighSha1", it.Value, true) == 0)
                        {
                            settings.client.Authentication = Authentication.HighSHA1;
                        }
                        else if (string.Compare("HighSha256", it.Value, true) == 0)
                        {
                            settings.client.Authentication = Authentication.HighSHA256;
                        }
                        else if (string.Compare("HighGMac", it.Value, true) == 0)
                        {
                            settings.client.Authentication = Authentication.HighGMAC;
                        }
                        else if (string.Compare("HighECDSA", it.Value, true) == 0)
                        {
                            settings.client.Authentication = Authentication.HighECDSA;
                        }
                        else
                        {
                            throw new ArgumentException("Invalid Authentication option: '" + it.Value + "'. (None, Low, High, HighMd5, HighSha1, HighGMac, HighSha256)");
                        }
                    }
                    catch (Exception)
                    {
                        throw new ArgumentException("Invalid Authentication option: '" + it.Value + "'. (None, Low, High, HighMd5, HighSha1, HighGMac, HighSha256)");
                    }
                    break;

                case 'C':
                    try
                    {
                        settings.client.Ciphering.Security = Convert.ToByte(Enum.Parse(typeof(Security), it.Value));
                    }
                    catch (Exception)
                    {
                        throw new ArgumentException("Invalid Ciphering option '" + it.Value + "'. (None, Authentication, Encryption, AuthenticationEncryption)");
                    }
                    break;

                case 'T':
                    settings.client.Ciphering.SystemTitle = GXCommon.HexToBytes(it.Value);
                    break;

                case 'A':
                    settings.client.Ciphering.AuthenticationKey = GXCommon.HexToBytes(it.Value);
                    break;

                case 'B':
                    settings.client.Ciphering.BlockCipherKey = GXCommon.HexToBytes(it.Value);
                    break;

                case 'D':
                    settings.client.Ciphering.DedicatedKey = GXCommon.HexToBytes(it.Value);
                    break;

                case 'F':
                    settings.client.Ciphering.InvocationCounter = UInt32.Parse(it.Value.Trim());
                    break;

                case 'K':
                    GXPkcs8 cert1 = GXPkcs8.Load(it.Value);
                    settings.client.Ciphering.SigningKeyPair = new KeyValuePair <GXPrivateKey, GXPublicKey>(cert1.PrivateKey, cert1.PublicKey);
                    Console.WriteLine("Client Private key: " + GXDLMSTranslator.ToHex(cert1.PrivateKey.RawValue));
                    Console.WriteLine("Client Public key: " + GXDLMSTranslator.ToHex(cert1.PublicKey.RawValue));
                    break;

                case 'k':
                    GXx509Certificate cert = GXx509Certificate.Load(it.Value);
                    if ((cert.KeyUsage & ASN.Enums.KeyUsage.DigitalSignature) == 0)
                    {
                        throw new Exception("This certificate is not used for digital signature.");
                    }
                    settings.client.Ciphering.PublicKeys.Add(new KeyValuePair <CertificateType, GXx509Certificate>(CertificateType.DigitalSignature, cert));
                    string[] sn = cert.Subject.Split('=');
                    if (sn.Length != 2)
                    {
                        throw new ArgumentOutOfRangeException("Invalid public key subject.");
                    }
                    settings.client.Ciphering.SystemTitle = GXDLMSTranslator.HexToBytes(sn[1]);
                    Console.WriteLine("Server Public key: " + GXDLMSTranslator.ToHex(cert.PublicKey.RawValue));
                    break;

                case 'o':
                    settings.outputFile = it.Value;
                    break;

                case 'd':
                    try
                    {
                        settings.client.Standard = (Standard)Enum.Parse(typeof(Standard), it.Value);
                        if (settings.client.Standard == Standard.Italy || settings.client.Standard == Standard.India || settings.client.Standard == Standard.SaudiArabia)
                        {
                            settings.client.UseUtc2NormalTime = true;
                        }
                    }
                    catch (Exception)
                    {
                        throw new ArgumentException("Invalid DLMS standard option '" + it.Value + "'. (DLMS, India, Italy, SaudiArabia, IDIS)");
                    }
                    break;

                case 'c':
                    settings.client.ClientAddress = int.Parse(it.Value);
                    break;

                case 's':
                    if (settings.client.ServerAddress != 1)
                    {
                        settings.client.ServerAddress = GXDLMSClient.GetServerAddress(settings.client.ServerAddress, int.Parse(it.Value));
                    }
                    else
                    {
                        settings.client.ServerAddress = int.Parse(it.Value);
                    }
                    break;

                case 'l':
                    settings.client.ServerAddress = GXDLMSClient.GetServerAddress(int.Parse(it.Value), settings.client.ServerAddress);
                    break;

                case 'n':
                    settings.client.ServerAddress = GXDLMSClient.GetServerAddress(int.Parse(it.Value));
                    break;

                case 'm':
                    settings.client.Plc.MacDestinationAddress = UInt16.Parse(it.Value);
                    break;

                case '?':
                    switch (it.Tag)
                    {
                    case 'c':
                        throw new ArgumentException("Missing mandatory client option.");

                    case 's':
                        throw new ArgumentException("Missing mandatory server option.");

                    case 'h':
                        throw new ArgumentException("Missing mandatory host name option.");

                    case 'p':
                        throw new ArgumentException("Missing mandatory port option.");

                    case 'r':
                        throw new ArgumentException("Missing mandatory reference option.");

                    case 'a':
                        throw new ArgumentException("Missing mandatory authentication option.");

                    case 'S':
                        throw new ArgumentException("Missing mandatory Serial port option.");

                    case 't':
                        throw new ArgumentException("Missing mandatory trace option.");

                    case 'g':
                        throw new ArgumentException("Missing mandatory OBIS code option.");

                    case 'C':
                        throw new ArgumentException("Missing mandatory Ciphering option.");

                    case 'v':
                        throw new ArgumentException("Missing mandatory invocation counter logical name option.");

                    case 'T':
                        throw new ArgumentException("Missing mandatory system title option.");

                    case 'A':
                        throw new ArgumentException("Missing mandatory authentication key option.");

                    case 'B':
                        throw new ArgumentException("Missing mandatory block cipher key option.");

                    case 'D':
                        throw new ArgumentException("Missing mandatory dedicated key option.");

                    case 'F':
                        throw new ArgumentException("Missing mandatory frame counter option.");

                    case 'd':
                        throw new ArgumentException("Missing mandatory DLMS standard option.");

                    case 'K':
                        throw new ArgumentException("Missing mandatory private key file option.");

                    case 'k':
                        throw new ArgumentException("Missing mandatory public key file option.");

                    case 'l':
                        throw new ArgumentException("Missing mandatory logical server address option.");

                    case 'm':
                        throw new ArgumentException("Missing mandatory MAC destination address option.");

                    default:
                        ShowHelp();
                        return(1);
                    }

                default:
                    ShowHelp();
                    return(1);
                }
            }
            if (settings.media == null)
            {
                ShowHelp();
                return(1);
            }
            return(0);
        }
コード例 #16
0
ファイル: Program.cs プロジェクト: s9703830/SmartVillage
        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();
                }
            }
        }
コード例 #17
0
        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);
            }
        }
コード例 #18
0
ファイル: Program.cs プロジェクト: 01F0/Gurux.DLMS.Net
        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();
                }
            }
        }
コード例 #19
0
        private async void DoWork(object ínfo)
        {
            //Give some time DB server to start up.
            Thread.Sleep(1000);
            GetNextTaskResponse ret = null;

            System.Net.Http.HttpResponseMessage response;
            //Don't wait reply. It might that DB server is not up yet.
            if (ínfo != null)
            {
                using (response = await client.PostAsJsonAsync(Startup.ServerAddress + "/api/reader/AddReader", new AddReader()
                {
                    Reader = ínfo as GXReaderInfo
                }))
                {
                    Helpers.CheckStatus(response);
                }
            }
            _logger.LogInformation("Reader Service is started.");
            while (!_cancellationToken.IsCancellationRequested)
            {
                try
                {
                    using (response = await client.PostAsJsonAsync(Startup.ServerAddress + "/api/task/GetNextTask", new GetNextTask()))
                    {
                        Helpers.CheckStatus(response);
                        ret = await response.Content.ReadAsAsync <GetNextTaskResponse>();
                    }
                    if (ret.Tasks != null)
                    {
                        int                pos = 0;
                        GXDevice           dev;
                        GXDLMSSecureClient cl;
                        using (response = await client.PostAsJsonAsync(Startup.ServerAddress + "/api/device/ListDevices", new ListDevices()
                        {
                            Ids = new[] { ret.Tasks[0].Object.DeviceId }
                        }))
                        {
                            Helpers.CheckStatus(response);
                            ListDevicesResponse r = await response.Content.ReadAsAsync <ListDevicesResponse>();

                            if (r.Devices == null || r.Devices.Length == 0)
                            {
                                continue;
                            }
                            dev = r.Devices[0];
                        }
                        IGXMedia media;
                        if (string.Compare(dev.MediaType, typeof(GXNet).FullName, true) == 0)
                        {
                            media = new GXNet();
                        }
                        else if (string.Compare(dev.MediaType, typeof(GXSerial).FullName, true) == 0)
                        {
                            media = new GXSerial();
                        }
                        else if (string.Compare(dev.MediaType, typeof(GXTerminal).FullName, true) == 0)
                        {
                            media = new GXTerminal();
                        }
                        else
                        {
                            Type type = Type.GetType(dev.MediaType);
                            if (type == null)
                            {
                                string ns = "";
                                pos = dev.MediaType.LastIndexOf('.');
                                if (pos != -1)
                                {
                                    ns = dev.MediaType.Substring(0, pos);
                                }
                                foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
                                {
                                    if (assembly.GetName().Name == ns)
                                    {
                                        if (assembly.GetType(dev.MediaType, false, true) != null)
                                        {
                                            type = assembly.GetType(dev.MediaType);
                                        }
                                    }
                                }
                            }
                            if (type == null)
                            {
                                throw new Exception("Invalid media type: " + dev.MediaType);
                            }
                            media = (IGXMedia)Activator.CreateInstance(type);
                        }
                        if (media == null)
                        {
                            throw new Exception("Unknown media type '" + dev.MediaType + "'.");
                        }
                        media.Settings = dev.MediaSettings;
                        GXDLMSReader reader;
                        //Read frame counter from the meter.
                        if (dev.Security != 0)
                        {
                            cl = new GXDLMSSecureClient(dev.UseLogicalNameReferencing, 16, dev.PhysicalAddress,
                                                        Authentication.None, null, (InterfaceType)dev.InterfaceType);
                            reader = new GXDLMSReader(cl, media, _logger);
                            media.Open();
                            reader.InitializeConnection();
                            //Read Innovation counter.
                            GXDLMSData d = new GXDLMSData(dev.FrameCounter);
                            reader.Read(d, 2);
                            dev.InvocationCounter = 1 + Convert.ToUInt32(d.Value);
                            reader.Disconnect();
                            media.Close();
                        }
                        cl = new GXDLMSSecureClient(dev.UseLogicalNameReferencing, dev.ClientAddress, dev.PhysicalAddress,
                                                    (Authentication)dev.Authentication, dev.Password, (InterfaceType)dev.InterfaceType);
                        if (dev.HexPassword != null && dev.HexPassword.Length != 0)
                        {
                            cl.Password = dev.HexPassword;
                        }
                        cl.UseUtc2NormalTime     = dev.UtcTimeZone;
                        cl.Standard              = dev.Standard;
                        cl.Ciphering.SystemTitle = GXCommon.HexToBytes(dev.ClientSystemTitle);
                        if (cl.Ciphering.SystemTitle != null && cl.Ciphering.SystemTitle.Length == 0)
                        {
                            cl.Ciphering.SystemTitle = null;
                        }
                        cl.Ciphering.BlockCipherKey = GXCommon.HexToBytes(dev.BlockCipherKey);
                        if (cl.Ciphering.BlockCipherKey != null && cl.Ciphering.BlockCipherKey.Length == 0)
                        {
                            cl.Ciphering.BlockCipherKey = null;
                        }
                        cl.Ciphering.AuthenticationKey = GXCommon.HexToBytes(dev.AuthenticationKey);
                        if (cl.Ciphering.AuthenticationKey != null && cl.Ciphering.AuthenticationKey.Length == 0)
                        {
                            cl.Ciphering.AuthenticationKey = null;
                        }
                        cl.ServerSystemTitle = GXCommon.HexToBytes(dev.DeviceSystemTitle);
                        if (cl.ServerSystemTitle != null && cl.ServerSystemTitle.Length == 0)
                        {
                            cl.ServerSystemTitle = null;
                        }
                        cl.Ciphering.InvocationCounter = dev.InvocationCounter;
                        cl.Ciphering.Security          = (Security)dev.Security;
                        reader = new GXDLMSReader(cl, media, _logger);
                        media.Open();
                        reader.InitializeConnection();
                        pos = 0;
                        int count = ret.Tasks.Length;
                        foreach (GXTask task in ret.Tasks)
                        {
                            ++pos;
                            try
                            {
                                GXDLMSObject obj = GXDLMSClient.CreateObject((ObjectType)task.Object.ObjectType);
                                obj.LogicalName = task.Object.LogicalName;
                                obj.ShortName   = task.Object.ShortName;
                                if (task.TaskType == TaskType.Write)
                                {
                                    if (obj.LogicalName == "0.0.1.1.0.255" && task.Index == 2)
                                    {
                                        cl.UpdateValue(obj, task.Index, GXDateTime.ToUnixTime(DateTime.UtcNow));
                                    }
                                    else
                                    {
                                        cl.UpdateValue(obj, task.Index, GXDLMSTranslator.XmlToValue(task.Data));
                                    }
                                    reader.Write(obj, task.Index);
                                }
                                else if (task.TaskType == TaskType.Action)
                                {
                                    reader.Method(obj, task.Index, GXDLMSTranslator.XmlToValue(task.Data), DataType.None);
                                }
                                else if (task.TaskType == TaskType.Read)
                                {
                                    //Reading the meter.
                                    if (task.Object.Attributes[0].DataType != 0)
                                    {
                                        obj.SetDataType(task.Index, (DataType)task.Object.Attributes[0].DataType);
                                    }
                                    if (task.Object.Attributes[0].UIDataType != 0)
                                    {
                                        obj.SetUIDataType(task.Index, (DataType)task.Object.Attributes[0].UIDataType);
                                    }
                                    Reader.Read(_logger, client, reader, task, media, obj);
                                    if (task.Object.Attributes[0].DataType == 0)
                                    {
                                        task.Object.Attributes[0].DataType = (int)obj.GetDataType(task.Index);
                                        if (task.Object.Attributes[0].UIDataType == 0)
                                        {
                                            task.Object.Attributes[0].UIDataType = (int)obj.GetUIDataType(task.Index);
                                        }
                                        UpdateDatatype u = new UpdateDatatype()
                                        {
                                            Items = new GXAttribute[] { task.Object.Attributes[0] }
                                        };
                                        response = client.PostAsJsonAsync(Startup.ServerAddress + "/api/Object/UpdateDatatype", u).Result;
                                        Helpers.CheckStatus(response);
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                task.Result = ex.Message;
                                AddError error = new AddError();
                                error.Error = new GXError()
                                {
                                    DeviceId = dev.Id,
                                    Error    = "Failed to " + task.TaskType + " " + task.Object.LogicalName + ":" + task.Index + ". " + ex.Message
                                };
                                _logger.LogError(error.Error.Error);
                                using (response = await client.PostAsJsonAsync(Startup.ServerAddress + "/api/error/AddError", error))
                                {
                                    Helpers.CheckStatus(response);
                                    await response.Content.ReadAsAsync <AddErrorResponse>();
                                }
                            }
                            task.End = DateTime.Now;
                            //Close connection after last task is executed.
                            //This must done because there might be new task to execute.
                            if (count == pos)
                            {
                                try
                                {
                                    reader.Close();
                                }
                                catch (Exception ex)
                                {
                                    task.Result = ex.Message;
                                    AddError error = new AddError();
                                    error.Error = new GXError()
                                    {
                                        DeviceId = dev.Id,
                                        Error    = "Failed to close the connection. " + ex.Message
                                    };
                                    _logger.LogError(error.Error.Error);
                                    using (response = await client.PostAsJsonAsync(Startup.ServerAddress + "/api/error/AddError", error))
                                    {
                                        Helpers.CheckStatus(response);
                                        await response.Content.ReadAsAsync <AddErrorResponse>();
                                    }
                                }
                            }
                            //Update execution time.
                            response = client.PostAsJsonAsync(Startup.ServerAddress + "/api/task/TaskReady", new TaskReady()
                            {
                                Tasks = new GXTask[] { task }
                            }).Result;
                            Helpers.CheckStatus(response);
                        }
                    }
                    else
                    {
                        try
                        {
                            using (response = await client.PostAsJsonAsync(Startup.ServerAddress + "/api/task/WaitChange", new WaitChange()
                            {
                                Change = TargetType.Tasks, Time = lastUpdated, WaitTime = _waitTime
                            }))
                            {
                                Helpers.CheckStatus(response);
                                {
                                    WaitChangeResponse r = await response.Content.ReadAsAsync <WaitChangeResponse>();

                                    if (r.Time > lastUpdated)
                                    {
                                        lastUpdated = r.Time;
                                    }
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            if (!_cancellationToken.IsCancellationRequested)
                            {
                                break;
                            }
                            _cancellationToken.WaitHandle.WaitOne(TimeSpan.FromSeconds(10));
                        }
                    }
                }
                catch (Exception ex)
                {
                    //If app is closing.
                    if (_cancellationToken.IsCancellationRequested)
                    {
                        break;
                    }
                    if (ret == null)
                    {
                        _logger.LogError("Failed to connect to the DB server.");
                    }
                    else
                    {
                        AddError error = new AddError();
                        error.Error = new GXError()
                        {
                            DeviceId = ret.Tasks[0].Object.DeviceId,
                            Error    = "Failed to " + ret.Tasks[0].TaskType + " " + ret.Tasks[0].Object.LogicalName + ":" + ret.Tasks[0].Index + ". " + ex.Message
                        };
                        using (response = await client.PostAsJsonAsync(Startup.ServerAddress + "/api/error/AddError", error))
                        {
                            if (ret.Tasks != null)
                            {
                                DateTime now = DateTime.Now;
                                foreach (GXTask it in ret.Tasks)
                                {
                                    it.Result = ex.Message;
                                    it.End    = now;
                                }
                                response = await client.PostAsJsonAsync(Startup.ServerAddress + "/api/task/TaskReady", new TaskReady()
                                {
                                    Tasks = ret.Tasks
                                });
                            }
                        }
                    }
                    _logger.LogError(ex.Message);
                }
            }
        }
コード例 #20
0
        static int Main(string[] args)
        {
            Settings settings = new Settings();

            Reader.GXDLMSReader reader = null;
            try
            {
                ////////////////////////////////////////
                //Handle command line parameters.
                int ret = Settings.GetParameters(args, settings);
                if (ret != 0)
                {
                    return(ret);
                }
                ////////////////////////////////////////
                //Initialize connection settings.
                if (settings.media is GXSerial)
                {
                    GXSerial serial = settings.media as GXSerial;
                    if (settings.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 (settings.media is GXNet)
                {
                }
                else
                {
                    throw new Exception("Unknown media type.");
                }
                ////////////////////////////////////////
                reader = new Reader.GXDLMSReader(settings.client, settings.media, settings.trace, settings.invocationCounter, settings.iec);
                settings.media.Open();
                //Some meters need a break here.
                Thread.Sleep(1000);
                if (settings.readObjects.Count != 0)
                {
                    bool read = false;
                    if (settings.outputFile != null)
                    {
                        try
                        {
                            settings.client.Objects.Clear();
                            settings.client.Objects.AddRange(GXDLMSObjectCollection.Load(settings.outputFile));
                            read = true;
                        }
                        catch (Exception)
                        {
                            //It's OK if this fails.
                        }
                    }
                    reader.InitializeConnection();
                    if (!read)
                    {
                        reader.GetAssociationView(settings.outputFile);
                    }
                    foreach (KeyValuePair <string, int> it in settings.readObjects)
                    {
                        object val = reader.Read(settings.client.Objects.FindByLN(ObjectType.None, it.Key), it.Value);
                        reader.ShowValue(val, it.Value);
                    }
                    if (settings.outputFile != null)
                    {
                        try
                        {
                            settings.client.Objects.Save(settings.outputFile, new GXXmlWriterSettings()
                            {
                                IgnoreDefaultValues = false
                            });
                        }
                        catch (Exception)
                        {
                            //It's OK if this fails.
                        }
                    }
                }
                else
                {
                    reader.ReadAll(settings.outputFile);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.ToString());
                if (System.Diagnostics.Debugger.IsAttached)
                {
                    Console.ReadKey();
                }
                return(1);
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }
                if (System.Diagnostics.Debugger.IsAttached)
                {
                    Console.WriteLine("Ended. Press any key to continue.");
                    Console.ReadKey();
                }
            }
            return(0);
        }
コード例 #21
0
ファイル: Program.cs プロジェクト: ttgzs/SmartVillage
        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();
                }
            }
        }
コード例 #22
0
        public string[] Read()
        {
            object values = null;
            int    ret    = 0;

            string[] _result = new string[4];
            try
            {
                if (_boolGetParamAtFirst == false)
                {
                    ret = GetParameters(settings);
                    _boolGetParamAtFirst = true;
                }

                if (ret != 0)
                {
                    //return ret;
                }
                ////////////////////////////////////////
                //Initialize connection settings.
                if (settings.media is GXSerial)
                {
                    GXSerial serial = settings.media as GXSerial;
                    if (settings.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 (settings.media is GXNet)
                {
                }
                else
                {
                    throw new Exception("Unknown media type.");
                }

                reader = new GXDLMSReader(settings.client, settings.media, settings.trace);
                //reader = new Gurux.DLMS.Reader.GXDLMSReader.GXDLMSReader(settings.client, settings.media, settings.trace);
                settings.media.Open();
                //Some meters need a break here.
                Thread.Sleep(1000);
                if (settings.media.IsOpen)
                {
                    if (settings.readObjects.Count != 0)
                    {
                        reader.InitializeConnection();
                        reader.GetAssociationView(false);
                        foreach (KeyValuePair <string, int> it in settings.readObjects)
                        {
                            object val = reader.Read(settings.client.Objects.FindByLN(ObjectType.None, it.Key), it.Value);
                            //reader.ShowValue(val, it.Value);
                            values = reader.ShowValues(val, it.Value);
                            if (_result != null && _result[0] == null)
                            {
                                _result[0] = values.ToString();
                            }
                            else
                            {
                                _result[1] = values.ToString();
                            }
                        }
                        _result[2] = "0";
                        _result[3] = "Success";
                        return(_result);
                    }
                    else
                    {
                        reader.ReadAll(false);
                    }
                }
                else
                {
                    _result[2] = "1";
                    _result[3] = "IP not reachable";
                    return(_result);
                }
                return(_result);
            }
            catch (Exception)
            {
                _result[2] = "2";
                _result[3] = "Error in Initialize TCP Connection / Meter Not reachable";
                return(_result);

                throw;
            }
        }
コード例 #23
0
        void InitializeIEC()
        {
            GXManufacturer manufacturer = this.Parent.Manufacturers.FindByIdentification(Parent.Manufacturer);

            if (manufacturer == null)
            {
                throw new Exception("Unknown manufacturer " + Parent.Manufacturer);
            }
            GXSerial serial     = Media as GXSerial;
            byte     Terminator = (byte)0x0A;

            if (serial != null && Parent.StartProtocol == StartProtocolType.IEC)
            {
                serial.BaudRate = 300;
                serial.DataBits = 7;
                serial.Parity   = Parity.Even;
                serial.StopBits = StopBits.One;
            }
            Media.Open();
            //Query device information.
            if (Media != null && Parent.StartProtocol == StartProtocolType.IEC)
            {
                string data = "/?!\r\n";
                if (this.Parent.HDLCAddressing == HDLCAddressType.SerialNumber)
                {
                    data = "/?" + this.Parent.PhysicalAddress + "!\r\n";
                }
                GXLogWriter.WriteLog("HDLC sending:" + data);
                ReceiveParameters <string> p = new ReceiveParameters <string>()
                {
                    AllData  = false,
                    Eop      = Terminator,
                    WaitTime = Parent.WaitTime * 1000
                };
                lock (Media.Synchronous)
                {
                    Media.Send(data, null);
                    if (!Media.Receive(p))
                    {
                        //Try to move away from mode E.
                        try
                        {
                            this.ReadDLMSPacket(this.DisconnectRequest(), 1);
                        }
                        catch (Exception ex)
                        {
                        }
                        data = (char)0x01 + "B0" + (char)0x03 + "\r\n";
                        Media.Send(data, null);
                        p.Count = 1;
                        Media.Receive(p);
                        data = "Failed to receive reply from the device in given time.";
                        GXLogWriter.WriteLog(data);
                        throw new Exception(data);
                    }
                    //If echo is used.
                    if (p.Reply == data)
                    {
                        p.Reply = null;
                        if (!Media.Receive(p))
                        {
                            //Try to move away from mode E.
                            this.ReadDLMSPacket(this.DisconnectRequest(), 1);
                            if (serial != null)
                            {
                                data = (char)0x01 + "B0" + (char)0x03 + "\r\n";
                                Media.Send(data, null);
                                p.Count = 1;
                                if (!Media.Receive(p))
                                {
                                }
                                serial.DtrEnable = serial.RtsEnable = false;
                                serial.BaudRate  = 9600;
                                serial.DtrEnable = serial.RtsEnable = true;
                                data             = (char)0x01 + "B0" + (char)0x03 + "\r\n";
                                Media.Send(data, null);
                                p.Count = 1;
                                Media.Receive(p);
                            }

                            data = "Failed to receive reply from the device in given time.";
                            GXLogWriter.WriteLog(data);
                            throw new Exception(data);
                        }
                    }
                }
                GXLogWriter.WriteLog("HDLC received: " + p.Reply);
                if (p.Reply[0] != '/')
                {
                    p.WaitTime = 100;
                    Media.Receive(p);
                    throw new Exception("Invalid responce.");
                }
                string manufactureID = p.Reply.Substring(1, 3);
                UpdateManufactureSettings(manufactureID);
                char baudrate = p.Reply[4];
                int  BaudRate = 0;
                switch (baudrate)
                {
                case '0':
                    BaudRate = 300;
                    break;

                case '1':
                    BaudRate = 600;
                    break;

                case '2':
                    BaudRate = 1200;
                    break;

                case '3':
                    BaudRate = 2400;
                    break;

                case '4':
                    BaudRate = 4800;
                    break;

                case '5':
                    BaudRate = 9600;
                    break;

                case '6':
                    BaudRate = 19200;
                    break;

                default:
                    throw new Exception("Unknown baud rate.");
                }
                GXLogWriter.WriteLog("BaudRate is : " + BaudRate.ToString());
                //Send ACK
                //Send Protocol control character
                byte controlCharacter = (byte)'2';// "2" HDLC protocol procedure (Mode E)
                //Send Baud rate character
                //Mode control character
                byte ModeControlCharacter = (byte)'2';//"2" //(HDLC protocol procedure) (Binary mode)
                //Set mode E.
                byte[] arr = new byte[] { 0x06, controlCharacter, (byte)baudrate, ModeControlCharacter, 13, 10 };
                GXLogWriter.WriteLog("Moving to mode E.", arr);
                lock (Media.Synchronous)
                {
                    Media.Send(arr, null);
                    System.Threading.Thread.Sleep(500);
                    serial.BaudRate = BaudRate;
                    p.Reply         = null;
                    p.WaitTime      = 100;
                    //Note! All meters do not echo this.
                    Media.Receive(p);
                    if (p.Reply != null)
                    {
                        GXLogWriter.WriteLog("Received: " + p.Reply);
                    }
                    serial.Close();
                    serial.DataBits = 8;
                    serial.Parity   = Parity.None;
                    serial.StopBits = StopBits.One;
                    serial.Open();
                    System.Threading.Thread.Sleep(500);
                }
            }
        }
コード例 #24
0
 public GXReceiveThread(GXSerial parent)
 {
     Closing  = new ManualResetEvent(false);
     m_Parent = parent;
 }
コード例 #25
0
ファイル: Program.cs プロジェクト: nafeezabrar/Gurux.DLMS.Net
        static int Main(string[] args)
        {
            List <string> files    = new List <string>();
            GXDLMSReader  reader   = null;
            GXSettings    settings = new GXSettings();

            try
            {
                ////////////////////////////////////////
                //Handle command line parameters.
                int ret = GetParameters(args, settings);
                if (ret != 0)
                {
                    return(ret);
                }
                ////////////////////////////////////////
                //Initialize connection settings.
                if (settings.media is GXSerial)
                {
                    GXSerial serial = settings.media as GXSerial;
                    if (settings.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 (settings.media is GXNet)
                {
                }
                else
                {
                    throw new Exception("Unknown media type.");
                }
                if (settings.path == null)
                {
                    if (settings.client.UseLogicalNameReferencing)
                    {
                        settings.path = Path.Combine(Path.GetDirectoryName(typeof(Program).Assembly.Location), "Messages\\LN");
                    }
                    else
                    {
                        settings.path = Path.Combine(Path.GetDirectoryName(typeof(Program).Assembly.Location), "Messages\\SN");
                    }
                }
                FileAttributes attr = File.GetAttributes(settings.path);
                if ((attr & FileAttributes.Directory) == FileAttributes.Directory)
                {
                    files.AddRange(Directory.GetFiles(settings.path, "*.xml"));
                }
                else
                {
                    files.Add(settings.path);
                }
                //Execute messages.
                foreach (string file in files)
                {
                    string name = Path.GetFileNameWithoutExtension(file);
                    if (settings.trace > TraceLevel.Warning)
                    {
                        Console.WriteLine("------------------------------------------------------------");
                        Console.WriteLine(name);
                    }
                    List <GXDLMSXmlPdu> actions = settings.client.Load(file);
                    if (actions.Count == 0)
                    {
                        continue;
                    }
                    try
                    {
                        settings.media.Open();
                        reader = new Reader.GXDLMSReader(settings.client, settings.media, settings.trace);
                        GXReplyData reply = new GXReplyData();
                        //Send SNRM if not in xml.
                        if (settings.client.InterfaceType == InterfaceType.HDLC)
                        {
                            if (!ContainsCommand(actions, Command.Snrm))
                            {
                                reader.SNRMRequest();
                            }
                        }

                        //Send AARQ if not in xml.
                        if (!ContainsCommand(actions, Command.Aarq))
                        {
                            if (!ContainsCommand(actions, Command.Snrm))
                            {
                                reader.AarqRequest();
                            }
                        }

                        foreach (GXDLMSXmlPdu it in actions)
                        {
                            if (it.Command == Command.Snrm && settings.client.InterfaceType == InterfaceType.WRAPPER)
                            {
                                continue;
                            }
                            if (it.Command == Command.DisconnectRequest && settings.client.InterfaceType == InterfaceType.WRAPPER)
                            {
                                break;
                            }
                            //Send
                            reply.Clear();
                            if (settings.trace > TraceLevel.Warning)
                            {
                                Console.WriteLine("------------------------------------------------------------");
                                Console.WriteLine(it.ToString());
                            }
                            if (it.IsRequest())
                            {
                                reader.ReadDataBlock(settings.client.PduToMessages(it), reply);
                                HandleReply(it, reply);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("------------------------------------------------------------");
                        Console.WriteLine(ex.Message);
                    }
                    finally
                    {
                        //Send AARQ if not in xml.
                        if (!ContainsCommand(actions, Command.DisconnectRequest))
                        {
                            reader.Disconnect();
                        }
                        else
                        {
                            settings.media.Close();
                        }
                    }
                }
                return(0);
            }
            catch (Exception ex)
            {
                if (reader != null)
                {
                    reader.Close();
                }
                if (settings.trace > TraceLevel.Off)
                {
                    Console.WriteLine("------------------------------------------------------------");
                    Console.WriteLine(ex.Message);
                }
                if (System.Diagnostics.Debugger.IsAttached)
                {
                    Console.ReadKey();
                }
                return(1);
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }
                if (System.Diagnostics.Debugger.IsAttached)
                {
                    Console.WriteLine("Press any key to continue.");
                    Console.ReadKey();
                }
            }
        }
コード例 #26
0
        private static void MainProcessing(object state)
        {
            IGXMedia media = null;
            GXCommunicatation comm = null;
            Gurux.Net.GXNet net = null;

            if ((!Environment.UserInteractive) && (args.Length == 0))	// when in service mode, get arguments from commandline if failed from onStart method
                args = Environment.CommandLine.Split(new char[] { ' ' });

            if (!Environment.UserInteractive && !running)
                return;

            try
            {
                logFile = new StreamWriter(File.Open(logFileName, FileMode.Append, FileAccess.Write, FileShare.ReadWrite));
                logFile.WriteLine("\n");

                //Handle command line parameters.
                String id = "lgz", host = "", port = "4095", pw = "";
                String lt = "-1";
                bool trace = false, iec = true;
                int loopTime = -1;
                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("/host=")) //Host
                    {
                        host = item.Replace("/host=", "");
                    }
                    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 if (item.StartsWith("/l="))// loop time
                    {
                        lt = item.Replace("/l=", "");
                    }
                    else if (item.StartsWith("/h"))// help
                    {
                        ShowHelp();
                        return;
                    }
                    else if (item.StartsWith("/sm=")) //sitemap
                    {
                        sitesMapPath = it.Trim().Replace("/sm=", "");
                    }
                    else if (item.StartsWith("/is=")) //IAM server
                    {
                        IAMServer = it.Trim().Replace("/is=", "");
                    }
                }
                if (media == null)
                    media = new Gurux.Net.GXNet();

                int.TryParse(lt, out loopTime);

                Version version = Assembly.GetExecutingAssembly().GetName().Version;

                if (!Environment.UserInteractive)
                    TraceLine(logFile, string.Format("IAM Reader OPEN SOURCE EXAMPLE Service ver. {0} started with loop time={1} min.", version.ToString(3), loopTime));
                else
                    TraceLine(logFile, string.Format("IAM Reader OPEN SOURCE EXAMPLE ver. {0} started with loop time={1} min.", version.ToString(3), loopTime));

                logFile.Flush();

                //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 debended 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.ObisCodes = man.ObisCodes;

                List<IAM.DLMSSite> DlmsSites = null;
                IAM.ArrayOfDLMSSite aods = null;

                XmlSerializer y = new XmlSerializer(typeof(IAM.ArrayOfDLMSSite));
                if (File.Exists(sitesMapPath))
                {
                    try
                    {
                        using (Stream stream = File.Open(sitesMapPath, FileMode.Open))
                        {
                            TraceLine(logFile, "Get configured sites map from file.");
                            aods = y.Deserialize(stream) as IAM.ArrayOfDLMSSite;
                            DlmsSites = aods.DLMSSite;
                            stream.Close();
                        }

                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }
                else
                {
                    TraceLine(logFile, "Error. SitesMap file not found.");
                    return;
                }

                List<Type> extraTypes = new List<Type>(Gurux.DLMS.GXDLMSClient.GetObjectTypes());
                extraTypes.Add(typeof(GXDLMSAttributeSettings));
                extraTypes.Add(typeof(GXDLMSAttribute));
                //TraceLine(logFile, "Memory32: " + GC.GetTotalMemory(true));
                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.
                extraTypes.Clear();

                foreach (IAM.DLMSSite site in DlmsSites) //
                {
                    site.DataProcessing.EnergyPeriodDateTime = DateTime.MinValue;
                    site.DataProcessing.PowerPeriodDateTime = DateTime.MinValue;
                }

                //bool keyAvailable = false;
                DateTime startTime;
                FileInfo infoFileSite = new FileInfo(sitesMapPath);
                DateTime lastWriteMapFile = infoFileSite.LastWriteTime;

                do
                {
                    try
                    {
                        FileInfo f = new FileInfo(logFileName); //output log file
                        if (f.Length > maxLogFileSize)
                        {
                            logFile.Flush();
                            logFile.Close();
                            File.Delete(rotatedLogFileName);
                            File.Move(logFileName, rotatedLogFileName);
                            logFile = new StreamWriter(File.Open(logFileName, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite));
                        }

                        infoFileSite.Refresh();
                        if (infoFileSite.LastWriteTime != lastWriteMapFile)
                        {
                            try
                            {
                                using (Stream stream = File.Open(sitesMapPath, FileMode.Open))
                                {
                                    TraceLine(logFile, "Get updated sites map from file.");
                                    aods = y.Deserialize(stream) as IAM.ArrayOfDLMSSite;
                                    DlmsSites = aods.DLMSSite;
                                    stream.Close();

                                    lastWriteMapFile = infoFileSite.LastWriteTime;
                                }

                            }
                            catch (Exception ex)
                            {
                                throw ex;
                            }

                        }

                        startTime = DateTime.Now;
                        TraceLine(logFile, "Start new iteration");
                        foreach (IAM.DLMSSite site in DlmsSites) //cycle for each remote meter (listed in the sitemap.xml)
                        {
                            TraceLine(logFile, "Now processing: " + site.Name); //current remote meter
                            if (!site.Enabled)
                            {
                                TraceLine(logFile, "Disabled: skip to next");
                                continue;
                            }
                            try
                            {
                                host = site.Device.Host; //ip address of the current remote meter
                                port = site.Device.Port;
                                if (site.Device.Manufacturer != "")
                                    id = site.Device.Manufacturer.ToLower();
                                if (site.Device.Protocol != "")
                                    iec = site.Device.Protocol.ToLower() == "dlms";
                                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;
                                }
                                comm = new GXCommunicatation(dlms, media, iec, auth, pw);
                                comm.Trace = trace;
                                TraceLine(logFile, "Initializing Network connection.");
                                comm.InitializeConnection(man);
                            }
                            catch (Exception ex)
                            {
                                TraceLine(logFile, "Error. " + ex.Message);
                                if (comm != null)
                                {
                                    comm.Close();
                                }
                                continue;
                            }
                            GXDLMSObjectCollection objects = null;

                            string meterPath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) +  "\\" +host.Replace('.', '_') + "_" + port.ToString() + ".xml";

                            if (File.Exists(meterPath)) //list of OBIS objects for remote meter
                            {
                                try
                                {
                                    using (Stream stream = File.Open(meterPath, FileMode.Open))
                                    {
                                        TraceLine(logFile, "Get available objects from the cache.");
                                        objects = x.Deserialize(stream) as GXDLMSObjectCollection;
                                        stream.Close();
                                    }

                                }
                                catch (Exception ex)
                                {
                                    if (File.Exists(meterPath))
                                    {
                                        File.Delete(meterPath);
                                    }
                                    throw ex;
                                }
                            }
                            else
                            {
                                TraceLine(logFile, "Get available objects from the device.");
                                objects = comm.GetAssociationView();

                                // Save to file
                                try
                                {
                                    using (Stream stream = File.Open(meterPath, FileMode.Create))
                                    {
                                        TextWriter writer = new StreamWriter(stream);
                                        x.Serialize(writer, objects);
                                        writer.Close();
                                        stream.Close();
                                    }
                                    TraceLine(logFile, "Available objects saved to the cache.");

                                }
                                catch (Exception ex)
                                {
                                    if (File.Exists(meterPath))
                                    {
                                        File.Delete(meterPath);
                                    }
                                    throw ex;
                                }

                            }

                            // start remote meter reading
                            try
                            {
                                int EPeriod = 15;	// energy integration period
                                if (site.DataProcessing.EnergyPeriod != 0)
                                    EPeriod = site.DataProcessing.EnergyPeriod;
                                else
                                    site.DataProcessing.EnergyPeriod = EPeriod;

                                //if (EPeriod <= 0)
                                //    EPeriod = 15;

                                int PPeriod = 15;	// power integration period
                                if (site.DataProcessing.PowerPeriod != 0)
                                    PPeriod = site.DataProcessing.PowerPeriod;
                                else
                                    site.DataProcessing.PowerPeriod = PPeriod;

                                //if (PPeriod <= 0)
                                //    PPeriod = 15;

                                DateTime now = DateTime.Now;
                                DateTime nowRnd = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute / EPeriod * EPeriod, 0);

                                if (site.DataProcessing.EnergyPeriodDateTime == DateTime.MinValue)
                                {
                                    site.DataProcessing.EnergyPeriodDateTime = now;
                                    TraceLine(logFile, "Initialize energy period from null.");
                                }

                                // default OBIS codes for energies
                                string AEP = "1.0.1.8.0.255";
                                string AEM = "1.0.2.8.0.255";
                                string REP = "1.0.3.8.0.255";
                                string REM = "1.0.4.8.0.255";

                                if (!string.IsNullOrEmpty(site.ArrayOfOBIS.DataObjects.ActiveEnergyP)) //plus = absorbed energy
                                    AEP = site.ArrayOfOBIS.DataObjects.ActiveEnergyP;
                                if (!string.IsNullOrEmpty(site.ArrayOfOBIS.DataObjects.ActiveEnergyM)) //minus = supplied energy
                                    AEM = site.ArrayOfOBIS.DataObjects.ActiveEnergyM;
                                if (!string.IsNullOrEmpty(site.ArrayOfOBIS.DataObjects.ReactiveEnergyP)) //plus = absorbed energy
                                    REP = site.ArrayOfOBIS.DataObjects.ReactiveEnergyP;
                                if (!string.IsNullOrEmpty(site.ArrayOfOBIS.DataObjects.ReactiveEnergyM)) //minus = supplied energy
                                    REM = site.ArrayOfOBIS.DataObjects.ReactiveEnergyM;

                                GXDLMSObject aepObj = objects.FindByLN(ObjectType.Register, AEP);
                                if (aepObj == null)
                                    throw new System.InvalidOperationException(string.Format("Error: Active Energy Positive Object not defined for site {0}.", site.Name));
                                GXDLMSObject aemObj = objects.FindByLN(ObjectType.Register, AEM);
                                if (aemObj == null)
                                    throw new System.InvalidOperationException(string.Format("Active Energy Negative Object not defined for site {0}.", site.Name));
                                GXDLMSObject repObj = objects.FindByLN(ObjectType.Register, REP);
                                if (repObj == null)
                                    throw new System.InvalidOperationException(string.Format("Reactive Energy Positive Object not defined for site {0}.", site.Name));
                                GXDLMSObject remObj = objects.FindByLN(ObjectType.Register, REM);
                                if (remObj == null)
                                    throw new System.InvalidOperationException(string.Format("Reactive Energy Negative Object not defined for site {0}.", site.Name));

                                Regex regex = new Regex(@"^Scaler:(.*) Unit:(.*)$");
                                double scaler = 1;

                                object value = comm.Read(aepObj, 2);
                                string scalerAttr = (string)comm.Read(aepObj, 3);
                                Match match = regex.Match(scalerAttr);
                                if (match.Groups.Count >= 2)
                                    scaler = double.Parse(match.Groups[1].Value);
                                double ActiveEnergyP = double.Parse(value.ToString()) * scaler;
                                TraceLine(logFile, "Positive Active Energy reading completed.");

                                value = comm.Read(aemObj, 2);
                                scalerAttr = (string)comm.Read(aemObj, 3);
                                match = regex.Match(scalerAttr);
                                if (match.Groups.Count >= 2)
                                    scaler = double.Parse(match.Groups[1].Value);
                                double ActiveEnergyM = double.Parse(value.ToString()) * scaler;
                                TraceLine(logFile, "Negative Active Energy reading completed.");

                                value = comm.Read(repObj, 2);
                                scalerAttr = (string)comm.Read(repObj, 3);
                                match = regex.Match(scalerAttr);
                                if (match.Groups.Count >= 2)
                                    scaler = double.Parse(match.Groups[1].Value);
                                double ReactiveEnergyP = double.Parse(value.ToString()) * scaler;
                                TraceLine(logFile, "Positive Reactive Energy reading completed.");

                                value = comm.Read(remObj, 2);
                                scalerAttr = (string)comm.Read(remObj, 3);
                                match = regex.Match(scalerAttr);
                                if (match.Groups.Count >= 2)
                                    scaler = double.Parse(match.Groups[1].Value);
                                double ReactiveEnergyM = double.Parse(value.ToString()) * scaler;
                                TraceLine(logFile, "Negative Reactive Energy reading completed.");

                                // end of remote meter reading

                                if (site.DataProcessing.ActiveEnergyPStart == 0)
                                    site.DataProcessing.ActiveEnergyPStart = ActiveEnergyP;
                                site.DataProcessing.ActiveEnergyPCurrent = ActiveEnergyP;

                                if (site.DataProcessing.ActiveEnergyMStart == 0)
                                    site.DataProcessing.ActiveEnergyMStart = ActiveEnergyM;
                                site.DataProcessing.ActiveEnergyMCurrent = ActiveEnergyM;

                                if (site.DataProcessing.ReactiveEnergyPStart == 0)
                                    site.DataProcessing.ReactiveEnergyPStart = ReactiveEnergyP;
                                site.DataProcessing.ReactiveEnergyPCurrent = ReactiveEnergyP;

                                if (site.DataProcessing.ReactiveEnergyMStart == 0)
                                    site.DataProcessing.ReactiveEnergyMStart = ReactiveEnergyM;
                                site.DataProcessing.ReactiveEnergyMCurrent = ReactiveEnergyM;

                                DateTime tStart = new DateTime(site.DataProcessing.EnergyPeriodDateTime.Year, site.DataProcessing.EnergyPeriodDateTime.Month, site.DataProcessing.EnergyPeriodDateTime.Day, site.DataProcessing.EnergyPeriodDateTime.Hour, site.DataProcessing.EnergyPeriodDateTime.Minute / EPeriod * EPeriod, 0);
                                TimeSpan ts = now.Subtract(tStart);

                                if (EPeriod > 0)		// if energy recording enabled
                                {
                                    if (((ts.Hours * 60) + ts.Minutes) >= EPeriod)  // if end of period
                                    {
                                        ts = now.Subtract(site.DataProcessing.EnergyPeriodDateTime);
                                        double ratio = (double)((ts.Hours * 3600) + (ts.Minutes * 60) + ts.Seconds) / (EPeriod * 60);
                                        if (ratio > 0.9) ratio = 1;
                                        ratio = Math.Round(ratio, 2);
                                        TraceLine(logFile, string.Format("End of integration energy period (ratio = {0})", ratio));

                                        double deltaActiveEnergyP = site.DataProcessing.ActiveEnergyPCurrent - site.DataProcessing.ActiveEnergyPStart;
                                        double deltaActiveEnergyM = site.DataProcessing.ActiveEnergyMCurrent - site.DataProcessing.ActiveEnergyMStart;

                                        double deltaReactiveEnergyP = site.DataProcessing.ReactiveEnergyPCurrent - site.DataProcessing.ReactiveEnergyPStart;
                                        double deltaReactiveEnergyM = site.DataProcessing.ReactiveEnergyMCurrent - site.DataProcessing.ReactiveEnergyMStart;

                                        if (deltaActiveEnergyP > deltaActiveEnergyM)	// quadrants prevalent: I or IV
                                        {
                                            PublishEnergy(site, nowRnd, deltaActiveEnergyP, deltaActiveEnergyM, deltaReactiveEnergyP, 0, 0, deltaReactiveEnergyM, ratio, logFile);
                                        }
                                        else  // quadrants prevalent: II or III
                                        {
                                            PublishEnergy(site, nowRnd, deltaActiveEnergyP, deltaActiveEnergyM, 0, deltaReactiveEnergyP, deltaReactiveEnergyM, 0, ratio, logFile);
                                        }

                                        site.DataProcessing.EnergyPeriodDateTime = now;
                                        site.DataProcessing.ActiveEnergyPStart = ActiveEnergyP;
                                        site.DataProcessing.ActiveEnergyMStart = ActiveEnergyM;
                                        site.DataProcessing.ReactiveEnergyPStart = ReactiveEnergyP;
                                        site.DataProcessing.ReactiveEnergyMStart = ReactiveEnergyM;
                                    }
                                }

                                if (site.DataProcessing.ActivePowerPStart == 0)
                                    site.DataProcessing.ActivePowerPStart = ActiveEnergyP;
                                site.DataProcessing.ActivePowerPCurrent = ActiveEnergyP;

                                if (site.DataProcessing.ActivePowerMStart == 0)
                                    site.DataProcessing.ActivePowerMStart = ActiveEnergyM;
                                site.DataProcessing.ActivePowerMCurrent = ActiveEnergyM;

                                if (site.DataProcessing.ReactivePowerPStart == 0)
                                    site.DataProcessing.ReactivePowerPStart = ReactiveEnergyP;
                                site.DataProcessing.ReactivePowerPCurrent = ReactiveEnergyP;

                                if (site.DataProcessing.ReactivePowerMStart == 0)
                                    site.DataProcessing.ReactivePowerMStart = ReactiveEnergyM;
                                site.DataProcessing.ReactivePowerMCurrent = ReactiveEnergyM;

                                tStart = new DateTime(site.DataProcessing.PowerPeriodDateTime.Year, site.DataProcessing.PowerPeriodDateTime.Month, site.DataProcessing.PowerPeriodDateTime.Day, site.DataProcessing.PowerPeriodDateTime.Hour, site.DataProcessing.PowerPeriodDateTime.Minute / PPeriod * PPeriod, 0);
                                ts = now.Subtract(tStart);

                                if (PPeriod > 0)		// if power recording enabled
                                {
                                    if (((ts.Hours * 60) + ts.Minutes) >= PPeriod)  // if end of period
                                    {
                                        ts = now.Subtract(site.DataProcessing.PowerPeriodDateTime);
                                        double ratio = (double)((ts.Hours * 3600) + (ts.Minutes * 60) + ts.Seconds) / (PPeriod * 60);
                                        if (ratio > 0.9) ratio = 1;
                                        ratio = Math.Round(ratio, 2);
                                        TraceLine(logFile, string.Format("End of integration power period (ratio = {0})", ratio));

                                        double deltaActivePowerP = (site.DataProcessing.ActivePowerPCurrent - site.DataProcessing.ActivePowerPStart) / PPeriod * 60;
                                        double deltaActivePowerM = (site.DataProcessing.ActivePowerMCurrent - site.DataProcessing.ActivePowerMStart) / PPeriod * 60;

                                        double deltaReactivePowerP = (site.DataProcessing.ReactivePowerPCurrent - site.DataProcessing.ReactivePowerPStart) / PPeriod * 60;
                                        double deltaReactivePowerM = (site.DataProcessing.ReactivePowerMCurrent - site.DataProcessing.ReactivePowerMStart) / PPeriod * 60;

                                        // since ZXF meter has no capability to supply Q1-Q4 (but only 2 quadrants), we calculate Q1, Q2, Q3, Q4 here

                                        if (deltaActivePowerP > deltaActivePowerM)	// quadrants prevalent: I or IV
                                        {
                                            PublishPower(site, nowRnd, deltaActivePowerP, deltaActivePowerM, deltaReactivePowerP, 0, 0, deltaReactivePowerM, ratio, logFile);
                                        }
                                        else  // quadrants prevalent: II or III
                                        {
                                            PublishPower(site, nowRnd, deltaActivePowerP, deltaActivePowerM, 0, deltaReactivePowerP, deltaReactivePowerM, 0, ratio, logFile);
                                        }

                                        //

                                        site.DataProcessing.PowerPeriodDateTime = now;
                                        site.DataProcessing.ActivePowerPStart = ActiveEnergyP;
                                        site.DataProcessing.ActivePowerMStart = ActiveEnergyM;
                                        site.DataProcessing.ReactivePowerPStart = ReactiveEnergyP;
                                        site.DataProcessing.ReactivePowerMStart = ReactiveEnergyM;
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                TraceLine(logFile, "Error. " + ex.Message);
                                if (comm != null)
                                {
                                    comm.Close();
                                }
                                continue;
                            }

            #if ZERO
                            foreach (GXDLMSObject it in objects)
                            {
                                if (!string.IsNullOrEmpty(site.ArrayOfOBIS.DataObjects.ActiveEnergyP))		// if is requested the ActiveEnergy+ obis code
                                {

                                    if (it.LogicalName == AEP)
                                    {
                                        try
                                        {
                                            object value = comm.Read(it, 2);
                                            string scalerAttr = (string)comm.Read(it, 3);

                                            Regex regex = new Regex(@"^Scaler:(.*) Unit:(.*)$");
                                            Match match = regex.Match(scalerAttr);

                                            double scaler = 1;
                                            if (match.Groups.Count >= 2)
                                                scaler = double.Parse(match.Groups[1].Value);

                                            double Energy = double.Parse(value.ToString()) * scaler;

                                            // First time initialize the value of initial energy
                                            if (site.DataProcessing.ActiveEnergyPStart == 0)
                                            {
                                                site.DataProcessing.ActiveEnergyPStart = Energy;
                                                TraceLine(logFile, "Initial ActiveEnergy+ : " + Energy + " Wh");
                                            }
                                        }
                                        catch (Exception ex)
                                        {
                                            TraceLine(logFile, "Error. Failed to get ActiveEnergy+: " + ex.Message);
                                            //Continue reading.
                                        }

                                    }
                                }

                                // Read meter inst. values
                                if (!string.IsNullOrEmpty(site.ArrayOfOBIS.DataObjects.ActivePower))
                                {
                                    try
                                    {

                                        if (it.LogicalName == site.ArrayOfOBIS.DataObjects.ActivePower)
                                        {
                                            //Console.WriteLine(it.Name);
                                            object value = comm.Read(it, 2);
                                            string scalerAttr = (string)comm.Read(it, 3);

                                            Regex regex = new Regex(@"^Scaler:(.*) Unit:(.*)$");
                                            Match match = regex.Match(scalerAttr);

                                            double scaler = 1;
                                            if (match.Groups.Count >= 2)
                                                scaler = double.Parse(match.Groups[1].Value);

                                            double activePower = double.Parse(value.ToString()) * scaler;
                                            TraceLine(logFile, "Active Power: " + activePower + " W");

                                            int period = 15;
                                            if (site.DataProcessing.Period != 0)
                                            {
                                                period = site.DataProcessing.Period;
                                            }
                                            DateTime now = DateTime.Now;
                                            DateTime nowRnd = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute / period * period, 0);

                                            if (site.DataProcessing.IntervalDateTime.Ticks == 0)
                                            {
                                                site.DataProcessing.IntervalDateTime = nowRnd;
                                                site.DataProcessing.Count = 0;
                                                site.DataProcessing.Sum = 0;
                                                TraceLine(logFile, "Initialize period from null.");
                                            }
                                            else
                                            {
                                                long elapsedTicks = now.Ticks - site.DataProcessing.IntervalDateTime.Ticks;
                                                TimeSpan elapsedSpan = new TimeSpan(elapsedTicks);
                                                if (elapsedSpan.TotalMinutes >= period)  // if end of period
                                                {
                                                    // Round date to minute multiple of "period"
                                                    if (site.DataProcessing.Count > 0)    // compute avg quantities
                                                    {
                                                        TraceLine(logFile, "End of inst. readings integration period.");
                                                        double avgActivePower = site.DataProcessing.Sum / site.DataProcessing.Count;
                                                        site.DataProcessing.IntervalDateTime = nowRnd;
                                                        site.DataProcessing.Count = 0;
                                                        site.DataProcessing.Sum = 0;
                                                        //                                                    PublishReading(site, site.DataProcessing.IntervalDateTime.AddMinutes(period), avgActivePower, logFile);
                                                        PublishReading(site, site.DataProcessing.IntervalDateTime, avgActivePower, 0, 0, 0, 0, 0, logFile);
                                                    }
                                                    else
                                                    {
                                                        TraceLine(logFile, "Zero counts period: initialize only.");
                                                        site.DataProcessing.IntervalDateTime = nowRnd;
                                                        site.DataProcessing.Count = 0;
                                                        site.DataProcessing.Sum = 0;
                                                    }
                                                }
                                                site.DataProcessing.Sum += activePower;
                                                site.DataProcessing.Count++;
                                            }
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        TraceLine(logFile, "Error. Failed to get inst. readings: " + ex.Message);
                                        //Continue reading.
                                    }
                                }

                                //  Read load profiles
                                if (string.IsNullOrEmpty(site.ArrayOfOBIS.GenericProfileObjects.LoadProfile))
                                    continue;

                                if (it.LogicalName == site.ArrayOfOBIS.GenericProfileObjects.LoadProfile)
                                {
                                    //Console.WriteLine(it.Name);
                                    try
                                    {
                                        int period = 15;
                                        if (site.DataProcessing.ProfilePeriod != 0)
                                        {
                                            period = site.DataProcessing.ProfilePeriod;
                                        }

                                        DateTime now = DateTime.Now;
                                        DateTime nowRnd = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute / period * period, 0);
                                        long elapsedTicks = now.Ticks - site.DataProcessing.ProfileDateTime.Ticks;
                                        TimeSpan elapsedSpan = new TimeSpan(elapsedTicks);
                                        double totalMinutes = elapsedSpan.TotalMinutes;
                                        int maxDays = 1;
                                        if (totalMinutes > 1440 * maxDays)
                                        {  // max one week
                                            totalMinutes = 1440 * maxDays;
                                            site.DataProcessing.ProfileDateTime = nowRnd.AddMinutes(-totalMinutes);
                                        }
                                        if (totalMinutes >= period)  // if end of period
                                        {
                                            //Read from Profile Generic.
                                            object[] rows = comm.ReadRowsByRange(it, site.DataProcessing.ProfileDateTime, nowRnd, (it as GXDLMSProfileGeneric).CaptureObjects);
                                            StringBuilder sb = new StringBuilder();
                                            foreach (object[] row in rows)
                                            {
                                                object dto = row[0];
                                                DateTime dt;
                                                if (DateTime.TryParse(dto.ToString(), out dt))
                                                {
                                                    dt = dt.ToLocalTime();
                                                    row[0] = dt;
                                                }

                                                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");
                                            }
                                            site.DataProcessing.ProfileDateTime = nowRnd;
                                            PublishProfile(site, site.DataProcessing.ProfileDateTime, sb, logFile);
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        TraceLine(logFile, "Error. Failed to get load profile: " + ex.Message);
                                        //Continue reading.
                                    }
                                }
                            }
            #endif
                            try
                            {
                                using (Stream stream = File.Open(sitesMapPath, FileMode.Create))
                                {
                                    TraceLine(logFile, "Save site map to file.");
                                    TextWriter writer = new StreamWriter(stream);
                                    y.Serialize(writer, aods);
                                    //                            aods = y.Deserialize(stream) as IAM.ArrayOfDLMSSite;
                                    stream.Close();

                                    infoFileSite.Refresh();
                                    lastWriteMapFile = infoFileSite.LastWriteTime;
                                }

                            }
                            catch (Exception ex)
                            {
                                throw ex;
                            }

                            TraceLine(logFile, "Disconnecting from the meter.");
                            comm.Close();
                            objects.Clear();
                        }
                    }
                    catch (Exception ex)
                    {
                        TraceLine(logFile, ex.Message);
                        if (comm != null)
                        {
                            comm.Close();
                        }
                        // Continue reading
                    }

                    logFile.Flush();

                    if (loopTime > 0)   // wait until next loop time
                    {
                        DateTime when = DateTime.Now;
                        int nextMinutes = (when.Minute / loopTime) * loopTime + loopTime;
                        DateTime nextTime = new DateTime(when.Year, when.Month, when.Day);
                        nextTime = nextTime.AddHours(when.Hour);
                        nextTime = nextTime.AddMinutes(nextMinutes);
                        int waitSeconds = (int)(new TimeSpan(nextTime.Ticks - when.Ticks).TotalSeconds);
                        waitSeconds++;
                        TraceLine(logFile, "Waiting for next loop (in "+waitSeconds+" sec.)...\r\n");
                        logFile.Flush();
                        do
                        {
                            Thread.Sleep(1000);
                            waitSeconds--;

                            //if (Environment.UserInteractive)
                            //    keyAvailable = Console.KeyAvailable;

                        } while ((waitSeconds > 0) && !keyAvailable && running);
                    }
                    Console.WriteLine("");

                    //if (Environment.UserInteractive)
                    //    keyAvailable = Console.KeyAvailable;

                } while (!keyAvailable && (loopTime != -1) && running);

                if (keyAvailable)
                {
                    TraceLine(logFile, "Program interrupted by user.");
                }
                else if (!running)
                {
                    TraceLine(logFile, "Service stopped.");
                }
                else
                {
                    TraceLine(logFile, "Single run ended.");
                    if (!Environment.UserInteractive)
                    {
                        logFile.Flush();
                        logFile.Close();
                        Environment.Exit(0);
                    }
                }
            }
            catch (Exception ex)
            {
                if (logFile != null)
                    TraceLine(logFile, ex.Message);

                if (comm != null)
                {
                    comm.Close();
                }
                Console.WriteLine("Error. " + ex.Message);
            }
            finally
            {
                logFile.Flush();
                logFile.Close();

                if (comm != null)
                {
                    comm.Close();
                }
                Console.WriteLine("Now stop.");
            }
        }
コード例 #27
0
        public int GetParameters(Settings settings)
        {
            string[]         tmp;
            List <GxCommand> parameters = new List <GxCommand>();//List<GXCmdParameter> parameters = GXCommon.GetParameters(args, "h:p:c:s:r:it:a:wP:g:S:C:");

            parameters.Add(new GxCommand()
            {
                Tag = 'c', Value = configuration.ClientAdd
            });                                                                            //"32"
            parameters.Add(new GxCommand()
            {
                Tag = 'r', Value = configuration.Name
            });                                                                       //"ln"
            parameters.Add(new GxCommand()
            {
                Tag = 'h', Value = configuration.IpAddress
            });                                                                            //"192.168.5.104"
            parameters.Add(new GxCommand()
            {
                Tag = 'p', Value = Convert.ToString(configuration.Port)
            });                                                                                         //"502"
            parameters.Add(new GxCommand()
            {
                Tag = 'a', Value = configuration.Authentication
            });                                                                                 //"Low"
            parameters.Add(new GxCommand()
            {
                Tag = 'P', Value = configuration.Password
            });                                                                           //"1111111111111111"
            parameters.Add(new GxCommand()
            {
                Tag = 'g', Value = configuration.SObisValue
            });                                                                             //"1.0.1.8.0.255:2"
            parameters.Add(new GxCommand()
            {
                Tag = 'g', Value = configuration.RObisValue
            });
            GXNet net = null;

            foreach (GxCommand it in parameters)
            {
                switch (it.Tag)
                {
                case 'w':
                    settings.client.InterfaceType = InterfaceType.WRAPPER;
                    break;

                case 'r':
                    if (string.Compare(it.Value, "sn", true) == 0)
                    {
                        settings.client.UseLogicalNameReferencing = false;
                    }
                    else if (string.Compare(it.Value, "ln", true) == 0)
                    {
                        settings.client.UseLogicalNameReferencing = true;
                    }
                    else
                    {
                        throw new ArgumentException("Invalid reference option.");
                    }
                    break;

                case 'h':
                    //Host address.
                    if (settings.media == null)
                    {
                        settings.media = new GXNet();
                    }
                    net          = settings.media as GXNet;
                    net.HostName = it.Value;
                    break;

                case 't':
                    //Trace.
                    try
                    {
                        settings.trace = (TraceLevel)Enum.Parse(typeof(TraceLevel), it.Value);
                    }
                    catch (Exception)
                    {
                        throw new ArgumentException("Invalid trace level option. (Error, Warning, Info, Verbose, Off)");
                    }
                    break;

                case 'p':
                    //Port.
                    if (settings.media == null)
                    {
                        settings.media = new GXNet();
                    }
                    net      = settings.media as GXNet;
                    net.Port = int.Parse(it.Value);
                    break;

                case 'P':    //Password
                    settings.client.Password = ASCIIEncoding.ASCII.GetBytes(it.Value);
                    break;

                case 'i':
                    //IEC.
                    settings.iec = true;
                    break;

                case 'g':
                    //Get (read) selected objects.
                    foreach (string o in it.Value.Split(new char[] { ';', ',' }))
                    {
                        tmp = o.Split(new char[] { ':' });
                        if (tmp.Length != 2)
                        {
                            throw new ArgumentOutOfRangeException("Invalid Logical name or attribute index.");
                        }
                        settings.readObjects.Add(new KeyValuePair <string, int>(tmp[0].Trim(), int.Parse(tmp[1].Trim())));
                    }
                    break;

                case 'S':    //Serial Port
                    settings.media = new GXSerial();
                    GXSerial serial = settings.media as GXSerial;
                    tmp             = it.Value.Split(':');
                    serial.PortName = tmp[0];
                    if (tmp.Length > 1)
                    {
                        serial.BaudRate = int.Parse(tmp[1]);
                        serial.DataBits = int.Parse(tmp[2].Substring(0, 1));
                        serial.Parity   = (Parity)Enum.Parse(typeof(Parity), tmp[2].Substring(1, tmp[2].Length - 2));
                        serial.StopBits = (StopBits)int.Parse(tmp[2].Substring(tmp[2].Length - 1, 1));
                    }
                    else
                    {
                        serial.BaudRate = 9600;
                        serial.DataBits = 8;
                        serial.Parity   = Parity.None;
                        serial.StopBits = StopBits.One;
                    }
                    break;

                case 'a':
                    try
                    {
                        if (string.Compare("None", it.Value, true) == 0)
                        {
                            settings.client.Authentication = Authentication.None;
                        }
                        else if (string.Compare("Low", it.Value, true) == 0)
                        {
                            settings.client.Authentication = Authentication.Low;
                        }
                        else if (string.Compare("High", it.Value, true) == 0)
                        {
                            settings.client.Authentication = Authentication.High;
                        }
                        else if (string.Compare("HighMd5", it.Value, true) == 0)
                        {
                            settings.client.Authentication = Authentication.HighMD5;
                        }
                        else if (string.Compare("HighSha1", it.Value, true) == 0)
                        {
                            settings.client.Authentication = Authentication.HighSHA1;
                        }
                        else if (string.Compare("HighSha256", it.Value, true) == 0)
                        {
                            settings.client.Authentication = Authentication.HighSHA256;
                        }
                        else if (string.Compare("HighGMac", it.Value, true) == 0)
                        {
                            settings.client.Authentication = Authentication.HighGMAC;
                        }
                        else
                        {
                            throw new ArgumentException("Invalid Authentication option: '" + it.Value + "'. (None, Low, High, HighMd5, HighSha1, HighGMac, HighSha256)");
                        }
                    }
                    catch (Exception)
                    {
                        throw new ArgumentException("Invalid Authentication option: '" + it.Value + "'. (None, Low, High, HighMd5, HighSha1, HighGMac, HighSha256)");
                    }
                    break;

                case 'C':
                    try
                    {
                        settings.client.Ciphering.Security = (Security)Enum.Parse(typeof(Security), it.Value);
                    }
                    catch (Exception)
                    {
                        throw new ArgumentException("Invalid Ciphering option. (None, Authentication, Encrypted, AuthenticationEncryption)");
                    }
                    break;

                case 'o':
                    break;

                case 'c':
                    settings.client.ClientAddress = int.Parse(it.Value);
                    break;

                case 's':
                    settings.client.ServerAddress = int.Parse(it.Value);
                    break;

                case '?':
                    switch (it.Tag)
                    {
                    case 'c':
                        throw new ArgumentException("Missing mandatory client option.");

                    case 's':
                        throw new ArgumentException("Missing mandatory server option.");

                    case 'h':
                        throw new ArgumentException("Missing mandatory host name option.");

                    case 'p':
                        throw new ArgumentException("Missing mandatory port option.");

                    case 'r':
                        throw new ArgumentException("Missing mandatory reference option.");

                    case 'a':
                        throw new ArgumentException("Missing mandatory authentication option.");

                    case 'S':
                        throw new ArgumentException("Missing mandatory Serial port option.");

                    case 't':
                        throw new ArgumentException("Missing mandatory trace option.");

                    case 'g':
                        throw new ArgumentException("Missing mandatory OBIS code option.");

                    case 'C':
                        throw new ArgumentException("Missing mandatory Ciphering option.");

                    default:
                        //ShowHelp();
                        return(1);
                    }

                default:
                    //ShowHelp();
                    return(1);
                }
            }
            if (settings.media == null)
            {
                // ShowHelp();
                return(1);
            }
            return(0);
        }
コード例 #28
0
        /// <summary>
        /// Initialize optical head.
        /// </summary>
        void InitializeOpticalHead()
        {
            if (Client.InterfaceType != InterfaceType.HdlcWithModeE)
            {
                return;
            }
            GXSerial serial     = Media as GXSerial;
            byte     Terminator = (byte)0x0A;

            Media.Open();
            //Some meters need a little break.
            Thread.Sleep(1000);
            //Query device information.
            string data = "/?!\r\n";

            if (Trace > TraceLevel.Info)
            {
                Console.WriteLine("IEC Sending:" + data);
            }
            ReceiveParameters <string> p = new ReceiveParameters <string>()
            {
                AllData  = false,
                Eop      = Terminator,
                WaitTime = WaitTime * 1000
            };

            lock (Media.Synchronous)
            {
                Media.Send(data, null);
                if (!Media.Receive(p))
                {
                    //Try to move away from mode E.
                    try
                    {
                        Disconnect();
                    }
                    catch (Exception)
                    {
                    }
                    DiscIEC();
                    string str = "Failed to receive reply from the device in given time.";
                    if (Trace > TraceLevel.Info)
                    {
                        Console.WriteLine(str);
                    }
                    Media.Send(data, null);
                    if (!Media.Receive(p))
                    {
                        throw new Exception(str);
                    }
                }
                //If echo is used.
                if (p.Reply == data)
                {
                    p.Reply = null;
                    if (!Media.Receive(p))
                    {
                        //Try to move away from mode E.
                        GXReplyData reply = new GXReplyData();
                        Disconnect();
                        if (serial != null)
                        {
                            DiscIEC();
                            serial.DtrEnable = serial.RtsEnable = false;
                            serial.BaudRate  = 9600;
                            serial.DtrEnable = serial.RtsEnable = true;
                            DiscIEC();
                        }
                        data = "Failed to receive reply from the device in given time.";
                        if (Trace > TraceLevel.Info)
                        {
                            Console.WriteLine(data);
                        }
                        throw new Exception(data);
                    }
                }
            }
            if (Trace > TraceLevel.Info)
            {
                Console.WriteLine("HDLC received: " + p.Reply);
            }
            if (p.Reply[0] != '/')
            {
                p.WaitTime = 100;
                Media.Receive(p);
                DiscIEC();
                throw new Exception("Invalid responce.");
            }
            string manufactureID = p.Reply.Substring(1, 3);
            char   baudrate      = p.Reply[4];
            int    BaudRate      = 0;

            switch (baudrate)
            {
            case '0':
                BaudRate = 300;
                break;

            case '1':
                BaudRate = 600;
                break;

            case '2':
                BaudRate = 1200;
                break;

            case '3':
                BaudRate = 2400;
                break;

            case '4':
                BaudRate = 4800;
                break;

            case '5':
                BaudRate = 9600;
                break;

            case '6':
                BaudRate = 19200;
                break;

            default:
                throw new Exception("Unknown baud rate.");
            }
            if (Trace > TraceLevel.Info)
            {
                Console.WriteLine("BaudRate is : " + BaudRate.ToString());
            }
            //Send ACK
            //Send Protocol control character
            // "2" HDLC protocol procedure (Mode E)
            byte controlCharacter = (byte)'2';
            //Send Baud rate character
            //Mode control character
            byte ModeControlCharacter = (byte)'2';

            //"2" //(HDLC protocol procedure) (Binary mode)
            //Set mode E.
            byte[] arr = new byte[] { 0x06, controlCharacter, (byte)baudrate, ModeControlCharacter, 13, 10 };
            if (Trace > TraceLevel.Info)
            {
                Console.WriteLine("Moving to mode E.", arr);
            }
            lock (Media.Synchronous)
            {
                p.Reply = null;
                Media.Send(arr, null);
                //Some meters need this sleep. Do not remove.
                Thread.Sleep(200);
                p.WaitTime = 2000;
                //Note! All meters do not echo this.
                Media.Receive(p);
                if (p.Reply != null)
                {
                    if (Trace > TraceLevel.Info)
                    {
                        Console.WriteLine("Received: " + p.Reply);
                    }
                }
                serial.BaudRate = BaudRate;
                serial.DataBits = 8;
                serial.Parity   = Parity.None;
                serial.StopBits = StopBits.One;
                //Some meters need this sleep. Do not remove.
                Thread.Sleep(800);
            }
        }
コード例 #29
0
        private void StartWithIec()
        {
            //Query device information.
            GXSerial serial = Media as GXSerial;

            if (serial == null)
            {
                return;
            }
            if (UseIec)
            {
                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;
            }

            byte   Terminator = (byte)0x0A;
            string data       = "/?!\r\n";

            if (Trace > TraceLevel.Info)
            {
                Console.WriteLine("IEC sending:" + data);
            }
            ReceiveParameters <string> p = new ReceiveParameters <string>()
            {
                Eop      = Terminator,
                WaitTime = WaitTime
            };

            lock (Media.Synchronous)
            {
                WriteTrace("<- " + DateTime.Now.ToLongTimeString() + "\t" + GXCommon.ToHex(ASCIIEncoding.ASCII.GetBytes(data), true));
                Media.Send(data, null);
                if (!Media.Receive(p))
                {
                    //Try to move away from mode E.
                    try
                    {
                        GXReplyData reply = new GXReplyData();
                        ReadDLMSPacket(Client.DisconnectRequest(), reply);
                    }
                    catch (Exception)
                    {
                    }
                    data = (char)0x01 + "B0" + (char)0x03;
                    Media.Send(data, null);
                    p.Count = 1;
                    if (!Media.Receive(p))
                    {
                    }
                    data = "Failed to receive reply from the device in given time.";
                    Console.WriteLine(data);
                    throw new Exception(data);
                }
                WriteTrace("-> " + DateTime.Now.ToLongTimeString() + "\t" + GXCommon.ToHex(ASCIIEncoding.ASCII.GetBytes(p.Reply), true));
                //If echo is used.
                if (p.Reply == data)
                {
                    p.Reply = null;
                    if (!Media.Receive(p))
                    {
                        //Try to move away from mode E.
                        GXReplyData reply = new GXReplyData();
                        ReadDLMSPacket(Client.DisconnectRequest(), reply);
                        if (serial != null)
                        {
                            data = (char)0x01 + "B0" + (char)0x03;
                            Media.Send(data, null);
                            p.Count = 1;
                            Media.Receive(p);
                            serial.BaudRate = 9600;
                            data            = (char)0x01 + "B0" + (char)0x03 + "\r\n";
                            Media.Send(data, null);
                            p.Count = 1;
                            Media.Receive(p);
                        }

                        data = "Failed to receive reply from the device in given time.";
                        Console.WriteLine(data);
                        throw new Exception(data);
                    }
                    WriteTrace("-> " + DateTime.Now.ToLongTimeString() + "\t" + GXCommon.ToHex(ASCIIEncoding.ASCII.GetBytes(p.Reply), true));
                }
            }
            Console.WriteLine("IEC received: " + p.Reply);
            if (p.Reply[0] != '/')
            {
                p.WaitTime = 100;
                Media.Receive(p);
                throw new Exception("Invalid responce.");
            }
            string manufactureID = p.Reply.Substring(1, 3);
            char   baudrate      = p.Reply[4];
            int    BaudRate      = 0;

            switch (baudrate)
            {
            case '0':
                BaudRate = 300;
                break;

            case '1':
                BaudRate = 600;
                break;

            case '2':
                BaudRate = 1200;
                break;

            case '3':
                BaudRate = 2400;
                break;

            case '4':
                BaudRate = 4800;
                break;

            case '5':
                BaudRate = 9600;
                break;

            case '6':
                BaudRate = 19200;
                break;

            default:
                throw new Exception("Unknown baud rate.");
            }
            Console.WriteLine("BaudRate is : " + BaudRate.ToString());
            //Send ACK
            //Send Protocol control character
            byte controlCharacter = (byte)'2';     // "2" HDLC protocol procedure (Mode E)
                                                   //Send Baudrate character
                                                   //Mode control character
            byte ModeControlCharacter = (byte)'2'; //"2" //(HDLC protocol procedure) (Binary mode)

            //Set mode E.
            byte[] arr = new byte[] { 0x06, controlCharacter, (byte)baudrate, ModeControlCharacter, 13, 10 };
            Console.WriteLine("Moving to mode E.", arr);
            lock (Media.Synchronous)
            {
                WriteTrace("<- " + DateTime.Now.ToLongTimeString() + "\t" + GXCommon.ToHex(arr, true));
                Media.Send(arr, null);
                p.Reply = null;

                p.WaitTime = 2000;
                //Note! All meters do not echo this.
                Media.Receive(p);
                if (p.Reply != null)
                {
                    WriteTrace("-> " + DateTime.Now.ToLongTimeString() + "\t" + GXCommon.ToHex(ASCIIEncoding.ASCII.GetBytes(p.Reply), true));
                    Console.WriteLine("Received: " + p.Reply);
                }
                if (serial != null)
                {
                    Media.Close();
                    serial.BaudRate = BaudRate;
                    serial.DataBits = 8;
                    serial.Parity   = Parity.None;
                    serial.StopBits = StopBits.One;
                    Media.Open();
                    //Some meters need this sleep. Do not remove.
                    Thread.Sleep(1000);
                }
            }
        }
コード例 #30
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);
            }
        }
コード例 #31
0
ファイル: Settings.cs プロジェクト: davudjokar63/Gurux.Serial
        void IGXPropertyPage.Initialize()
        {
            //Update texts.
            this.Text             = Resources.SettingsTxt;
            this.PortNameLbl.Text = Resources.PortNameTxt;
            this.BaudRateLbl.Text = Resources.BaudRateTxt;
            this.DataBitsLbl.Text = Resources.DataBitsTxt;
            this.ParityLbl.Text   = Resources.ParityTxt;
            this.StopBitsLbl.Text = Resources.StopBitsTxt;
            //Hide controls which user do not want to show.
            PortNamePanel.Enabled = (target.ConfigurableSettings & AvailableMediaSettings.PortName) != 0;
            if (PortNamePanel.Enabled)
            {
                if (target.AvailablePorts != null)
                {
                    PortNameCB.Items.AddRange(target.AvailablePorts);
                }
                else
                {
                    PortNameCB.Items.AddRange(GXSerial.GetPortNames());
                }
                if (this.PortNameCB.Items.Contains(target.PortName))
                {
                    this.PortNameCB.SelectedItem = target.PortName;
                }
                else
                {
                    if (PortNameCB.Items.Count != 0)
                    {
                        this.PortNameCB.SelectedIndex = 0;
                    }
                    else
                    {
                        StopBitsPanel.Enabled = ParityPanel.Enabled = DataBitsPanel.Enabled = BaudRatePanel.Enabled = this.PortNameCB.Enabled = false;
                        return;
                    }
                }
            }
            BaudRatePanel.Enabled = (target.ConfigurableSettings & AvailableMediaSettings.BaudRate) != 0;
            if (BaudRatePanel.Enabled)
            {
                PortNameCB_SelectedIndexChanged(null, null);
                this.BaudRateCB.SelectedItem = target.BaudRate;
            }
            DataBitsPanel.Enabled = (target.ConfigurableSettings & AvailableMediaSettings.DataBits) != 0;
            if (DataBitsPanel.Enabled)
            {
                this.DataBitsCB.Items.Add(7);
                this.DataBitsCB.Items.Add(8);
                this.DataBitsCB.SelectedItem = target.DataBits;
            }

            ParityPanel.Enabled = (target.ConfigurableSettings & AvailableMediaSettings.Parity) != 0;
            if (ParityPanel.Enabled)
            {
                this.ParityCB.Items.Add(System.IO.Ports.Parity.None);
                this.ParityCB.Items.Add(System.IO.Ports.Parity.Odd);
                this.ParityCB.Items.Add(System.IO.Ports.Parity.Even);
                this.ParityCB.Items.Add(System.IO.Ports.Parity.Mark);
                this.ParityCB.Items.Add(System.IO.Ports.Parity.Space);
                this.ParityCB.SelectedItem = target.Parity;
            }

            StopBitsPanel.Enabled = (target.ConfigurableSettings & AvailableMediaSettings.StopBits) != 0;
            if (StopBitsPanel.Enabled)
            {
                this.StopBitsCB.Items.Add(System.IO.Ports.StopBits.None);
                this.StopBitsCB.Items.Add(System.IO.Ports.StopBits.One);
                this.StopBitsCB.Items.Add(System.IO.Ports.StopBits.OnePointFive);
                this.StopBitsCB.Items.Add(System.IO.Ports.StopBits.Two);
                this.StopBitsCB.SelectedItem = target.StopBits;
            }
            Dirty = false;
        }
コード例 #32
0
 public GXReceiveThread(GXSerial parent)
 {
     Closing = new ManualResetEvent(false);
     m_Parent = parent;
 }
コード例 #33
0
        public static int GetParameters(string[] args, Settings settings)
        {
            string[] tmp;
            List <GXCmdParameter> parameters = GXCommon.GetParameters(args, "h:p:c:s:r:iIt:a:wP:g:S:C:n:v:o:T:A:B:D:d:l:F:");
            GXNet net = null;

            foreach (GXCmdParameter it in parameters)
            {
                switch (it.Tag)
                {
                case 'w':
                    settings.client.InterfaceType = InterfaceType.WRAPPER;
                    break;

                case 'r':
                    if (string.Compare(it.Value, "sn", true) == 0)
                    {
                        settings.client.UseLogicalNameReferencing = false;
                    }
                    else if (string.Compare(it.Value, "ln", true) == 0)
                    {
                        settings.client.UseLogicalNameReferencing = true;
                    }
                    else
                    {
                        throw new ArgumentException("Invalid reference option.");
                    }
                    break;

                case 'h':
                    //Host address.
                    if (settings.media == null)
                    {
                        settings.media = new GXNet();
                    }
                    net          = settings.media as GXNet;
                    net.HostName = it.Value;
                    break;

                case 't':
                    //Trace.
                    try
                    {
                        settings.trace = (TraceLevel)Enum.Parse(typeof(TraceLevel), it.Value);
                    }
                    catch (Exception)
                    {
                        throw new ArgumentException("Invalid trace level option. (Error, Warning, Info, Verbose, Off)");
                    }
                    break;

                case 'p':
                    //Port.
                    if (settings.media == null)
                    {
                        settings.media = new GXNet();
                    }
                    net      = settings.media as GXNet;
                    net.Port = int.Parse(it.Value);
                    break;

                case 'P':    //Password
                    settings.client.Password = ASCIIEncoding.ASCII.GetBytes(it.Value);
                    break;

                case 'i':
                    //IEC.
                    settings.iec = true;
                    break;

                case 'I':
                    //AutoIncreaseInvokeID.
                    settings.client.AutoIncreaseInvokeID = true;
                    break;

                case 'v':
                    settings.invocationCounter = it.Value.Trim();
                    Objects.GXDLMSObject.ValidateLogicalName(settings.invocationCounter);
                    break;

                case 'g':
                    //Get (read) selected objects.
                    foreach (string o in it.Value.Split(new char[] { ';', ',' }))
                    {
                        tmp = o.Split(new char[] { ':' });
                        if (tmp.Length != 2)
                        {
                            throw new ArgumentOutOfRangeException("Invalid Logical name or attribute index.");
                        }
                        settings.readObjects.Add(new KeyValuePair <string, int>(tmp[0].Trim(), int.Parse(tmp[1].Trim())));
                    }
                    break;

                case 'S':    //Serial Port
                    settings.media = new GXSerial();
                    GXSerial serial = settings.media as GXSerial;
                    tmp             = it.Value.Split(':');
                    serial.PortName = tmp[0];
                    if (tmp.Length > 1)
                    {
                        serial.BaudRate = int.Parse(tmp[1]);
                        serial.DataBits = int.Parse(tmp[2].Substring(0, 1));
                        serial.Parity   = (Parity)Enum.Parse(typeof(Parity), tmp[2].Substring(1, tmp[2].Length - 2));
                        serial.StopBits = (StopBits)int.Parse(tmp[2].Substring(tmp[2].Length - 1, 1));
                    }
                    else
                    {
                        serial.BaudRate = 9600;
                        serial.DataBits = 8;
                        serial.Parity   = Parity.None;
                        serial.StopBits = StopBits.One;
                    }
                    break;

                case 'a':
                    try
                    {
                        if (string.Compare("None", it.Value, true) == 0)
                        {
                            settings.client.Authentication = Authentication.None;
                        }
                        else if (string.Compare("Low", it.Value, true) == 0)
                        {
                            settings.client.Authentication = Authentication.Low;
                        }
                        else if (string.Compare("High", it.Value, true) == 0)
                        {
                            settings.client.Authentication = Authentication.High;
                        }
                        else if (string.Compare("HighMd5", it.Value, true) == 0)
                        {
                            settings.client.Authentication = Authentication.HighMD5;
                        }
                        else if (string.Compare("HighSha1", it.Value, true) == 0)
                        {
                            settings.client.Authentication = Authentication.HighSHA1;
                        }
                        else if (string.Compare("HighSha256", it.Value, true) == 0)
                        {
                            settings.client.Authentication = Authentication.HighSHA256;
                        }
                        else if (string.Compare("HighGMac", it.Value, true) == 0)
                        {
                            settings.client.Authentication = Authentication.HighGMAC;
                        }
                        else
                        {
                            throw new ArgumentException("Invalid Authentication option: '" + it.Value + "'. (None, Low, High, HighMd5, HighSha1, HighGMac, HighSha256)");
                        }
                    }
                    catch (Exception)
                    {
                        throw new ArgumentException("Invalid Authentication option: '" + it.Value + "'. (None, Low, High, HighMd5, HighSha1, HighGMac, HighSha256)");
                    }
                    break;

                case 'C':
                    try
                    {
                        settings.client.Ciphering.Security = Convert.ToByte(Enum.Parse(typeof(Security), it.Value));
                    }
                    catch (Exception)
                    {
                        throw new ArgumentException("Invalid Ciphering option '" + it.Value + "'. (None, Authentication, Encryption, AuthenticationEncryption)");
                    }
                    break;

                case 'T':
                    settings.client.Ciphering.SystemTitle = GXCommon.HexToBytes(it.Value);
                    break;

                case 'A':
                    settings.client.Ciphering.AuthenticationKey = GXCommon.HexToBytes(it.Value);
                    break;

                case 'B':
                    settings.client.Ciphering.BlockCipherKey = GXCommon.HexToBytes(it.Value);
                    break;

                case 'D':
                    settings.client.Ciphering.DedicatedKey = GXCommon.HexToBytes(it.Value);
                    break;

                case 'F':
                    settings.client.Ciphering.InvocationCounter = UInt32.Parse(it.Value.Trim());
                    break;

                case 'o':
                    settings.outputFile = it.Value;
                    break;

                case 'd':
                    try
                    {
                        settings.client.Standard = (Standard)Enum.Parse(typeof(Standard), it.Value);
                        if (settings.client.Standard == Standard.Italy || settings.client.Standard == Standard.India || settings.client.Standard == Standard.SaudiArabia)
                        {
                            settings.client.UseUtc2NormalTime = true;
                        }
                    }
                    catch (Exception)
                    {
                        throw new ArgumentException("Invalid DLMS standard option '" + it.Value + "'. (DLMS, India, Italy, SaudiArabia, IDIS)");
                    }
                    break;

                case 'c':
                    settings.client.ClientAddress = int.Parse(it.Value);
                    break;

                case 's':
                    if (settings.client.ServerAddress != 1)
                    {
                        settings.client.ServerAddress = GXDLMSClient.GetServerAddress(settings.client.ServerAddress, int.Parse(it.Value));
                    }
                    else
                    {
                        settings.client.ServerAddress = int.Parse(it.Value);
                    }
                    break;

                case 'l':
                    settings.client.ServerAddress = GXDLMSClient.GetServerAddress(int.Parse(it.Value), settings.client.ServerAddress);
                    break;

                case 'n':
                    settings.client.ServerAddress = GXDLMSClient.GetServerAddress(int.Parse(it.Value));
                    break;

                case '?':
                    switch (it.Tag)
                    {
                    case 'c':
                        throw new ArgumentException("Missing mandatory client option.");

                    case 's':
                        throw new ArgumentException("Missing mandatory server option.");

                    case 'h':
                        throw new ArgumentException("Missing mandatory host name option.");

                    case 'p':
                        throw new ArgumentException("Missing mandatory port option.");

                    case 'r':
                        throw new ArgumentException("Missing mandatory reference option.");

                    case 'a':
                        throw new ArgumentException("Missing mandatory authentication option.");

                    case 'S':
                        throw new ArgumentException("Missing mandatory Serial port option.");

                    case 't':
                        throw new ArgumentException("Missing mandatory trace option.");

                    case 'g':
                        throw new ArgumentException("Missing mandatory OBIS code option.");

                    case 'C':
                        throw new ArgumentException("Missing mandatory Ciphering option.");

                    case 'v':
                        throw new ArgumentException("Missing mandatory invocation counter logical name option.");

                    case 'T':
                        throw new ArgumentException("Missing mandatory system title option.");

                    case 'A':
                        throw new ArgumentException("Missing mandatory authentication key option.");

                    case 'B':
                        throw new ArgumentException("Missing mandatory block cipher key option.");

                    case 'D':
                        throw new ArgumentException("Missing mandatory dedicated key option.");

                    case 'F':
                        throw new ArgumentException("Missing mandatory frame counter option.");

                    case 'd':
                        throw new ArgumentException("Missing mandatory DLMS standard option.");

                    default:
                        ShowHelp();
                        return(1);
                    }

                default:
                    ShowHelp();
                    return(1);
                }
            }
            if (settings.media == null)
            {
                ShowHelp();
                return(1);
            }
            return(0);
        }
コード例 #34
0
        void InitSerial()
        {
            GXSerial serial     = Media as GXSerial;
            byte     Terminator = (byte)0x0A;

            if (serial != null && InitializeIEC)
            {
                serial.BaudRate = 300;
                serial.DataBits = 7;
                serial.Parity   = Parity.Even;
                serial.StopBits = StopBits.One;
            }
            Media.Open();
            //Query device information.
            if (Media != null && InitializeIEC)
            {
                string data = "/?001!\r\n";
                if (Trace)
                {
                    Console.WriteLine("HDLC sending:" + data);
                }
                ReceiveParameters <string> p = new ReceiveParameters <string>()
                {
                    Eop      = Terminator,
                    WaitTime = WaitTime
                };
                lock (Media.Synchronous)
                {
                    Media.Send(data, null);
                    if (!Media.Receive(p))
                    {
                        //Try to move away from mode E.
                        throw new Exception("Failed to receive reply from the device in given time.");
                    }
                    //If echo is used.
                    if (p.Reply == data)
                    {
                        p.Reply = null;
                        if (!Media.Receive(p))
                        {
                            //Try to move away from mode E.
                            throw new Exception("Failed to receive reply from the device in given time.");
                        }
                    }
                }
                if (Trace)
                {
                    Console.WriteLine("HDLC received: " + p.Reply);
                }
                if (p.Reply[0] != '/')
                {
                    p.WaitTime = 100;
                    Media.Receive(p);
                    throw new Exception("Invalid responce.");
                }
                string manufactureID = p.Reply.Substring(1, 3);
                //UpdateManufactureSettings(manufactureID);
                char baudrate = p.Reply[4];
                int  BaudRate = 0;
                switch (baudrate)
                {
                case '0':
                    BaudRate = 300;
                    break;

                case '1':
                    BaudRate = 600;
                    break;

                case '2':
                    BaudRate = 1200;
                    break;

                case '3':
                    BaudRate = 2400;
                    break;

                case '4':
                    BaudRate = 4800;
                    break;

                case '5':
                    BaudRate = 9600;
                    break;

                case '6':
                    BaudRate = 19200;
                    break;

                default:
                    throw new Exception("Unknown baud rate.");
                }
                Console.WriteLine("BaudRate is :", BaudRate.ToString());
                //Send ACK
                //Send Protocol control character
                byte controlCharacter = (byte)'2';// "2" HDLC protocol procedure (Mode E)
                //Send Baudrate character
                //Mode control character
                byte ModeControlCharacter = (byte)'2';//"2" //(HDLC protocol procedure) (Binary mode)
                //Set mode E.
                byte[] arr = new byte[] { 0x06, controlCharacter, (byte)baudrate, ModeControlCharacter, 13, 10 };
                if (Trace)
                {
                    Console.WriteLine("Moving to mode E", BitConverter.ToString(arr));
                }
                lock (Media.Synchronous)
                {
                    Media.Send(arr, null);
                    p.Reply    = null;
                    p.WaitTime = 500;
                    if (!Media.Receive(p))
                    {
                        //Try to move away from mode E.
                        this.ReadDLMSPacket(m_Parser.DisconnectRequest());
                        throw new Exception("Failed to receive reply from the device in given time.");
                    }
                }
                if (serial != null)
                {
                    serial.BaudRate = BaudRate;
                    serial.DataBits = 8;
                    serial.Parity   = Parity.None;
                    serial.StopBits = StopBits.One;
                }
            }
        }