protected Task <TResp> DispatchRequestWithResponseAsync <TReq, TResp>(string address, int port, SonoffMethods method, string deviceId, TReq request) where TReq : class, new() where TResp : class, new() { return(DispatchRequestWithResponseAsync <TReq, TResp>(address, port, method, deviceId, request, true)); }
protected async Task <TResp> DispatchRequestWithResponseAsync <TReq, TResp>(string address, int port, SonoffMethods method, string deviceId, TReq request, bool handleReturnValue) where TReq : class, new() where TResp : class, new() { var methodUrl = method.GetDescription(); var url = string.Format(methodUrl, address, port); using (var message = new HttpRequestMessage()) { message.RequestUri = new Uri(url); message.Method = HttpMethod.Post; var requestObject = new DeviceRequest <TReq> { DeviceId = deviceId, Data = request }; var requestContent = JsonConvert.SerializeObject(requestObject); message.Content = new StringContent(requestContent, Encoding.UTF8, "application/json"); try { using (var response = await _client.SendAsync(message, HttpCompletionOption.ResponseContentRead).ConfigureAwait(false)) { if (!response.IsSuccessStatusCode) { throw new Exception($"Status Code = {response.StatusCode}. Requires custom exception"); } if (!handleReturnValue) { return(null); } var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false); var stringObject = JsonConvert.DeserializeObject <DeviceResponse <string> >(content); var data = JsonConvert.DeserializeObject <TResp>(stringObject.Data); return(data); } } catch (TaskCanceledException) { throw new TimeoutException($"Timeout getting response from {url}, client timeout is set to {_client.Timeout}."); } } }
protected Task DispatchRequestAsync <TReq>(string address, int port, SonoffMethods method, string deviceId, TReq request) where TReq : class, new() { return(DispatchRequestWithResponseAsync <TReq, EmptyData>(address, port, method, deviceId, request, false)); }