/// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context) { ListDevicesResponse response = new ListDevicesResponse(); context.Read(); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.TestExpression("Devices", targetDepth)) { var unmarshaller = new ListUnmarshaller <DeviceType, DeviceTypeUnmarshaller>(DeviceTypeUnmarshaller.Instance); response.Devices = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("PaginationToken", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.PaginationToken = unmarshaller.Unmarshall(context); continue; } } return(response); }
public override void Invoke(AWSCredentials creds, RegionEndpoint region, int maxItems) { AmazonSageMakerConfig config = new AmazonSageMakerConfig(); config.RegionEndpoint = region; ConfigureClient(config); AmazonSageMakerClient client = new AmazonSageMakerClient(creds, config); ListDevicesResponse resp = new ListDevicesResponse(); do { ListDevicesRequest req = new ListDevicesRequest { NextToken = resp.NextToken , MaxResults = maxItems }; resp = client.ListDevices(req); CheckError(resp.HttpStatusCode, "200"); foreach (var obj in resp.DeviceSummaries) { AddObject(obj); } }while (!string.IsNullOrEmpty(resp.NextToken)); }
public override Task <ListDevicesResponse> ListDevices(ListDevicesRequest request, ServerCallContext context) { IOptionsSnapshot <DeviceOptions> deviceOptions = this.serviceProvider.GetRequiredService <IOptionsSnapshot <DeviceOptions> >(); var response = new ListDevicesResponse(); response.Devices.Add( from d in deviceOptions.Value.Devices let id = ByteString.CopyFrom(d.ComputeIdBinary()) join e in this.plcManager.PlcDictionary.AsEnumerable() on id equals e.Key into g from e in g.DefaultIfEmpty() select new Device { Id = id, Name = d.Name, Ipv4Address = e.Value == null ? ByteString.Empty : ByteString.CopyFrom(((IPEndPoint)e.Value.RemoteEndPoint).Address.GetAddressBytes()), Status = e.Value == null ? DeviceStatus.Disconnected : DeviceStatus.Healthy, }); return(Task.FromResult(response)); }
public override AsyncUnaryCall <ListDevicesResponse> ListDevicesAsync(ListDevicesRequest request, Metadata headers = null, DateTime?deadline = null, CancellationToken cancellationToken = default) { var response = new ListDevicesResponse(); response.Devices.Add(Devices.Values); return(TestCalls.AsyncUnaryCall( Task.FromResult(response), Task.FromResult(new Metadata()), () => Status.DefaultSuccess, () => new Metadata(), () => { })); }
/// <summary> /// Lists the CognitoDevices associated with this user using an asynchronous call /// </summary> /// <param name="limit">Maxmimum number of devices to be returned in this call</param> /// <param name="paginationToken">Token to continue earlier search</param> /// <returns>Returns a list of CognitoDevices associated with this user</returns> public virtual async Task <List <CognitoDevice> > ListDevicesAsync(int limit, string paginationToken) { ListDevicesRequest listDevicesRequest = CreateListDevicesRequest(limit, paginationToken); ListDevicesResponse listDevicesReponse = await Provider.ListDevicesAsync(listDevicesRequest).ConfigureAwait(false); List <CognitoDevice> devicesList = new List <CognitoDevice>(); foreach (DeviceType device in listDevicesReponse.Devices) { devicesList.Add(new CognitoDevice(device, this)); } return(devicesList); }
public static ListDevicesResponse Unmarshall(UnmarshallerContext context) { ListDevicesResponse listDevicesResponse = new ListDevicesResponse(); listDevicesResponse.HttpResponse = context.HttpResponse; listDevicesResponse.Code = context.StringValue("ListDevices.Code"); listDevicesResponse.Message = context.StringValue("ListDevices.Message"); listDevicesResponse.RequestId = context.StringValue("ListDevices.RequestId"); ListDevicesResponse.ListDevices_Data data = new ListDevicesResponse.ListDevices_Data(); data.PageNumber = context.IntegerValue("ListDevices.Data.PageNumber"); data.PageSize = context.IntegerValue("ListDevices.Data.PageSize"); data.TotalCount = context.IntegerValue("ListDevices.Data.TotalCount"); data.TotalPage = context.IntegerValue("ListDevices.Data.TotalPage"); List <ListDevicesResponse.ListDevices_Data.ListDevices_Record> data_records = new List <ListDevicesResponse.ListDevices_Data.ListDevices_Record>(); for (int i = 0; i < context.Length("ListDevices.Data.Records.Length"); i++) { ListDevicesResponse.ListDevices_Data.ListDevices_Record record = new ListDevicesResponse.ListDevices_Data.ListDevices_Record(); record.AccessProtocolType = context.StringValue("ListDevices.Data.Records[" + i + "].AccessProtocolType"); record.BitRate = context.StringValue("ListDevices.Data.Records[" + i + "].BitRate"); record.CoverImageUrl = context.StringValue("ListDevices.Data.Records[" + i + "].CoverImageUrl"); record.GBid = context.StringValue("ListDevices.Data.Records[" + i + "].GBid"); record.DeviceAddress = context.StringValue("ListDevices.Data.Records[" + i + "].DeviceAddress"); record.DeviceDirection = context.StringValue("ListDevices.Data.Records[" + i + "].DeviceDirection"); record.DeviceSite = context.StringValue("ListDevices.Data.Records[" + i + "].DeviceSite"); record.Latitude = context.StringValue("ListDevices.Data.Records[" + i + "].Latitude"); record.Longitude = context.StringValue("ListDevices.Data.Records[" + i + "].Longitude"); record.DeviceName = context.StringValue("ListDevices.Data.Records[" + i + "].DeviceName"); record.Resolution = context.StringValue("ListDevices.Data.Records[" + i + "].Resolution"); record.SipGBId = context.StringValue("ListDevices.Data.Records[" + i + "].SipGBId"); record.SipPassword = context.StringValue("ListDevices.Data.Records[" + i + "].SipPassword"); record.SipServerIp = context.StringValue("ListDevices.Data.Records[" + i + "].SipServerIp"); record.SipServerPort = context.StringValue("ListDevices.Data.Records[" + i + "].SipServerPort"); record.Status = context.IntegerValue("ListDevices.Data.Records[" + i + "].Status"); record.DeviceType = context.StringValue("ListDevices.Data.Records[" + i + "].DeviceType"); record.Vendor = context.StringValue("ListDevices.Data.Records[" + i + "].Vendor"); record.CreateTime = context.StringValue("ListDevices.Data.Records[" + i + "].CreateTime"); data_records.Add(record); } data.Records = data_records; listDevicesResponse.Data = data; return(listDevicesResponse); }
public ActionResult <ListDevicesResponse> Post(ListDevices request) { ListDevicesResponse ret = new ListDevicesResponse(); GXSelectArgs arg = GXSelectArgs.SelectAll <GXDevice>(); arg.Where.And <GXDevice>(q => q.Removed == DateTime.MinValue); if ((request.Targets & TargetType.Attribute) != 0) { arg.Columns.Add <GXObject>(); arg.Columns.Add <GXAttribute>(); arg.Joins.AddLeftJoin <GXDevice, GXObject>(d => d.Id, o => o.DeviceId); arg.Joins.AddLeftJoin <GXObject, GXAttribute>(o => o.Id, a => a.ObjectId); arg.Where.And <GXObject>(q => q.Removed == DateTime.MinValue); arg.Where.And <GXAttribute>(q => q.Removed == DateTime.MinValue); } else if ((request.Targets & TargetType.Object) != 0) { arg.Columns.Add <GXObject>(); arg.Joins.AddLeftJoin <GXDevice, GXObject>(d => d.Id, o => o.DeviceId); arg.Where.And <GXObject>(q => q.Removed == DateTime.MinValue); } byte[] st = GXCommon.HexToBytes(request.SystemTitle); if (st.Length == 8) { string str = GXCommon.ToHex(st, false); arg.Where.And <GXDevice>(q => q.DeviceSystemTitle.Equals(str)); } else if (!string.IsNullOrEmpty(request.Name)) { string name = request.Name; arg.Where.And <GXDevice>(q => q.Name.Contains(name)); } else if (request.Ids != null) { arg.Where.And <GXDevice>(q => request.Ids.Contains(q.Id)); } ret.Devices = host.Connection.Select <GXDevice>(arg).ToArray(); return(ret); }
public static ListDevicesResponse Unmarshall(UnmarshallerContext _ctx) { ListDevicesResponse listDevicesResponse = new ListDevicesResponse(); listDevicesResponse.HttpResponse = _ctx.HttpResponse; listDevicesResponse.Code = _ctx.StringValue("ListDevices.Code"); listDevicesResponse.HttpStatusCode = _ctx.IntegerValue("ListDevices.HttpStatusCode"); listDevicesResponse.Message = _ctx.StringValue("ListDevices.Message"); listDevicesResponse.RequestId = _ctx.StringValue("ListDevices.RequestId"); List <string> listDevicesResponse_params = new List <string>(); for (int i = 0; i < _ctx.Length("ListDevices.Params.Length"); i++) { listDevicesResponse_params.Add(_ctx.StringValue("ListDevices.Params[" + i + "]")); } listDevicesResponse._Params = listDevicesResponse_params; List <ListDevicesResponse.ListDevices_Device> listDevicesResponse_data = new List <ListDevicesResponse.ListDevices_Device>(); for (int i = 0; i < _ctx.Length("ListDevices.Data.Length"); i++) { ListDevicesResponse.ListDevices_Device device = new ListDevicesResponse.ListDevices_Device(); device.CallId = _ctx.StringValue("ListDevices.Data[" + i + "].CallId"); device.Contact = _ctx.StringValue("ListDevices.Data[" + i + "].Contact"); device.DeviceId = _ctx.StringValue("ListDevices.Data[" + i + "].DeviceId"); device.Expires = _ctx.LongValue("ListDevices.Data[" + i + "].Expires"); device.Extension = _ctx.StringValue("ListDevices.Data[" + i + "].Extension"); device.InstanceId = _ctx.StringValue("ListDevices.Data[" + i + "].InstanceId"); device.UserId = _ctx.StringValue("ListDevices.Data[" + i + "].UserId"); listDevicesResponse_data.Add(device); } listDevicesResponse.Data = listDevicesResponse_data; return(listDevicesResponse); }
public static ListDevicesResponse Unmarshall(UnmarshallerContext _ctx) { ListDevicesResponse listDevicesResponse = new ListDevicesResponse(); listDevicesResponse.HttpResponse = _ctx.HttpResponse; listDevicesResponse.ErrorCode = _ctx.IntegerValue("ListDevices.ErrorCode"); listDevicesResponse.Message = _ctx.StringValue("ListDevices.Message"); listDevicesResponse.Success = _ctx.BooleanValue("ListDevices.Success"); listDevicesResponse.RequestId = _ctx.StringValue("ListDevices.RequestId"); ListDevicesResponse.ListDevices_Data data = new ListDevicesResponse.ListDevices_Data(); data.Total = _ctx.IntegerValue("ListDevices.Data.Total"); data.PageSize = _ctx.IntegerValue("ListDevices.Data.PageSize"); data.PageNumber = _ctx.IntegerValue("ListDevices.Data.PageNumber"); List <ListDevicesResponse.ListDevices_Data.ListDevices_Device> data_devices = new List <ListDevicesResponse.ListDevices_Data.ListDevices_Device>(); for (int i = 0; i < _ctx.Length("ListDevices.Data.Devices.Length"); i++) { ListDevicesResponse.ListDevices_Data.ListDevices_Device device = new ListDevicesResponse.ListDevices_Data.ListDevices_Device(); device.ActivationCode = _ctx.StringValue("ListDevices.Data.Devices[" + i + "].ActivationCode"); device.ConferenceCode = _ctx.StringValue("ListDevices.Data.Devices[" + i + "].ConferenceCode"); device.ConferenceName = _ctx.StringValue("ListDevices.Data.Devices[" + i + "].ConferenceName"); device.CreateTime = _ctx.StringValue("ListDevices.Data.Devices[" + i + "].CreateTime"); device.PictureUrl = _ctx.StringValue("ListDevices.Data.Devices[" + i + "].PictureUrl"); device.SN = _ctx.StringValue("ListDevices.Data.Devices[" + i + "].SN"); device.Status = _ctx.StringValue("ListDevices.Data.Devices[" + i + "].Status"); device.CastScreenCode = _ctx.StringValue("ListDevices.Data.Devices[" + i + "].CastScreenCode"); data_devices.Add(device); } data.Devices = data_devices; listDevicesResponse.Data = data; return(listDevicesResponse); }
/// <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(); } } } }
internal static void Read(ILogger _logger, System.Net.Http.HttpClient client, GXDLMSReader reader, GXTask task, IGXMedia net, GXDLMSObject obj) { AddValue v; System.Net.Http.HttpResponseMessage response; if (_logger != null) { _logger.LogInformation("Reading: " + obj.ToString()); } Console.WriteLine("Reading: " + obj.ToString()); object val; if (obj.ObjectType == ObjectType.ProfileGeneric && task.Index == 2 && GetReadTime(task.Object) != DateTime.MinValue && IsSortedByDateTime(task.Object)) { //Read profile generic using range. DateTime now = DateTime.Now; now = now.AddSeconds(-now.Second); now = now.AddMinutes(-now.Minute); now = now.AddHours(1); val = reader.ReadRowsByRange((GXDLMSProfileGeneric)obj, task.Object.Attributes[GetBufferIndex(task.Object)].Read, now); } else { val = reader.Read(obj, task.Index); } if (val is Enum) { //Enum values are saved as interger. val = Convert.ToString(Convert.ToInt32(val)); } else if (val is byte[]) { DataType dt = (DataType)task.Object.Attributes[GetBufferIndex(task.Object)].UIDataType; if (dt == DataType.String) { val = ASCIIEncoding.ASCII.GetString((byte[])val); } else if (dt == DataType.StringUTF8) { val = ASCIIEncoding.UTF8.GetString((byte[])val); } else { val = GXCommon.ToHex((byte[])val); } } else if (val is GXDateTime) { val = ((GXDateTime)val).ToFormatString(); } if (obj.ObjectType == ObjectType.ProfileGeneric && task.Index == 2) { //Make own value from each row. if (val != null) { UInt64 attributeId = task.Object.Attributes[GetBufferIndex(task.Object)].Id; List<GXValue> list = new List<GXValue>(); DateTime latest = task.Object.Attributes[GetBufferIndex(task.Object)].Read; DateTime first = latest; Boolean read = false; int period = -1; foreach (GXStructure row in (GXArray)val) { DateTime dt = DateTime.MinValue; task.Data = GXDLMSTranslator.ValueToXml(row); for (int pos = 0; pos != row.Count; ++pos) { if (row[pos] is byte[]) { row[pos] = GXDLMSClient.ChangeType((byte[])row[pos], DataType.DateTime); if (pos == 0) { dt = ((GXDateTime)row[pos]).Value.LocalDateTime; //If we have already read this row. if (dt <= first) { read = true; break; } if (dt > latest) { latest = dt; } } } //Some meters are returning null as date time to save bytes... if (pos == 0 && row[pos] == null) { if (period == -1) { period = GetCapturePeriod(task.Object); if (period == -1) { throw new Exception("Invalid capture period."); } } row[pos] = latest.AddMinutes(period); } } if (_logger != null) { _logger.LogInformation("Read: " + task.Data); } if (!read) { list.Add(new GXValue() { Read = dt, Value = task.Data, AttributeId = attributeId }); } } if (list.Count != 0) { v = new AddValue() { Items = list.ToArray() }; response = client.PostAsJsonAsync(Startup.ServerAddress + "/api/value/AddValue", v).Result; Helpers.CheckStatus(response); ListDevicesResponse r = response.Content.ReadAsAsync<ListDevicesResponse>().Result; } } } else { if (!(val is string)) { val = Convert.ToString(val); } task.Data = (string)val; if (_logger != null) { _logger.LogInformation("Read: " + (string)val); } int index = GetAttributeIndex(task.Object, task.Index); if (index != -1) { UInt64 attributeId = task.Object.Attributes[index].Id; v = new AddValue() { Items = new GXValue[] {new GXValue(){ AttributeId = attributeId, Read = DateTime.Now, Value = (string)val} } }; response = client.PostAsJsonAsync(Startup.ServerAddress + "/api/value/AddValue", v).Result; Helpers.CheckStatus(response); AddValueResponse r = response.Content.ReadAsAsync<AddValueResponse>().Result; } else { if (_logger != null) { _logger.LogInformation("Invalid task index: " + task.Index); } } } }
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); } } }