コード例 #1
0
 private void createTestDevicesToolStripMenuItem_Click(object sender, EventArgs e)
 {
     try
     {
         GXDeviceTemplate[] templates = ami.templates;
         GXDeviceTemplate   target    = null;
         if (TemplatesView.SelectedItems.Count == 1)
         {
             target = (GXDeviceTemplate)TemplatesView.SelectedItems[0].Tag;
         }
         TestDevicesDlg dlg = new TestDevicesDlg(target, templates);
         if (dlg.ShowDialog(panel1.Parent) == DialogResult.OK)
         {
             GXDevice dev = new GXDevice();
             GXDevice.Copy(dev, dlg.target);
             dev.TemplateId   = dlg.target.Id;
             dev.Manufacturer = dlg.target.Name;
             ami.AddTestDevices(dev, dlg.Index, dlg.Count);
             MessageBox.Show(panel1.Parent, "Test devices added.", "GXDLMSDirector", MessageBoxButtons.OK, MessageBoxIcon.Information);
         }
     }
     catch (Exception Ex)
     {
         MessageBox.Show(panel1.Parent, Ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
 }
コード例 #2
0
 private void TemplatesAdd_Click(object sender, EventArgs e)
 {
     try
     {
         OpenFileDialog dlg = new OpenFileDialog();
         dlg.Multiselect      = false;
         dlg.InitialDirectory = Directory.GetCurrentDirectory();
         dlg.Filter           = Properties.Resources.FilterTxt;
         dlg.DefaultExt       = ".gdr";
         dlg.ValidateNames    = true;
         if (dlg.ShowDialog(panel1.Parent) == DialogResult.OK)
         {
             if (File.Exists(dlg.FileName))
             {
                 List <GXDLMSDevice> devices;
                 using (XmlReader reader = XmlReader.Create(dlg.FileName))
                 {
                     List <Type> types = new List <Type>(Gurux.DLMS.GXDLMSClient.GetObjectTypes());
                     types.Add(typeof(GXDLMSAttributeSettings));
                     types.Add(typeof(GXDLMSAttribute));
                     //Version is added to namespace.
                     XmlSerializer x = new XmlSerializer(typeof(List <GXDLMSDevice>), null, types.ToArray(), null, "Gurux1");
                     if (!x.CanDeserialize(reader))
                     {
                         x = new XmlSerializer(typeof(List <GXDLMSDevice>), types.ToArray());
                     }
                     devices = (List <GXDLMSDevice>)x.Deserialize(reader);
                     reader.Close();
                 }
                 GXDeviceTemplate        m         = new GXDeviceTemplate();
                 List <GXDeviceTemplate> templates = new List <GXDeviceTemplate>();
                 foreach (GXDLMSDevice it in devices)
                 {
                     GXDeviceTemplate t = new GXDeviceTemplate();
                     GXDevice.Copy(t, it);
                     if (!string.IsNullOrEmpty(it.Password))
                     {
                         t.Password = ASCIIEncoding.ASCII.GetString(CryptHelper.Decrypt(it.Password, Password.Key));
                     }
                     else if (it.HexPassword != null)
                     {
                         t.Password = GXDLMSTranslator.ToHex(CryptHelper.Decrypt(it.HexPassword, Password.Key));
                     }
                     List <GXObjectTemplate> list = new List <GXObjectTemplate>();
                     foreach (GXDLMSObject value in it.Objects)
                     {
                         string[]         names = ((IGXDLMSBase)value).GetNames();
                         GXObjectTemplate obj   = new GXObjectTemplate();
                         obj.LogicalName = value.LogicalName;
                         obj.ObjectType  = (int)value.ObjectType;
                         obj.Name        = value.Description;
                         obj.Version     = value.Version;
                         obj.ShortName   = value.ShortName;
                         list.Add(obj);
                         for (int pos = 2; pos <= ((IGXDLMSBase)value).GetAttributeCount(); ++pos)
                         {
                             GXAttributeTemplate a = new GXAttributeTemplate();
                             a.Index       = pos;
                             a.AccessLevel = (int)value.GetAccess(pos);
                             a.DataType    = (int)((IGXDLMSBase)value).GetDataType(pos);
                             a.UIDataType  = (int)((GXDLMSObject)value).GetUIDataType(pos);
                             if (value.GetStatic(pos))
                             {
                                 a.ExpirationTime = 0xFFFFFFFF;
                             }
                             //Profile generic capture object read is not allowed.
                             if (value is GXDLMSProfileGeneric && pos == 3)
                             {
                                 a.ExpirationTime = 0xFFFFFFFF;
                             }
                             obj.Attributes.Add(a);
                         }
                         t.Objects = list;
                     }
                     templates.Add(t);
                 }
                 DBDevicePropertiesForm dlg2 = new DBDevicePropertiesForm(templates.ToArray(), m);
                 if (dlg2.ShowDialog(panel1.Parent) == DialogResult.OK)
                 {
                     {
                         ami.AddDeviceTemplates(new GXDLMSMeterBase[] { m });
                         ListViewItem li = TemplatesView.Items.Add(m.Name);
                         li.Tag      = m;
                         li.Selected = true;
                     }
                 }
             }
         }
     }
     catch (Exception Ex)
     {
         MessageBox.Show(panel1.Parent, Ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
 }
コード例 #3
0
        /// <summary>
        /// Read data from the meter.
        /// </summary>
        private static void ReadMeter(object parameter)
        {
            GXDLMSReader reader = null;

            System.Net.Http.HttpClient httpClient = Helpers.client;
            using (GXNet media = (GXNet)parameter)
            {
                try
                {
                    var config = new ConfigurationBuilder()
                                 .SetBasePath(Directory.GetCurrentDirectory())
                                 .AddJsonFile("appsettings.json", optional: true)
                                 .Build();
                    ListenerOptions        listener = config.GetSection("Listener").Get <ListenerOptions>();
                    GXDLMSObjectCollection objects  = new GXDLMSObjectCollection();
                    GXDLMSSecureClient     client   = new GXDLMSSecureClient(listener.UseLogicalNameReferencing, listener.ClientAddress, listener.ServerAddress, (Authentication)listener.Authentication, listener.Password, (InterfaceType)listener.Interface);
                    reader = new GXDLMSReader(client, media, _logger);
                    GXDLMSData ldn = new GXDLMSData("0.0.42.0.0.255");
                    ldn.SetUIDataType(2, DataType.String);
                    reader.InitializeConnection();
                    reader.Read(ldn, 2);
                    Console.WriteLine("Meter connected: " + ldn.Value);
                    //Find device.
                    GXDevice            dev  = null;
                    ListDevicesResponse devs = null;
                    {
                        using (System.Net.Http.HttpResponseMessage response = httpClient.PostAsJsonAsync(Startup.ServerAddress + "/api/device/ListDevices", new ListDevices()
                        {
                            Name = (string)ldn.Value
                        }).Result)
                        {
                            Helpers.CheckStatus(response);
                            devs = response.Content.ReadAsAsync <ListDevicesResponse>().Result;
                        }
                        //If device is unknown.
                        if (devs.Devices.Length == 0)
                        {
                            if (listener.DefaultDeviceTemplate == 0)
                            {
                                string str = "Unknown Meter try to connect to the Gurux.DLMS.AMI server: " + ldn.Value;
                                Console.WriteLine(str);
                                AddSystemError info = new AddSystemError();
                                info.Error = new GXSystemError()
                                {
                                    Error = str
                                };
                                using (System.Net.Http.HttpResponseMessage response = httpClient.PostAsJsonAsync(Startup.ServerAddress + "/api/SystemError/AddSystemError", info).Result)
                                {
                                    Helpers.CheckStatus(response);
                                }
                                return;
                            }
                            ListDeviceTemplates lt = new ListDeviceTemplates()
                            {
                                Ids = new UInt64[] { listener.DefaultDeviceTemplate }
                            };
                            using (System.Net.Http.HttpResponseMessage response = httpClient.PostAsJsonAsync(Startup.ServerAddress + "/api/template/ListDeviceTemplates", lt).Result)
                            {
                                Helpers.CheckStatus(response);
                                ListDeviceTemplatesResponse ret = response.Content.ReadAsAsync <ListDeviceTemplatesResponse>().Result;
                                if (ret.Devices.Length != 1)
                                {
                                    throw new Exception("DefaultDeviceTemplate value is invalid: " + listener.DefaultDeviceTemplate);
                                }
                                dev = new GXDevice();
                                GXDevice.Copy(dev, ret.Devices[0]);
                                dev.Name         = Convert.ToString(ldn.Value);
                                dev.TemplateId   = listener.DefaultDeviceTemplate;
                                dev.Manufacturer = ret.Devices[0].Name;
                            }
                            dev.Dynamic = true;
                            UpdateDevice update = new UpdateDevice();
                            update.Device = dev;
                            using (System.Net.Http.HttpResponseMessage response = httpClient.PostAsJsonAsync(Startup.ServerAddress + "/api/device/UpdateDevice", update).Result)
                            {
                                Helpers.CheckStatus(response);
                                UpdateDeviceResponse r = response.Content.ReadAsAsync <UpdateDeviceResponse>().Result;
                                dev.Id = r.DeviceId;
                            }
                            using (System.Net.Http.HttpResponseMessage response = httpClient.PostAsJsonAsync(Startup.ServerAddress + "/api/device/ListDevices", new ListDevices()
                            {
                                Ids = new UInt64[] { dev.Id }
                            }).Result)
                            {
                                Helpers.CheckStatus(response);
                                devs = response.Content.ReadAsAsync <ListDevicesResponse>().Result;
                            }
                        }
                        else if (devs.Devices.Length != 1)
                        {
                            throw new Exception("There are multiple devices with same name: " + ldn.Value);
                        }
                        else
                        {
                            dev = devs.Devices[0];
                            if (dev.Security != Security.None)
                            {
                                Console.WriteLine("Reading frame counter.");
                                GXDLMSData fc = new GXDLMSData(listener.InvocationCounter);
                                reader.Read(fc, 2);
                                dev.InvocationCounter = 1 + Convert.ToUInt32(fc.Value);
                                Console.WriteLine("Device ID: " + dev.Id + " LDN: " + (string)ldn.Value);
                                Console.WriteLine("Frame counter: " + dev.FrameCounter);
                            }
                            GetNextTaskResponse ret;
                            using (System.Net.Http.HttpResponseMessage response = httpClient.PostAsJsonAsync(Startup.ServerAddress + "/api/task/GetNextTask", new GetNextTask()
                            {
                                Listener = true, DeviceId = dev.Id
                            }).Result)
                            {
                                Helpers.CheckStatus(response);
                                ret = response.Content.ReadAsAsync <GetNextTaskResponse>().Result;
                            }
                            if (ret.Tasks == null || ret.Tasks.Length == 0)
                            {
                                Console.WriteLine("No tasks to execute");
                            }
                            else
                            {
                                Console.WriteLine("Task count: " + ret.Tasks.Length);
                                if (client.ClientAddress != dev.ClientAddress || dev.Security != Security.None)
                                {
                                    reader.Release();
                                    reader.Disconnect();
                                    client             = new GXDLMSSecureClient(dev.UseLogicalNameReferencing, dev.ClientAddress, dev.PhysicalAddress, (Authentication)dev.Authentication, dev.Password, dev.InterfaceType);
                                    client.UtcTimeZone = dev.UtcTimeZone;
                                    client.Standard    = (Standard)dev.Standard;
                                    if (dev.Conformance != 0)
                                    {
                                        client.ProposedConformance = (Conformance)dev.Conformance;
                                    }
                                    client.Priority                    = dev.Priority;
                                    client.ServiceClass                = dev.ServiceClass;
                                    client.Ciphering.SystemTitle       = GXCommon.HexToBytes(dev.ClientSystemTitle);
                                    client.Ciphering.BlockCipherKey    = GXCommon.HexToBytes(dev.BlockCipherKey);
                                    client.Ciphering.AuthenticationKey = GXCommon.HexToBytes(dev.AuthenticationKey);
                                    client.ServerSystemTitle           = GXCommon.HexToBytes(dev.DeviceSystemTitle);
                                    client.Ciphering.InvocationCounter = dev.InvocationCounter;
                                    client.Ciphering.Security          = (Security)dev.Security;
                                    reader = new GXDLMSReader(client, media, _logger);
                                    reader.InitializeConnection();
                                }
                                List <GXValue> values = new List <GXValue>();
                                foreach (GXTask task in ret.Tasks)
                                {
                                    GXDLMSObject obj = GXDLMSClient.CreateObject((ObjectType)task.Object.ObjectType);
                                    obj.LogicalName = task.Object.LogicalName;
                                    try
                                    {
                                        if (task.TaskType == TaskType.Write)
                                        {
                                            if (obj.LogicalName == "0.0.1.1.0.255" && task.Index == 2)
                                            {
                                                client.UpdateValue(obj, task.Index, GXDateTime.ToUnixTime(DateTime.UtcNow));
                                            }
                                            else
                                            {
                                                client.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)
                                        {
                                            Reader.Reader.Read(null, httpClient, reader, task, media, obj);
                                        }
                                    }
                                    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
                                        };
                                        using (System.Net.Http.HttpResponseMessage response = httpClient.PostAsJsonAsync(Startup.ServerAddress + "/api/error/AddError", error).Result)
                                        {
                                            Helpers.CheckStatus(response);
                                            response.Content.ReadAsAsync <AddErrorResponse>();
                                        }
                                    }
                                    using (System.Net.Http.HttpResponseMessage response = httpClient.PostAsJsonAsync(Startup.ServerAddress + "/api/task/TaskReady", new TaskReady()
                                    {
                                        Tasks = new GXTask[] { task }
                                    }).Result)
                                    {
                                        Helpers.CheckStatus(response);
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    try
                    {
                        AddSystemError info = new AddSystemError();
                        info.Error = new GXSystemError()
                        {
                            Error = ex.Message
                        };
                        using (System.Net.Http.HttpResponseMessage response = httpClient.PostAsJsonAsync(Startup.ServerAddress + "/api/SystemError/AddSystemError", info).Result)
                        {
                            Helpers.CheckStatus(response);
                        }
                    }
                    catch (Exception ex2)
                    {
                    }
                }
                finally
                {
                    if (reader != null)
                    {
                        reader.Close();
                    }
                }
            }
        }