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; } }
/// <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(); } } } }