public void Write(GXDLMSObject obj, object target, int index, List <object> UpdatedObjects) { object value; GXReplyData reply = new GXReplyData(); for (int it = 1; it != (obj as IGXDLMSBase).GetAttributeCount() + 1; ++it) { reply.Clear(); if (obj.GetDirty(it, out value)) { //Read DLMS data type if not known. DataType type = obj.GetDataType(it); if (type == DataType.None) { byte[] data = client.Read(obj, it)[0]; ReadDataBlock(data, "Write object type " + obj.ObjectType, reply); type = reply.DataType; if (type == DataType.None) { throw new Exception("Failed to write value. Data type not set."); } obj.SetDataType(it, type); } try { ValueEventArgs e = new ValueEventArgs(obj, it, 0, null); e.Value = value; ((IGXDLMSBase)obj).SetValue(null, e); foreach (byte[] tmp in client.Write(obj, it)) { ReadDataBlock(tmp, "Write object", reply); } obj.ClearDirty(it); //Read data once again to make sure it is updated. reply.Clear(); byte[] data = client.Read(obj, it)[0]; ReadDataBlock(data, "Read object " + obj.ObjectType, reply); value = reply.Value; if (value is byte[] && (type = obj.GetUIDataType(it)) != DataType.None) { value = GXDLMSClient.ChangeType((byte[])value, type); } client.UpdateValue(obj, it, value); } catch (GXDLMSException ex) { if (ex.ErrorCode == 3) { throw new Exception("Read/Write Failed."); } else { throw ex; } } } } }
/// <summary> /// Read object. /// </summary> /// <param name="InitialValues"></param> /// <param name="obj"></param> /// <param name="attribute"></param> public void Read(object sender, GXDLMSObject obj, int attribute) { foreach (int it in (obj as IGXDLMSBase).GetAttributeIndexToRead()) { if (obj is GXDLMSProfileGeneric && it == 2) { if (OnBeforeRead != null) { OnBeforeRead(obj, it); } try { CurrentProfileGeneric = obj as GXDLMSProfileGeneric; OnDataReceived += new GXDLMSCommunicator.DataReceivedEventHandler(this.OnProfileGenericDataReceived); if (CurrentProfileGeneric.AccessSelector != AccessRange.Entry) { GXDLMSObject obj2 = CurrentProfileGeneric.CaptureObjects[0].Key; byte[] tmp = m_Cosem.ReadRowsByRange(CurrentProfileGeneric.Name, obj2.LogicalName, obj2.ObjectType, obj2.Version, Convert.ToDateTime(CurrentProfileGeneric.From), Convert.ToDateTime(CurrentProfileGeneric.To)); ReadDataBlock(tmp, "Reading profile generic data", 1); } else { byte[] tmp = m_Cosem.ReadRowsByEntry(CurrentProfileGeneric.Name, Convert.ToInt32(CurrentProfileGeneric.From), Convert.ToInt32(CurrentProfileGeneric.To)); ReadDataBlock(tmp, "Reading profile generic data " + CurrentProfileGeneric.Name, 1); } } finally { if (OnAfterRead != null) { OnAfterRead(obj, it); } OnDataReceived -= new GXDLMSCommunicator.DataReceivedEventHandler(OnProfileGenericDataReceived); } continue; } else { if (OnBeforeRead != null) { OnBeforeRead(obj, it); } byte[] data = m_Cosem.Read(obj.Name, obj.ObjectType, it)[0]; try { data = ReadDataBlock(data, "Read object type " + obj.ObjectType + " index: " + it); } catch (GXDLMSException ex) { if (ex.ErrorCode == 3 || //If read is denied. ex.ErrorCode == 4 || // Undefined object. ex.ErrorCode == 13) //Actaris returns access violation error. { obj.SetAccess(it, AccessMode.NoAccess); continue; } else { throw ex; } } if (obj is IGXDLMSBase) { object value = m_Cosem.GetValue(data); DataType type; if (value is byte[] && (type = obj.GetUIDataType(it)) != DataType.None) { value = GXDLMS.Common.GXHelpers.ConvertFromDLMS(value, obj.GetDataType(it), type, true); } (obj as IGXDLMSBase).SetValue(it, value); } if (OnAfterRead != null) { OnAfterRead(obj, it); } obj.SetLastReadTime(it, DateTime.Now); //If only selected attribute is read. if (attribute != 0) { break; } } } }
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); } } }
/// <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.UseUtc2NormalTime = 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) { //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.Reader.Read(null, httpClient, 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] } }; using (System.Net.Http.HttpResponseMessage response = httpClient.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 }; 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(); } } } }
/// <summary> /// Read object. /// </summary> /// <param name="InitialValues"></param> /// <param name="obj"></param> /// <param name="attribute">Attribute index to read.</param> /// <param name="forceRead">Force all attributes read.</param> public void Read(object sender, GXDLMSObject obj, int attribute, bool forceRead) { GXReplyData reply = new GXReplyData(); if (forceRead) { obj.ClearReadTime(); } foreach (int it in (obj as IGXDLMSBase).GetAttributeIndexToRead()) { reply.Clear(); if (obj is GXDLMSProfileGeneric && it == 2) { if (OnBeforeRead != null) { OnBeforeRead(obj, it); } try { byte[][] tmp; CurrentProfileGeneric = obj as GXDLMSProfileGeneric; OnDataReceived += new GXDLMSCommunicator.DataReceivedEventHandler(this.OnProfileGenericDataReceived); if (CurrentProfileGeneric.AccessSelector == AccessRange.Range || CurrentProfileGeneric.AccessSelector == AccessRange.Last) { GXDateTime start = CurrentProfileGeneric.From as GXDateTime; if (start == null) { start = Convert.ToDateTime(CurrentProfileGeneric.From); } GXDateTime end = CurrentProfileGeneric.To as GXDateTime; if (end == null) { end = Convert.ToDateTime(CurrentProfileGeneric.To); } tmp = client.ReadRowsByRange(CurrentProfileGeneric, start, end); ReadDataBlock(tmp, "Reading profile generic data", 1, reply); } else if (CurrentProfileGeneric.AccessSelector == AccessRange.Entry) { tmp = client.ReadRowsByEntry(CurrentProfileGeneric, Convert.ToInt32(CurrentProfileGeneric.From), Convert.ToInt32(CurrentProfileGeneric.To)); ReadDataBlock(tmp, "Reading profile generic data " + CurrentProfileGeneric.Name, 1, reply); } else //Read all. { tmp = client.Read(CurrentProfileGeneric, 2); ReadDataBlock(tmp, "Reading profile generic data " + CurrentProfileGeneric.Name, 1, reply); } } finally { if (OnAfterRead != null) { OnAfterRead(obj, it); } OnDataReceived -= new GXDLMSCommunicator.DataReceivedEventHandler(OnProfileGenericDataReceived); } continue; } else { if (OnBeforeRead != null) { OnBeforeRead(obj, it); } byte[] data = client.Read(obj.Name, obj.ObjectType, it)[0]; try { ReadDataBlock(data, "Read object type " + obj.ObjectType + " index: " + it, reply); } catch (GXDLMSException ex) { if (ex.ErrorCode == (int)ErrorCode.ReadWriteDenied || ex.ErrorCode == (int)ErrorCode.UndefinedObject || ex.ErrorCode == (int)ErrorCode.UnavailableObject || //Actaris returns access violation error. ex.ErrorCode == (int)ErrorCode.AccessViolated) { obj.SetAccess(it, AccessMode.NoAccess); continue; } else { throw ex; } } if (obj is IGXDLMSBase) { object value = reply.Value; DataType type; if (value is byte[] && (type = obj.GetUIDataType(it)) != DataType.None) { value = GXDLMSClient.ChangeType((byte[])value, type); } client.UpdateValue(obj, it, value); } if (OnAfterRead != null) { OnAfterRead(obj, it); } obj.SetLastReadTime(it, DateTime.Now); //If only selected attribute is read. if (attribute != 0) { break; } } } }
public void Write(GXDLMSObject obj, int index) { object val; GXReplyData reply = new GXReplyData(); for (int it = 1; it != (obj as IGXDLMSBase).GetAttributeCount() + 1; ++it) { reply.Clear(); if (it == index || (index == 0 && obj.GetDirty(it, out val))) { bool forced = false; GXDLMSAttributeSettings att = obj.Attributes.Find(it); //Read DLMS data type if not known. DataType type = obj.GetDataType(it); if (type == DataType.None) { byte[] data = client.Read(obj, it)[0]; ReadDataBlock(data, "Read object type " + obj.ObjectType, reply); type = reply.DataType; if (type == DataType.None) { throw new Exception("Failed to write value. Data type not set."); } obj.SetDataType(it, type); reply.Clear(); } try { if (att != null && att.ForceToBlocks) { forced = client.ForceToBlocks = true; } foreach (byte[] tmp in client.Write(obj, it)) { ReadDataBlock(tmp, string.Format("Writing object {0}, interface {1}", obj.LogicalName, obj.ObjectType), reply); } obj.ClearDirty(it); //Read data once again to make sure it is updated. reply.Clear(); byte[] data = client.Read(obj, it)[0]; ReadDataBlock(data, string.Format("Reading object {0}, interface {1}", obj.LogicalName, obj.ObjectType), reply); val = reply.Value; if (val is byte[] && (type = obj.GetUIDataType(it)) != DataType.None) { val = GXDLMSClient.ChangeType((byte[])val, type); } client.UpdateValue(obj, it, val); } catch (GXDLMSException ex) { if (ex.ErrorCode == 3) { throw new Exception("Read/Write Failed."); } else { throw ex; } } finally { if (forced) { client.ForceToBlocks = false; } } } } }