/// <summary> /// Initialize default provider /// </summary> /// <param name="iothub"></param> public IoTHubProvider(string iothub) { _iothub = new IoTHubService(iothub); }
/// <summary> /// Makes a method request from a message /// </summary> /// <param name="message"></param> /// <param name="timeout"></param> /// <param name="ct"></param> /// <returns></returns> public async Task <Message> CallAsync(Message message, TimeSpan timeout, CancellationToken ct) { #if LOG_MESSAGES var sw = System.Diagnostics.Stopwatch.StartNew(); #endif #endif if (string.IsNullOrEmpty(message.DeviceId)) { throw ProxyEventSource.Log.ArgumentNull("deviceId"); } var buffer = new MemoryStream(); var request = MethodCallRequest.Create(message, timeout); request.Encode(buffer, CodecId.Json); var uri = new UriBuilder { Scheme = "https", Host = ConnectionString.HostName, Path = $"/twins/{WebUtility.UrlEncode(message.DeviceId)}/methods", Query = "api-version=" + IoTHubService._apiVersion }; MethodCallResponse response; try { var stream = await _http.StreamAsync(uri.Uri, Http.Post, async h => { h.Add(HttpRequestHeader.Authorization.ToString(), await IoTHubService.GetSasTokenAsync(ConnectionString, 3600).ConfigureAwait(false)); h.Add(HttpRequestHeader.UserAgent.ToString(), IoTHubService._clientId); }, (s, h) => { }, ct, Encoding.UTF8.GetString(buffer.ToArray()), "application/json").ConfigureAwait(false); using (stream) { response = Serializable.Decode <MethodCallResponse>(stream, CodecId.Json); } } catch (HttpResponseException hex) { ProxyEventSource.Log.HandledExceptionAsError(this, hex); if (hex.StatusCode == HttpStatusCode.NotFound) { throw new ProxyNotFound(hex); } if (hex.StatusCode == HttpStatusCode.Forbidden) { throw new ProxyPermission(hex); } if (hex.StatusCode == HttpStatusCode.GatewayTimeout) { throw new ProxyTimeout(hex.Message, hex); } throw new ProxyException( $"Remote proxy device method communication failure: {hex.StatusCode}.", hex); } catch (OperationCanceledException) { throw; } catch (Exception ex) { ProxyEventSource.Log.HandledExceptionAsError(this, ex); throw new ProxyException($"Unknown proxy failure.", ex); } #if LOG_MESSAGES finally { System.Diagnostics.Trace.TraceInformation( $" > {sw.Elapsed} < for InvokeDeviceMethodAsync({message})"); } #endif if (response.Status != 200) { throw ProxyEventSource.Log.Rethrow( new ProxyException($"Unexpected status {response.Status} returned by proxy.")); } return(response.Payload); }
/// <summary> /// Initialize default provider /// </summary> /// <param name="iothub"></param> public IoTHubProvider(ConnectionString iothub) { _iothub = new IoTHubService(iothub); }