コード例 #1
0
 internal HttpTransportHandler(IotHubConnectionString iotHubConnectionString)
 {
     this.deviceId = iotHubConnectionString.DeviceId;
     this.httpClientHelper = new HttpClientHelper(
         iotHubConnectionString.HttpsEndpoint,
         iotHubConnectionString,
         ExceptionHandlingHelper.GetDefaultErrorMapping(),
         DefaultOperationTimeout,
         null);
 }
コード例 #2
0
 public AmqpTransportHandler(IotHubConnectionString connectionString, AmqpTransportSettings transportSettings)
 {
     this.IotHubConnection = connectionCache.GetConnection(connectionString, transportSettings);
     this.deviceId = connectionString.DeviceId;
     this.openTimeout = IotHubConnection.DefaultOpenTimeout;
     this.operationTimeout = IotHubConnection.DefaultOperationTimeout;
     this.DefaultReceiveTimeout = IotHubConnection.DefaultOperationTimeout;
     this.faultTolerantEventSendingLink = new Client.FaultTolerantAmqpObject<SendingAmqpLink>(this.CreateEventSendingLinkAsync, this.IotHubConnection.CloseLink);
     this.faultTolerantDeviceBoundReceivingLink = new Client.FaultTolerantAmqpObject<ReceivingAmqpLink>(this.CreateDeviceBoundReceivingLinkAsync, this.IotHubConnection.CloseLink);
     this.prefetchCount = transportSettings.PrefetchCount;
 }
コード例 #3
0
 internal HttpTransportHandler(IotHubConnectionString iotHubConnectionString, Http1TransportSettings transportSettings)
 {
     this.transportSettings = transportSettings;
     this.deviceId = iotHubConnectionString.DeviceId;
     this.httpClientHelper = new HttpClientHelper(
         iotHubConnectionString.HttpsEndpoint,
         iotHubConnectionString,
         ExceptionHandlingHelper.GetDefaultErrorMapping(),
         DefaultOperationTimeout,
         null,
         this.transportSettings.ClientCertificate);
 }
 public SasDeviceTokenAuthenticationHeaderProvider(IotHubConnectionString iotHubConnectionString)
 {
     if (iotHubConnectionString.CredentialScope == CredentialScope.Device
         && iotHubConnectionString.CredentialType == CredentialType.SharedAccessKey)
     {
         // Http Authorization header will not accept only a key as a value. It must have a prefix
         this.sasSignatureOrSharedAccessKey = SecurityConstants.SharedAccessKeyFullFieldName
                                              + iotHubConnectionString.GetPassword();
     }
     else
     {
         this.sasSignatureOrSharedAccessKey = iotHubConnectionString.GetPassword();
     }
     
 }
コード例 #5
0
 public MqttIotHubAdapter Create(
     Action onConnected, 
     Action<Message> onMessageReceived,
     Action<Exception> onError, 
     IotHubConnectionString iotHubConnectionString, 
     MqttTransportSettings mqttTransportSettings)
 {
     IWillMessage willMessage = mqttTransportSettings.HasWill ? this.settings.WillMessage : null;
     
     return new MqttIotHubAdapter(
         iotHubConnectionString.DeviceId,
         iotHubConnectionString.HostName,
         mqttTransportSettings.ClientCertificate != null ? null : iotHubConnectionString.GetPassword(),
         mqttTransportSettings,
         willMessage,
         onConnected,
         onMessageReceived,
         onError);
 }
コード例 #6
0
 public AmqpTransportHandler(IotHubConnectionString connectionString, AmqpTransportSettings transportSettings)
 {
     this.transportType = transportSettings.GetTransportType();
     switch (this.transportType)
     {
         case TransportType.Amqp_Tcp_Only:
             this.IotHubConnection = tcpConnectionCache.GetConnection(connectionString, transportSettings);
             break;
         case TransportType.Amqp_WebSocket_Only:
             this.IotHubConnection = wsConnectionCache.GetConnection(connectionString, transportSettings);
             break;
         default:
             throw new InvalidOperationException("Invalid Transport Type {0}".FormatInvariant(this.transportType));
     }
     
     this.deviceId = connectionString.DeviceId;
     this.openTimeout = IotHubConnection.DefaultOpenTimeout;
     this.operationTimeout = IotHubConnection.DefaultOperationTimeout;
     this.DefaultReceiveTimeout = IotHubConnection.DefaultOperationTimeout;
     this.faultTolerantEventSendingLink = new Client.FaultTolerantAmqpObject<SendingAmqpLink>(this.CreateEventSendingLinkAsync, this.IotHubConnection.CloseLink);
     this.faultTolerantDeviceBoundReceivingLink = new Client.FaultTolerantAmqpObject<ReceivingAmqpLink>(this.CreateDeviceBoundReceivingLinkAsync, this.IotHubConnection.CloseLink);
     this.prefetchCount = transportSettings.PrefetchCount;
 }
コード例 #7
0
        internal MqttTransportHandler(IotHubConnectionString iotHubConnectionString, MqttTransportSettings settings)
        {
            this.DefaultReceiveTimeout = DefaultReceiveTimeoutInSeconds;
            this.connectCompletion = new TaskCompletionSource();
            this.mqttIotHubAdapterFactory = new MqttIotHubAdapterFactory(settings);
            this.messageQueue = new ConcurrentQueue<Message>();
            this.completionQueue = new Queue<string>();
            this.serverAddress = Dns.GetHostEntry(iotHubConnectionString.HostName).AddressList[0];
            var group = new SingleInstanceEventLoopGroup();
            this.qos = settings.PublishToServerQoS;

            this.bootstrap = new Bootstrap()
                .Group(@group)
                .Channel<TcpSocketChannel>()
                .Option(ChannelOption.TcpNodelay, true)
                .Handler(new ActionChannelInitializer<ISocketChannel>(ch =>
                {
                    ch.Pipeline.AddLast(
                        TlsHandler.Client(iotHubConnectionString.HostName, null),
                        MqttEncoder.Instance,
                        new MqttDecoder(false, 256 * 1024),
                        this.mqttIotHubAdapterFactory.Create(
                            this.OnConnected,
                            this.OnMessageReceived,
                            this.OnError, 
                            iotHubConnectionString, 
                            settings));
                }));

            this.ScheduleCleanup(async () =>
            {
                this.connectCompletion.TrySetCanceled();
                await group.ShutdownGracefullyAsync();
            });

        }
コード例 #8
0
 internal HttpTransportHandler(IPipelineContext context, IotHubConnectionString iotHubConnectionString)
     : this(context, iotHubConnectionString, new Http1TransportSettings())
 {
 }
コード例 #9
0
 AmqpTransportHandler CreateFromConnectionString()
 {
     return(new AmqpTransportHandler(new PipelineContext(), IotHubConnectionString.Parse(DumpyConnectionString), new AmqpTransportSettings(TransportType.Amqp_Tcp_Only), (o, ea) => { }, (o, ea) => { }));
 }
コード例 #10
0
 internal MqttTransportHandler(IotHubConnectionString iotHubConnectionString, MqttTransportSettings settings, Func<IPAddress, int, Task<IChannel>> channelFactory)
     : base(settings)
 {
     this.mqttIotHubAdapterFactory = new MqttIotHubAdapterFactory(settings);
     this.messageQueue = new ConcurrentQueue<Message>();
     this.completionQueue = new Queue<string>();
     this.serverAddress = Dns.GetHostEntry(iotHubConnectionString.HostName).AddressList[0];
     this.qos = settings.PublishToServerQoS;
     this.eventLoopGroupKey = iotHubConnectionString.IotHubName + "#" + iotHubConnectionString.DeviceId + "#" + iotHubConnectionString.Audience;
     this.channelFactory = channelFactory ?? this.CreateChannelFactory(iotHubConnectionString, settings);
     this.closeRetryPolicy = new RetryPolicy(new TransientErrorIgnoreStrategy(), 5, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1));
 }
コード例 #11
0
        internal MqttTransportHandler(IotHubConnectionString iotHubConnectionString)
            : this(iotHubConnectionString, new MqttTransportSettings(TransportType.Mqtt))
        {

        }
コード例 #12
0
 internal MqttTransportHandler(IPipelineContext context, IotHubConnectionString iotHubConnectionString)
     : this(context, iotHubConnectionString, new MqttTransportSettings(TransportType.Mqtt_Tcp_Only))
 {
 }
コード例 #13
0
 public AmqpIoTCbsTokenProvider(IotHubConnectionString connectionString)
 {
     _connectionString = connectionString;
 }
コード例 #14
0
 internal MqttTransportHandler(IotHubConnectionString iotHubConnectionString)
     : this(iotHubConnectionString, new MqttTransportSettings(TransportType.Mqtt))
 {
 }
コード例 #15
0
 internal MqttTransportHandler(IotHubConnectionString iotHubConnectionString, MqttTransportSettings settings)
     : this(iotHubConnectionString, settings, null)
 {
 }
コード例 #16
0
 internal HttpTransportHandler(IotHubConnectionString iotHubConnectionString, Http1TransportSettings transportSettings)
     : this(iotHubConnectionString)
 {
     this.transportSettings = transportSettings;
 }
コード例 #17
0
        Func <IPAddress[], int, Task <IChannel> > CreateChannelFactory(IotHubConnectionString iotHubConnectionString, MqttTransportSettings settings, ProductInfo productInfo)
        {
            return(async(addresses, port) =>
            {
                IChannel channel = null;

                IEventLoopGroup eventLoopGroup = EventLoopGroupPool.TakeOrAdd(this.eventLoopGroupKey);

                Func <Stream, SslStream> streamFactory = stream => new SslStream(stream, true, settings.RemoteCertificateValidationCallback);
                var clientTlsSettings = settings.ClientCertificate != null ?
                                        new ClientTlsSettings(iotHubConnectionString.HostName, new List <X509Certificate> {
                    settings.ClientCertificate
                }) :
                                        new ClientTlsSettings(iotHubConnectionString.HostName);
                Bootstrap bootstrap = new Bootstrap()
                                      .Group(eventLoopGroup)
                                      .Channel <TcpSocketChannel>()
                                      .Option(ChannelOption.TcpNodelay, true)
                                      .Option(ChannelOption.Allocator, UnpooledByteBufferAllocator.Default)
                                      .Handler(new ActionChannelInitializer <ISocketChannel>(ch =>
                {
                    var tlsHandler = new TlsHandler(streamFactory, clientTlsSettings);

                    ch.Pipeline
                    .AddLast(
                        tlsHandler,
                        MqttEncoder.Instance,
                        new MqttDecoder(false, MaxMessageSize),
                        this.mqttIotHubAdapterFactory.Create(this, iotHubConnectionString, settings, productInfo));
                }));

                this.ScheduleCleanup(() =>
                {
                    EventLoopGroupPool.Release(this.eventLoopGroupKey);
                    return TaskConstants.Completed;
                });

                foreach (IPAddress address in addresses)
                {
                    try
                    {
                        Debug.WriteLine("Connecting to {0}.", address.ToString());
                        channel = await bootstrap.ConnectAsync(address, port).ConfigureAwait(false);

                        break;
                    }
                    catch (AggregateException ae)
                    {
                        ae.Handle((ex) =>
                        {
                            if (ex is ConnectException)     // We will handle DotNetty.Transport.Channels.ConnectException
                            {
                                Debug.WriteLine("ConnectException trying to connect to {0}: {1}", address.ToString(), ex.ToString());
                                return true;
                            }

                            return false; // Let anything else stop the application.
                        });
                    }
                }

                return channel;
            });
        }
コード例 #18
0
 HttpTransportHandler CreateFromConnectionString()
 {
     return(new HttpTransportHandler(new PipelineContext(), IotHubConnectionString.Parse(DumpyConnectionString), new Http1TransportSettings()));
 }
コード例 #19
0
        Func <IPAddress[], int, Task <IChannel> > CreateChannelFactory(IotHubConnectionString iotHubConnectionString, MqttTransportSettings settings, ProductInfo productInfo)
        {
            return(async(addresses, port) =>
            {
                IChannel channel = null;

                Func <Stream, SslStream> streamFactory = stream => new SslStream(stream, true, settings.RemoteCertificateValidationCallback);
                var clientTlsSettings = settings.ClientCertificate != null ?
                                        new ClientTlsSettings(iotHubConnectionString.HostName, new List <X509Certificate> {
                    settings.ClientCertificate
                }) :
                                        new ClientTlsSettings(iotHubConnectionString.HostName);
                Bootstrap bootstrap = new Bootstrap()
                                      .Group(s_eventLoopGroup.Value)
                                      .Channel <TcpSocketChannel>()
                                      .Option(ChannelOption.TcpNodelay, true)
                                      .Option(ChannelOption.Allocator, UnpooledByteBufferAllocator.Default)
                                      .Handler(new ActionChannelInitializer <ISocketChannel>(ch =>
                {
                    var tlsHandler = new TlsHandler(streamFactory, clientTlsSettings);

                    ch.Pipeline
                    .AddLast(
                        tlsHandler,
                        MqttEncoder.Instance,
                        new MqttDecoder(false, MaxMessageSize),
                        new LoggingHandler(LogLevel.DEBUG),
                        this.mqttIotHubAdapterFactory.Create(this, iotHubConnectionString, settings, productInfo));
                }));

                foreach (IPAddress address in addresses)
                {
                    try
                    {
                        if (Logging.IsEnabled)
                        {
                            Logging.Info(this, $"Connecting to {address.ToString()}", nameof(CreateChannelFactory));
                        }
                        channel = await bootstrap.ConnectAsync(address, port).ConfigureAwait(true);

                        break;
                    }
                    catch (AggregateException ae)
                    {
                        ae.Handle((ex) =>
                        {
                            if (ex is ConnectException)     // We will handle DotNetty.Transport.Channels.ConnectException
                            {
                                if (Logging.IsEnabled)
                                {
                                    Logging.Error(this, $"ConnectException trying to connect to {address.ToString()}: {ex.ToString()}", nameof(CreateChannelFactory));
                                }
                                return true;
                            }

                            return false; // Let anything else stop the application.
                        });
                    }
                }

                return channel;
            });
        }
コード例 #20
0
 internal MqttTransportHandler(IPipelineContext context, IotHubConnectionString iotHubConnectionString, MqttTransportSettings settings, Func <MethodRequestInternal, Task> onMethodCallback = null, Action <TwinCollection> onReportedStatePatchReceivedCallback = null)
     : this(context, iotHubConnectionString, settings, null)
 {
     this.messageListener = onMethodCallback;
     this.onReportedStatePatchListener = onReportedStatePatchReceivedCallback;
 }
コード例 #21
0
        Func <IPAddress[], int, Task <IChannel> > CreateWebSocketChannelFactory(IotHubConnectionString iotHubConnectionString, MqttTransportSettings settings, ProductInfo productInfo)
        {
            return(async(address, port) =>
            {
                string additionalQueryParams = "";
#if NETSTANDARD1_3
                // NETSTANDARD1_3 implementation doesn't set client certs, so we want to tell the IoT Hub to not ask for them
                additionalQueryParams = "?iothub-no-client-cert=true";
#endif

                var websocketUri = new Uri(WebSocketConstants.Scheme + iotHubConnectionString.HostName + ":" + WebSocketConstants.SecurePort + WebSocketConstants.UriSuffix + additionalQueryParams);
                var websocket = new ClientWebSocket();
                websocket.Options.AddSubProtocol(WebSocketConstants.SubProtocols.Mqtt);

                // Check if we're configured to use a proxy server
                IWebProxy webProxy = settings.Proxy;

                try
                {
                    if (webProxy != DefaultWebProxySettings.Instance)
                    {
                        // Configure proxy server
                        websocket.Options.Proxy = webProxy;
                        if (Logging.IsEnabled)
                        {
                            Logging.Info(this, $"{nameof(CreateWebSocketChannelFactory)} Setting ClientWebSocket.Options.Proxy");
                        }
                    }
                }
                catch (PlatformNotSupportedException)
                {
                    // .NET Core 2.0 doesn't support proxy. Ignore this setting.
                    if (Logging.IsEnabled)
                    {
                        Logging.Error(this, $"{nameof(CreateWebSocketChannelFactory)} PlatformNotSupportedException thrown as .NET Core 2.0 doesn't support proxy");
                    }
                }

                if (settings.ClientCertificate != null)
                {
                    websocket.Options.ClientCertificates.Add(settings.ClientCertificate);
                }

                using (var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromMinutes(1)))
                {
                    await websocket.ConnectAsync(websocketUri, cancellationTokenSource.Token).ConfigureAwait(true);
                }

                var clientChannel = new ClientWebSocketChannel(null, websocket);
                clientChannel
                .Option(ChannelOption.Allocator, UnpooledByteBufferAllocator.Default)
                .Option(ChannelOption.AutoRead, false)
                .Option(ChannelOption.RcvbufAllocator, new AdaptiveRecvByteBufAllocator())
                .Option(ChannelOption.MessageSizeEstimator, DefaultMessageSizeEstimator.Default)
                .Pipeline.AddLast(
                    MqttEncoder.Instance,
                    new MqttDecoder(false, MaxMessageSize),
                    new LoggingHandler(LogLevel.DEBUG),
                    this.mqttIotHubAdapterFactory.Create(this, iotHubConnectionString, settings, productInfo));

                await s_eventLoopGroup.Value.RegisterAsync(clientChannel).ConfigureAwait(false);

                return clientChannel;
            });
        }
コード例 #22
0
        Func <IPAddress, int, Task <IChannel> > CreateChannelFactory(IotHubConnectionString iotHubConnectionString, MqttTransportSettings settings)
        {
#if WINDOWS_UWP
            return(async(address, port) =>
            {
                PlatformProvider.Platform = new UWPPlatform();

                var eventLoopGroup = new MultithreadEventLoopGroup();

                var streamSocket = new StreamSocket();
                await streamSocket.ConnectAsync(new HostName(iotHubConnectionString.HostName), port.ToString(), SocketProtectionLevel.PlainSocket);

                streamSocket.Control.IgnorableServerCertificateErrors.Add(ChainValidationResult.Untrusted);
                await streamSocket.UpgradeToSslAsync(SocketProtectionLevel.Tls12, new HostName(iotHubConnectionString.HostName));

                var streamSocketChannel = new StreamSocketChannel(streamSocket);

                streamSocketChannel.Pipeline.AddLast(
                    MqttEncoder.Instance,
                    new MqttDecoder(false, MaxMessageSize),
                    this.mqttIotHubAdapterFactory.Create(this, iotHubConnectionString, settings));

                streamSocketChannel.Configuration.SetOption(ChannelOption.Allocator, UnpooledByteBufferAllocator.Default);

                await eventLoopGroup.GetNext().RegisterAsync(streamSocketChannel);

                this.ScheduleCleanup(() =>
                {
                    EventLoopGroupPool.Release(this.eventLoopGroupKey);
                    return TaskConstants.Completed;
                });

                return streamSocketChannel;
            });
#else
            return((address, port) =>
            {
                IEventLoopGroup eventLoopGroup = EventLoopGroupPool.TakeOrAdd(this.eventLoopGroupKey);

                Func <Stream, SslStream> streamFactory = stream => new SslStream(stream, true, settings.RemoteCertificateValidationCallback);
                var clientTlsSettings = settings.ClientCertificate != null ?
                                        new ClientTlsSettings(iotHubConnectionString.HostName, new List <X509Certificate> {
                    settings.ClientCertificate
                }) :
                                        new ClientTlsSettings(iotHubConnectionString.HostName);
                Bootstrap bootstrap = new Bootstrap()
                                      .Group(eventLoopGroup)
                                      .Channel <TcpSocketChannel>()
                                      .Option(ChannelOption.TcpNodelay, true)
                                      .Option(ChannelOption.Allocator, UnpooledByteBufferAllocator.Default)
                                      .Handler(new ActionChannelInitializer <ISocketChannel>(ch =>
                {
                    var tlsHandler = new TlsHandler(streamFactory, clientTlsSettings);

                    ch.Pipeline
                    .AddLast(
                        tlsHandler,
                        MqttEncoder.Instance,
                        new MqttDecoder(false, MaxMessageSize),
                        this.mqttIotHubAdapterFactory.Create(this, iotHubConnectionString, settings));
                }));

                this.ScheduleCleanup(() =>
                {
                    EventLoopGroupPool.Release(this.eventLoopGroupKey);
                    return TaskConstants.Completed;
                });

                return bootstrap.ConnectAsync(address, port);
            });
#endif
        }
コード例 #23
0
 internal HttpTransportHandler(IotHubConnectionString iotHubConnectionString)
     : this(iotHubConnectionString, new Http1TransportSettings())
 {
 }
コード例 #24
0
        Func <IPAddress, int, Task <IChannel> > CreateWebSocketChannelFactory(IotHubConnectionString iotHubConnectionString, MqttTransportSettings settings)
        {
            return(async(address, port) =>
            {
                var additionalQueryParams = "";
#if WINDOWS_UWP
                // UWP implementation doesn't set client certs, so we want to tell the IoT Hub to not ask for them
                additionalQueryParams = "?iothub-no-client-cert=true";
#endif

                IEventLoopGroup eventLoopGroup = EventLoopGroupPool.TakeOrAdd(this.eventLoopGroupKey);

                var websocketUri = new Uri(WebSocketConstants.Scheme + iotHubConnectionString.HostName + ":" + WebSocketConstants.SecurePort + WebSocketConstants.UriSuffix + additionalQueryParams);
                var websocket = new ClientWebSocket();
                websocket.Options.AddSubProtocol(WebSocketConstants.SubProtocols.Mqtt);

#if !WINDOWS_UWP // UWP does not support proxies
                // Check if we're configured to use a proxy server
                IWebProxy webProxy = WebRequest.DefaultWebProxy;
                Uri proxyAddress = webProxy?.GetProxy(websocketUri);
                if (!websocketUri.Equals(proxyAddress))
                {
                    // Configure proxy server
                    websocket.Options.Proxy = webProxy;
                }
#endif

                if (settings.ClientCertificate != null)
                {
                    websocket.Options.ClientCertificates.Add(settings.ClientCertificate);
                }
#if !WINDOWS_UWP && !NETSTANDARD1_3 // UseDefaultCredentials is not in UWP and NetStandard
                else
                {
                    websocket.Options.UseDefaultCredentials = true;
                }
#endif

                using (var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromMinutes(1)))
                {
                    await websocket.ConnectAsync(websocketUri, cancellationTokenSource.Token);
                }

#if WINDOWS_UWP
                PlatformProvider.Platform = new UWPPlatform();
#endif
                var clientChannel = new ClientWebSocketChannel(null, websocket);
                clientChannel
                .Option(ChannelOption.Allocator, UnpooledByteBufferAllocator.Default)
                .Option(ChannelOption.AutoRead, false)
                .Option(ChannelOption.RcvbufAllocator, new AdaptiveRecvByteBufAllocator())
                .Option(ChannelOption.MessageSizeEstimator, DefaultMessageSizeEstimator.Default)
                .Pipeline.AddLast(
                    MqttEncoder.Instance,
                    new MqttDecoder(false, MaxMessageSize),
                    this.mqttIotHubAdapterFactory.Create(this, iotHubConnectionString, settings));
                await eventLoopGroup.GetNext().RegisterAsync(clientChannel);

                this.ScheduleCleanup(() =>
                {
                    EventLoopGroupPool.Release(this.eventLoopGroupKey);
                    return TaskConstants.Completed;
                });

                return clientChannel;
            });
        }
コード例 #25
0
        Func<IPAddress, int, Task<IChannel>> CreateChannelFactory(IotHubConnectionString iotHubConnectionString, MqttTransportSettings settings)
        {
            return (address, port) =>
            {
                IEventLoopGroup eventLoopGroup = EventLoopGroupPool.TakeOrAdd(this.eventLoopGroupKey);

                Func<Stream, SslStream> streamFactory = stream => new SslStream(stream, true, settings.RemoteCertificateValidationCallback);
                ClientTlsSettings clientTlsSettings;
                clientTlsSettings = settings.ClientCertificate != null ? 
                    new ClientTlsSettings(iotHubConnectionString.HostName, new List<X509Certificate> { settings.ClientCertificate }) : 
                    new ClientTlsSettings(iotHubConnectionString.HostName);
                Bootstrap bootstrap = new Bootstrap()
                    .Group(eventLoopGroup)
                    .Channel<TcpSocketChannel>()
                    .Option(ChannelOption.TcpNodelay, true)
                    .Option(ChannelOption.Allocator, UnpooledByteBufferAllocator.Default)
                    .Handler(new ActionChannelInitializer<ISocketChannel>(ch =>
                    {
                        var tlsHandler = new TlsHandler(streamFactory, clientTlsSettings);

                        ch.Pipeline
                            .AddLast(
                                tlsHandler, 
                                MqttEncoder.Instance, 
                                new MqttDecoder(false, 256 * 1024), 
                                this.mqttIotHubAdapterFactory.Create(this.OnConnected, this.OnMessageReceived, this.OnError, iotHubConnectionString, settings));
                    }));

                this.ScheduleCleanup(() =>
                {
                    EventLoopGroupPool.Release(this.eventLoopGroupKey);
                    return TaskConstants.Completed;
                });

                return bootstrap.ConnectAsync(address, port);
            };
        }
コード例 #26
0
 internal HttpTransportHandler(IotHubConnectionString iotHubConnectionString, Http1TransportSettings transportSettings)
     :this(iotHubConnectionString)
 {
     this.transportSettings = transportSettings;
 }
コード例 #27
0
 internal MqttTransportHandler(IotHubConnectionString iotHubConnectionString, MqttTransportSettings settings)
     : this(iotHubConnectionString, settings, null)
 {
 }
コード例 #28
0
 internal HttpTransportHandler(IotHubConnectionString iotHubConnectionString)
     : this(iotHubConnectionString, new Http1TransportSettings())
 {
 }
コード例 #29
0
 MqttTransportHandler CreateFromConnectionString()
 {
     return(new MqttTransportHandler(new PipelineContext(), IotHubConnectionString.Parse(DumpyConnectionString), new MqttTransportSettings(Microsoft.Azure.Devices.Client.TransportType.Mqtt_Tcp_Only), (o, ea) => { }));
 }
コード例 #30
0
 internal MqttTransportHandler(IPipelineContext context, IotHubConnectionString iotHubConnectionString, MqttTransportSettings settings, Func <MethodRequestInternal, Task> onMethodCallback = null)
     : this(context, iotHubConnectionString, settings, null)
 {
     this.messageListener = onMethodCallback;
 }
コード例 #31
0
 public RoutingDelegatingHandler(TransportHandlerFactory transportHandlerFactory, IotHubConnectionString iotHubConnectionString, ITransportSettings[] transportSettings)
 {
     this.transportHandlerFactory = transportHandlerFactory;
     this.iotHubConnectionString = iotHubConnectionString;
     this.transportSettings = transportSettings;
 }
コード例 #32
0
        internal MqttTransportHandler(IotHubConnectionString iotHubConnectionString, MqttTransportSettings settings, Func<IPAddress, int, Task<IChannel>> channelFactory)
            : base(settings)
        {
            this.mqttIotHubAdapterFactory = new MqttIotHubAdapterFactory(settings);
            this.messageQueue = new ConcurrentQueue<Message>();
            this.completionQueue = new Queue<string>();
            this.serverAddress = Dns.GetHostEntry(iotHubConnectionString.HostName).AddressList[0];
            this.qos = settings.PublishToServerQoS;
            this.eventLoopGroupKey = iotHubConnectionString.IotHubName + "#" + iotHubConnectionString.DeviceId + "#" + iotHubConnectionString.Audience;

            if (channelFactory == null)
            {
                switch (settings.GetTransportType())
                {
                    case TransportType.Mqtt_Tcp_Only:
                        this.channelFactory = this.CreateChannelFactory(iotHubConnectionString, settings);
                        break;
                    case TransportType.Mqtt_WebSocket_Only:
                        this.channelFactory = this.CreateWebSocketChannelFactory(iotHubConnectionString, settings);
                        break;
                    default:
                        throw new InvalidOperationException("Unsupported Transport Setting {0}".FormatInvariant(settings.GetTransportType()));
                }
            }
            else
            {
                this.channelFactory = channelFactory;
            }

            this.closeRetryPolicy = new RetryPolicy(new TransientErrorIgnoreStrategy(), 5, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1));
        }
コード例 #33
0
 public RoutingDelegatingHandler(TransportHandlerFactory transportHandlerFactory, IotHubConnectionString iotHubConnectionString, ITransportSettings[] transportSettings)
 {
     this.transportHandlerFactory = transportHandlerFactory;
     this.iotHubConnectionString  = iotHubConnectionString;
     this.transportSettings       = transportSettings;
 }
コード例 #34
0
        private Func <IPAddress[], int, Task <IChannel> > CreateChannelFactory(IotHubConnectionString iotHubConnectionString, MqttTransportSettings settings, ProductInfo productInfo)
        {
            return(async(addresses, port) =>
            {
                IChannel channel = null;

                Func <Stream, SslStream> streamFactory = stream => new SslStream(stream, true, settings.RemoteCertificateValidationCallback);

                var certs = settings.ClientCertificate == null
                    ? new List <X509Certificate>(0)
                    : new List <X509Certificate> {
                    settings.ClientCertificate
                };

                SslProtocols protocols = TlsVersions.Instance.Preferred;
#if NET451
                // Requires hardcoding in NET451 otherwise yields error:
                //    Microsoft.Azure.Devices.Client.Exceptions.IotHubCommunicationException: Transient network error occurred, please retry.
                //    DotNetty.Transport.Channels.ClosedChannelException: I/O error occurred.
                if (settings.GetTransportType() == TransportType.Mqtt_Tcp_Only &&
                    protocols == SslProtocols.None)
                {
                    protocols = TlsVersions.Instance.MinimumTlsVersions;
                }
#endif

                var clientTlsSettings = new ClientTlsSettings(
                    protocols,
                    settings.CertificateRevocationCheck,
                    certs,
                    iotHubConnectionString.HostName);

                Bootstrap bootstrap = new Bootstrap()
                                      .Group(s_eventLoopGroup.Value)
                                      .Channel <TcpSocketChannel>()
                                      .Option(ChannelOption.TcpNodelay, true)
                                      .Option(ChannelOption.Allocator, UnpooledByteBufferAllocator.Default)
                                      .Handler(new ActionChannelInitializer <ISocketChannel>(ch =>
                {
                    var tlsHandler = new TlsHandler(streamFactory, clientTlsSettings);

                    ch.Pipeline
                    .AddLast(
                        tlsHandler,
                        MqttEncoder.Instance,
                        new MqttDecoder(false, MaxMessageSize),
                        new LoggingHandler(LogLevel.DEBUG),
                        this.mqttIotHubAdapterFactory.Create(this, iotHubConnectionString, settings, productInfo));
                }));

                foreach (IPAddress address in addresses)
                {
                    try
                    {
                        if (Logging.IsEnabled)
                        {
                            Logging.Info(this, $"Connecting to {address.ToString()}", nameof(CreateChannelFactory));
                        }
                        channel = await bootstrap.ConnectAsync(address, port).ConfigureAwait(true);

                        break;
                    }
                    catch (AggregateException ae)
                    {
                        ae.Handle((ex) =>
                        {
                            if (ex is ConnectException)     // We will handle DotNetty.Transport.Channels.ConnectException
                            {
                                if (Logging.IsEnabled)
                                {
                                    Logging.Error(this, $"ConnectException trying to connect to {address.ToString()}: {ex.ToString()}", nameof(CreateChannelFactory));
                                }
                                return true;
                            }

                            return false; // Let anything else stop the application.
                        });
                    }
                    catch (ConnectException ex)
                    {
                        //same as above, we will handle DotNetty.Transport.Channels.ConnectException
                        if (Logging.IsEnabled)
                        {
                            Logging.Error(this, $"ConnectException trying to connect to {address.ToString()}: {ex.ToString()}", nameof(CreateChannelFactory));
                        }
                    }
                }

                if (channel == null)
                {
                    throw new IotHubCommunicationException("MQTT channel open failed.");
                }
                return channel;
            });
        }
コード例 #35
0
 internal HttpTransportHandler(IotHubConnectionString iotHubConnectionString)
     : this(null, iotHubConnectionString)
 {
 }
コード例 #36
0
        Func<IPAddress, int, Task<IChannel>> CreateWebSocketChannelFactory(IotHubConnectionString iotHubConnectionString, MqttTransportSettings settings)
        {
            return async (address, port) =>
            {
                IEventLoopGroup eventLoopGroup = EventLoopGroupPool.TakeOrAdd(this.eventLoopGroupKey);

                var websocketUri = new Uri(WebSocketConstants.Scheme + iotHubConnectionString.HostName + ":" + WebSocketConstants.SecurePort + WebSocketConstants.UriSuffix);
                var websocket = new ClientWebSocket();
                websocket.Options.AddSubProtocol(WebSocketConstants.SubProtocols.Mqtt);

                // Check if we're configured to use a proxy server
                IWebProxy webProxy = WebRequest.DefaultWebProxy;
                Uri proxyAddress = webProxy?.GetProxy(websocketUri);
                if (!websocketUri.Equals(proxyAddress))
                {
                    // Configure proxy server
                    websocket.Options.Proxy = webProxy;
                }

                if (settings.ClientCertificate != null)
                {
                    websocket.Options.ClientCertificates.Add(settings.ClientCertificate);
                }
                else
                {
                    websocket.Options.UseDefaultCredentials = true;
                }

                using (var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromMinutes(1)))
                {
                    await websocket.ConnectAsync(websocketUri, cancellationTokenSource.Token);
                }

                var clientChannel = new ClientWebSocketChannel(null, websocket);
                clientChannel
                    .Option(ChannelOption.Allocator, UnpooledByteBufferAllocator.Default)
                    .Option(ChannelOption.AutoRead, false)
                    .Option(ChannelOption.RcvbufAllocator, new AdaptiveRecvByteBufAllocator())
                    .Option(ChannelOption.MessageSizeEstimator, DefaultMessageSizeEstimator.Default)
                    .Pipeline.AddLast(
                        MqttEncoder.Instance,
                        new MqttDecoder(false, MaxMessageSize),
                        this.mqttIotHubAdapterFactory.Create(this.OnConnected, this.OnMessageReceived, this.OnError, iotHubConnectionString, settings));
                await eventLoopGroup.GetNext().RegisterAsync(clientChannel);

                this.ScheduleCleanup(() =>
                {
                    EventLoopGroupPool.Release(this.eventLoopGroupKey);
                    return TaskConstants.Completed;
                });

                return clientChannel;
            };
        }