public ServiceBusOptionSet() { Add<string>("ns=", "The service bus namespace", x => ServiceUri = ServiceBusEnvironment.CreateServiceUri("sb", x, "Benchmark")); Add<string>("keyname=", "The access key name", x => _keyName = x); Add<string>("key=", "The access key", x => _accessKey = x); Add<int>("connections=", "The number of connections to configure for the service point manager", x => DefaultConnections = x); _tokenTimeToLive = TimeSpan.FromDays(1); _tokenScope = TokenScope.Namespace; OperationTimeout = TimeSpan.FromSeconds(60.0); RetryMinBackoff = TimeSpan.FromMilliseconds(100.0); RetryMaxBackoff = TimeSpan.FromSeconds(20.0); RetryLimit = 10; TransportType = Microsoft.ServiceBus.Messaging.TransportType.Amqp; AmqpTransportSettings = new AmqpTransportSettings { BatchFlushInterval = TimeSpan.FromMilliseconds(3.0) }; NetMessagingTransportSettings = new NetMessagingTransportSettings { BatchFlushInterval = TimeSpan.FromMilliseconds(3.0) }; DefaultConnections = ServicePointManager.DefaultConnectionLimit; }
/// <summary> /// Initializes the ModuleClient and sets up the callback to receive /// messages containing temperature information /// </summary> static async Task Init() { AmqpTransportSettings amqpSetting = new AmqpTransportSettings(TransportType.Amqp_Tcp_Only); ITransportSettings[] settings = { amqpSetting }; // Open a connection to the Edge runtime ModuleClient ioTHubModuleClient = await ModuleClient.CreateFromEnvironmentAsync(settings); await ioTHubModuleClient.OpenAsync(); Console.WriteLine("IoT Hub module client initialized."); // Read the TemperatureThreshold value from the module twin's desired properties var moduleTwin = await ioTHubModuleClient.GetTwinAsync(); // Execute callback function during Init for Twin desired properties await OnDesiredPropertiesUpdate(moduleTwin.Properties.Desired, ioTHubModuleClient); // Attach a callback for updates to the module twin's desired properties. await ioTHubModuleClient.SetDesiredPropertyUpdateCallbackAsync(OnDesiredPropertiesUpdate, null); // Register a callback for messages that are received by the module. await ioTHubModuleClient.SetInputMessageHandlerAsync("input1", FilterMessages, ioTHubModuleClient); }
internal AmqpTransportHandler( IPipelineContext context, IotHubConnectionString connectionString, AmqpTransportSettings transportSettings, Action <object, EventArgs> onLinkClosedCallback, Func <MethodRequestInternal, Task> onMethodCallback = null) : base(context, transportSettings) { this.linkClosedListener = onLinkClosedCallback; TransportType transportType = transportSettings.GetTransportType(); this.deviceId = connectionString.DeviceId; switch (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(transportType)); } this.openTimeout = transportSettings.OpenTimeout; this.operationTimeout = transportSettings.OperationTimeout; this.prefetchCount = transportSettings.PrefetchCount; this.faultTolerantEventSendingLink = new Client.FaultTolerantAmqpObject <SendingAmqpLink>(this.CreateEventSendingLinkAsync, this.IotHubConnection.CloseLink); this.faultTolerantDeviceBoundReceivingLink = new Client.FaultTolerantAmqpObject <ReceivingAmqpLink>(this.CreateDeviceBoundReceivingLinkAsync, this.IotHubConnection.CloseLink); this.iotHubConnectionString = connectionString; this.messageListener = onMethodCallback; }
/// <summary> /// Initializes the ModuleClient and sets up the callback to receive /// messages containing temperature information /// </summary> static async void Init(CancellationToken token) { AmqpTransportSettings amqpSetting = new AmqpTransportSettings(TransportType.Amqp_Tcp_Only); ITransportSettings[] settings = { amqpSetting }; // Apre la connessione ModuleClient ioTHubModuleClient = await ModuleClient.CreateFromEnvironmentAsync(settings); await ioTHubModuleClient.OpenAsync(token); // Recupera la connessione allo storage Storage = Environment.GetEnvironmentVariable("STORAGE_CONNECTION_STRING"); Console.WriteLine($"Storage: {Storage}"); await ioTHubModuleClient.SetDesiredPropertyUpdateCallbackAsync(OnDesiredPropertyUpdate, null, token); Console.WriteLine("IoT Hub module client initialized."); while (!token.IsCancellationRequested) { await Task.Delay(5000, token); try { await SendPhoto(ioTHubModuleClient, token); } catch (Exception ex) when(!(ex is OperationCanceledException)) { Console.WriteLine(ex.ToString()); } } }
/// <summary> /// Initializes the ModuleClient and sets up the callback to receive /// messages containing temperature information /// </summary> static async Task Init() { AmqpTransportSettings amqpSetting = new AmqpTransportSettings(TransportType.Amqp_Tcp_Only); ITransportSettings[] settings = { amqpSetting }; // Open a connection to the Edge runtime ModuleClient ioTHubModuleClient = await ModuleClient.CreateFromEnvironmentAsync(settings); await ioTHubModuleClient.OpenAsync(); Console.WriteLine("IoT Hub module client initialized."); // Register callback to be called when a message is received by the module //await ioTHubModuleClient.SetInputMessageHandlerAsync("input1", PipeMessage, ioTHubModuleClient); // Read the TemperatureThreshold value from the module twin's desired properties var moduleTwin = await ioTHubModuleClient.GetTwinAsync(); var moduleTwinCollection = moduleTwin.Properties.Desired; try { temperatureThreshold = moduleTwinCollection["TemperatureThreshold"]; } catch (ArgumentOutOfRangeException e) { Console.WriteLine($"Property TemperatureThreshold not exist: {e.Message}"); } // Attach a callback for updates to the module twin's desired properties. await ioTHubModuleClient.SetDesiredPropertyUpdateCallbackAsync(OnDesiredPropertiesUpdate, null); // Register a callback for messages that are received by the module. await ioTHubModuleClient.SetInputMessageHandlerAsync("input1", FilterMessages, ioTHubModuleClient); }
/// <summary> /// Initializes the ModuleClient and sets up the callback to receive /// messages containing temperature information /// </summary> static async Task Init() { IConfiguration configuration = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("config/appsettings.json", optional: true) .AddEnvironmentVariables() .Build(); int delay = configuration.GetValue("Delay", 5000); AmqpTransportSettings amqpSetting = new AmqpTransportSettings(TransportType.Amqp_Tcp_Only); ITransportSettings[] settings = { amqpSetting }; // Open a connection to the Edge runtime ModuleClient ioTHubModuleClient = await ModuleClient.CreateFromEnvironmentAsync(settings); await ioTHubModuleClient.OpenAsync(); Console.WriteLine("IoT Hub module client initialized."); // Register callback to be called when a message is received by the module await ioTHubModuleClient.SetInputMessageHandlerAsync("input1", PipeMessage, ioTHubModuleClient); // Start sending messages await SendTempMessages(ioTHubModuleClient, delay); }
/// <summary> /// Initializes the ModuleClient and sets up the callback to receive /// messages containing temperature information /// </summary> static async Task Init() { AmqpTransportSettings amqpSetting = new AmqpTransportSettings(TransportType.Amqp_Tcp_Only); ITransportSettings[] settings = { amqpSetting }; // Open a connection to the Edge runtime ModuleClient ioTHubModuleClient = await ModuleClient.CreateFromEnvironmentAsync(settings); await ioTHubModuleClient.OpenAsync(); Console.WriteLine("IoT Hub module client initialized."); // The Edge runtime gives us the connection string we need -- it is injected as an environment variable string connectionString = Environment.GetEnvironmentVariable("EdgeHubConnectionString"); Console.WriteLine($"Using connection string: {connectionString ?? "n/a"}"); // try // { // serviceClient = Microsoft.Azure.Devices.ServiceClient.CreateFromConnectionString(connectionString); // } // catch (Exception ex) // { // Console.WriteLine($"Error creating service client: {ex.ToString()}"); // } // Register callback to be called when a message is received by the module await ioTHubModuleClient.SetInputMessageHandlerAsync("input1", PipeMessage, ioTHubModuleClient); }
/// <summary> /// Inicializa o ModuleClient e configura o retorno de chamada para receber /// mensagens contendo informações de temperatura /// </summary> static async Task Init() { AmqpTransportSettings amqpSetting = new AmqpTransportSettings(TransportType.Amqp_Tcp_Only); ITransportSettings[] settings = { amqpSetting }; // Abra uma conexão com o tempo de execução do Edge ModuleClient ioTHubModuleClient = await ModuleClient.CreateFromEnvironmentAsync(settings); await ioTHubModuleClient.OpenAsync(); Console.WriteLine("*** Cliente do módulo IoT Hub inicializado ***"); // Obtem os valores das *propriedades desejadas* do módulo gêmeo var moduleTwin = await ioTHubModuleClient.GetTwinAsync(); // Atribui *propriedades desejadas* ao método de tratamento await OnDesiredPropertiesUpdate(moduleTwin.Properties.Desired, ioTHubModuleClient); // Anexa método para tratar as *propriedades desejadas* do módulo gêmeo sempre que tiver atualizações. await ioTHubModuleClient.SetDesiredPropertyUpdateCallbackAsync(OnDesiredPropertiesUpdate, null); // Registra um método responsável por tratar as mensagens recebidas pelo módulo (filtrar e encaminhar). await ioTHubModuleClient.SetInputMessageHandlerAsync(_inputName, FilterMessages, ioTHubModuleClient); }
public AmqpIoTTransport(AmqpSettings amqpSettings, AmqpTransportSettings amqpTransportSettings, string hostName, bool disableServerCertificateValidation) { _amqpSettings = amqpSettings; _amqpTransportSettings = amqpTransportSettings; _hostName = hostName; _disableServerCertificateValidation = disableServerCertificateValidation; var tcpTransportSettings = new TcpTransportSettings() { Host = hostName, Port = AmqpConstants.DefaultSecurePort }; _tlsTransportSettings = new TlsTransportSettings(tcpTransportSettings) { TargetHost = hostName, Certificate = null, CertificateValidationCallback = _amqpTransportSettings.RemoteCertificateValidationCallback ?? OnRemoteCertificateValidation }; if (_amqpTransportSettings.ClientCertificate != null) { _tlsTransportSettings.Certificate = _amqpTransportSettings.ClientCertificate; } }
/// <summary> /// Initializes the ModuleClient and sets up the callback to receive /// messages containing temperature information /// </summary> static async Task Init() { AmqpTransportSettings amqpSetting = new AmqpTransportSettings(TransportType.Amqp_Tcp_Only); ITransportSettings[] settings = { amqpSetting }; // Open a connection to the Edge runtime ModuleClient ioTHubModuleClient = await ModuleClient.CreateFromEnvironmentAsync(settings); await ioTHubModuleClient.OpenAsync(); IoTHubModuleClient = ioTHubModuleClient as ModuleClient; Console.WriteLine("IoT Hub module client initialized."); // Register callback to be called when a message is received by the module //await ioTHubModuleClient.SetInputMessageHandlerAsync("input1", PipeMessage, ioTHubModuleClient); _temperature = new Garage(); _temperature.ReadTemperatureAsync(); _temperature.LedMatrixAsync(); //Receive IoTHub commands _receiveData = new ReceiveData(); _receiveData.ReceiveCommandsAsync(); }
private ITransportSettings GetTransportSettings() { ITransportSettings transportSettings; switch (this.deviceRunnerConfiguration.Protocol) { case "mqtt": transportSettings = new MqttTransportSettings(TransportType.Mqtt_Tcp_Only); break; default: { var amqp = new AmqpTransportSettings(TransportType.Amqp_Tcp_Only); if (this.deviceRunnerConfiguration.AmqpMultiplex) { amqp.AmqpConnectionPoolSettings = new AmqpConnectionPoolSettings() { Pooling = true, }; } transportSettings = amqp; break; } } return(transportSettings); }
/// <summary> /// Initializes the ModuleClient and sets up the callback to receive /// messages containing temperature information /// </summary> static async Task Init() { AmqpTransportSettings amqpSetting = new AmqpTransportSettings(TransportType.Amqp_Tcp_Only); ITransportSettings[] settings = { amqpSetting }; Console.WriteLine("ENV: " + JsonConvert.SerializeObject(Environment.GetEnvironmentVariables())); // Open a connection to the Edge runtime ModuleClient ioTHubModuleClient = await ModuleClient.CreateFromEnvironmentAsync(settings); await ioTHubModuleClient.OpenAsync(); Console.WriteLine("IoT Hub module client initialized."); var moduleTwin = await ioTHubModuleClient.GetTwinAsync(); Console.WriteLine("Init value: "); Console.WriteLine(JsonConvert.SerializeObject(moduleTwin)); var moduleTwinCollection = moduleTwin.Properties.Desired; try { Console.WriteLine("Props: " + JsonConvert.SerializeObject(moduleTwinCollection)); await OnDesiredPropertiesUpdate(moduleTwinCollection, ioTHubModuleClient); } catch (Exception e) { Console.WriteLine($"Property not exist: {e}"); } await ioTHubModuleClient.SetDesiredPropertyUpdateCallbackAsync(OnDesiredPropertiesUpdate, ioTHubModuleClient); runningThread = Task.Run(() => GenerateData(ioTHubModuleClient)); // Attach a callback for updates to the module twin's desired properties. //GenerateData(ioTHubModuleClient); // Register a callback for messages that are received by the module. //await ioTHubModuleClient.SetInputMessageHandlerAsync("input1", GenerateData, ioTHubModuleClient); }
/// <summary> /// Initializes the ModuleClient and sets up the callback to receive /// messages containing temperature information /// </summary> static async Task Init() { AmqpTransportSettings amqpSetting = new AmqpTransportSettings(TransportType.Amqp_Tcp_Only); ITransportSettings[] settings = { amqpSetting }; // Open a connection to the Edge runtime ModuleClient ioTHubModuleClient = await ModuleClient.CreateFromEnvironmentAsync(settings); await ioTHubModuleClient.OpenAsync(); Console.WriteLine("IoT Hub module client initialized."); // Register callback to be called when a message is received by the module await ioTHubModuleClient.SetInputMessageHandlerAsync("input1", PipeMessage, ioTHubModuleClient); // Register twin update notifications await ioTHubModuleClient.SetDesiredPropertyUpdateCallbackAsync(OnDesiredPropertyChanged, null).ConfigureAwait(false); // Get current Twin properties Twin twin = await ioTHubModuleClient.GetTwinAsync().ConfigureAwait(false); Console.WriteLine("Initial twin value received:"); Console.WriteLine($"{twin.ToJson()}"); }
/// <summary> /// Initializes the ModuleClient and sets up the callback to receive /// messages containing temperature information /// </summary> static async Task Init() { AmqpTransportSettings amqpSetting = new AmqpTransportSettings(TransportType.Amqp_Tcp_Only); ITransportSettings[] settings = { amqpSetting }; // Open a connection to the Edge runtime ModuleClient ioTHubModuleClient = await ModuleClient.CreateFromEnvironmentAsync(settings); await ioTHubModuleClient.OpenAsync(); Console.WriteLine("IoT Hub module client initialized."); var moduleTwin = await ioTHubModuleClient.GetTwinAsync(); var moduleTwinCollection = moduleTwin.Properties.Desired; desiredPropertiesData = new DesiredPropertiesData(moduleTwinCollection); // callback for updating desired properties through the portal or rest api await ioTHubModuleClient.SetDesiredPropertyUpdateCallbackAsync(OnDesiredPropertiesUpdate, null); // this direct method will allow to reset the temperature sensor values back to their initial state //await ioTHubModuleClient.SetMethodHandlerAsync("reset", ResetMethod, null); // Register callback to be called when a message is received by the module //await ioTHubModuleClient.SetInputMessageHandlerAsync("input1", PipeMessage, ioTHubModuleClient); // as this runs in a loop we don't await await SendSimulationData(ioTHubModuleClient); Console.WriteLine("Simulating data..."); }
public void ConnectionPoolSettingsTest_ZeroPoolSize() { var connectionPoolSettings = new AmqpConnectionPoolSettings(); connectionPoolSettings.MaxPoolSize = 0; var transportSetting = new AmqpTransportSettings(TransportType.Amqp, 200, connectionPoolSettings); }
internal AmqpTransportHandler( PipelineContext context, IotHubConnectionString connectionString, AmqpTransportSettings transportSettings, Func <MethodRequestInternal, Task> onMethodCallback = null, Action <TwinCollection> onDesiredStatePatchReceivedCallback = null, Func <string, Message, Task> onModuleMessageReceivedCallback = null, Func <Message, Task> onDeviceMessageReceivedCallback = null) : base(context, transportSettings) { _operationTimeout = transportSettings.OperationTimeout; _onDesiredStatePatchListener = onDesiredStatePatchReceivedCallback; IDeviceIdentity deviceIdentity = new DeviceIdentity(connectionString, transportSettings, context.ProductInfo, context.ClientOptions); _amqpUnit = AmqpUnitManager.GetInstance().CreateAmqpUnit( deviceIdentity, onMethodCallback, TwinMessageListener, onModuleMessageReceivedCallback, onDeviceMessageReceivedCallback, OnDisconnected); if (Logging.IsEnabled) { Logging.Associate(this, _amqpUnit, nameof(_amqpUnit)); } }
/// <summary> /// Initializes the ModuleClient and sets up the callback to receive /// messages containing temperature information /// </summary> static async Task Init() { AmqpTransportSettings amqpSetting = new AmqpTransportSettings(TransportType.Amqp_Tcp_Only); ITransportSettings[] settings = { amqpSetting }; // Open a connection to the Edge runtime ModuleClient ioTHubModuleClient = await ModuleClient.CreateFromEnvironmentAsync(settings); await ioTHubModuleClient.OpenAsync(); Console.WriteLine("IoT Hub module client initialized."); var moduleTwin = await ioTHubModuleClient.GetTwinAsync(); var moduleTwinCollection = moduleTwin.Properties.Desired; Console.WriteLine("Got Device Twin configuration."); desiredPropertiesData = new DesiredPropertiesData(moduleTwinCollection); // callback for updating desired properties through the portal or rest api await ioTHubModuleClient.SetDesiredPropertyUpdateCallbackAsync(OnDesiredPropertiesUpdate, null); await ioTHubModuleClient.SetMethodHandlerAsync("capture", CaptureMethod, ioTHubModuleClient); }
public async Task <IImmutableList <Gateway> > RegisterDevicesAsync() { var ids = await FindDevicesAsync(); var setting = new AmqpTransportSettings(Microsoft.Azure.Devices.Client.TransportType.Amqp_Tcp_Only) { AmqpConnectionPoolSettings = new AmqpConnectionPoolSettings() { Pooling = true }, IdleTimeout = TimeSpan.FromMinutes(60) }; var settings = new ITransportSettings[] { setting }; var gateways = from g in Enumerable.Range(0, _configuration.GatewayCount) let gatewayName = $"gate.{_leaserName}.{g}" let devices = from d in Enumerable.Range(0, _configuration.DevicePerGateway) let deviceId = ids[_configuration.DevicePerGateway * g + d] let client = DeviceClient.CreateFromConnectionString( _configuration.IotConnectionString, deviceId, settings) select new DeviceProxy(deviceId, client) select new Gateway(gatewayName, devices); return(gateways.ToImmutableArray()); }
/// <summary> /// Initializes the ModuleClient and sets up the callback to receive /// messages containing temperature information /// </summary> static async Task Init() { AmqpTransportSettings amqpSetting = new AmqpTransportSettings(TransportType.Amqp_Tcp_Only); ITransportSettings[] settings = { amqpSetting }; // Open a connection to the Edge runtime ModuleClient ioTHubModuleClient = await ModuleClient.CreateFromEnvironmentAsync(settings); await ioTHubModuleClient.OpenAsync(); Console.WriteLine("IoT Hub module Client initialized."); // Execute callback function during Init for Twin desired properties var twin = await ioTHubModuleClient.GetTwinAsync(); await onDesiredPropertiesUpdate(twin.Properties.Desired, ioTHubModuleClient); //Register the desired property callback await ioTHubModuleClient.SetDesiredPropertyUpdateCallbackAsync(onDesiredPropertiesUpdate, ioTHubModuleClient); //start the main thread that will do the real job of the module var thread = new Thread(() => mainThreadBody(ioTHubModuleClient)); thread.Start(); }
public async Task DeviceScopeMuxConnection_ConnectionIdleTimeoutTest() { // Arrange var amqpConnectionPoolSettings = new AmqpConnectionPoolSettings(); amqpConnectionPoolSettings.ConnectionIdleTimeout = TimeSpan.FromSeconds(5); var amqpTransportSettings = new AmqpTransportSettings(TransportType.Amqp_Tcp_Only, 200, amqpConnectionPoolSettings); string connectionString = "HostName=acme.azure-devices.net;DeviceId=device1;SharedAccessKey=CQN2K33r45/0WeIjpqmErV5EIvX8JZrozt3NEHCEkG8="; var iotHubConnectionString = IotHubConnectionStringBuilder.Create(connectionString).ToIotHubConnectionString(); var connectionCache = new Mock <IotHubConnectionCache>(); var connectionPool = new IotHubDeviceScopeConnectionPool(connectionCache.Object, iotHubConnectionString, amqpTransportSettings); // Act var connections = new IotHubDeviceMuxConnection[10]; // Create 10 Muxed Device Connections - these should hash into different mux connections for (int i = 0; i < 10; i++) { connections[i] = (IotHubDeviceMuxConnection)connectionPool.GetConnection(i.ToString()); } for (int j = 0; j < 10; j++) { connectionPool.RemoveDeviceFromConnection(connections[j], j.ToString()); } await Task.Delay(TimeSpan.FromSeconds(6)).ConfigureAwait(false); // Assert Assert.IsTrue(connectionPool.GetCount() == 0, "Did not cleanup all Connection objects"); }
public void TransportSettingsTest_ZeroOpenTimeout() { var amqpConnectionPoolSettings = new AmqpConnectionPoolSettings(); var transportSetting = new AmqpTransportSettings(TransportType.Amqp, 200, amqpConnectionPoolSettings); transportSetting.OpenTimeout = TimeSpan.Zero; }
static ITransportSettings[] GetAmqpTransportSettings(TransportType type, int connectionPoolSize, Option <IWebProxy> proxy, bool useServerHeartbeat, string authChain) { var settings = new AmqpTransportSettings(type) { AmqpConnectionPoolSettings = new AmqpConnectionPoolSettings { Pooling = true, MaxPoolSize = (uint)connectionPoolSize } }; if (useServerHeartbeat) { settings.IdleTimeout = HeartbeatTimeout; } proxy.ForEach(p => settings.Proxy = p); // Set the auth chain via Reflection settings.GetType() .GetProperty("AuthenticationChain", BindingFlags.NonPublic | BindingFlags.Instance) .SetValue(settings, authChain); return(new ITransportSettings[] { settings }); }
public void AmqpTransportSettings_UnderOpenTimeoutMin() { _ = new AmqpTransportSettings(TransportType.Amqp, 200, new AmqpConnectionPoolSettings()) { OpenTimeout = TimeSpan.Zero, }; }
/// <summary> /// Initializes the ModuleClient and sets up the callback to receive /// messages containing temperature information /// </summary> internal static async Task Init() { Logger.LoggingLevel = LogSeverity.Verbose; AmqpTransportSettings amqpSetting = new AmqpTransportSettings(TransportType.Amqp_Tcp_Only); ITransportSettings[] settings = { amqpSetting }; // Open a connection to the Edge runtime ModuleClient ioTHubModuleClient = await ModuleClient .CreateFromEnvironmentAsync(settings) .ConfigureAwait(false); await ioTHubModuleClient.OpenAsync().ConfigureAwait(false); Console.WriteLine("IoT Hub module client initialized."); // Register callbacks for messages to the module await ioTHubModuleClient .SetInputMessageHandlerAsync(EndpointNames.FromLeafDevice, LeafDeviceInputMessageHandler, ioTHubModuleClient) .ConfigureAwait(false); await ioTHubModuleClient .SetInputMessageHandlerAsync(EndpointNames.FromClassifier, ClassifierCallbackMessageHandler, ioTHubModuleClient) .ConfigureAwait(false); // Register a callback for updates to the module twin's desired properties. await ioTHubModuleClient .SetDesiredPropertyUpdateCallbackAsync(OnDesiredPropertiesUpdate, null) .ConfigureAwait(false); }
internal AmqpTransportHandler( IPipelineContext context, IotHubConnectionString connectionString, AmqpTransportSettings transportSettings, Func <MethodRequestInternal, Task> methodHandler = null, Action <TwinCollection> desiredPropertyListener = null, Func <string, Message, Task> eventListener = null) : base(context, transportSettings) { _operationTimeout = transportSettings.OperationTimeout; _desiredPropertyListener = desiredPropertyListener; DeviceIdentity deviceIdentity = new DeviceIdentity(connectionString, transportSettings, context.Get <ProductInfo>()); _amqpUnit = AmqpUnitManager.GetInstance().CreateAmqpUnit( deviceIdentity, methodHandler, TwinMessageListener, eventListener, OnDisconnected ); if (Logging.IsEnabled) { Logging.Associate(this, _amqpUnit, $"{nameof(_amqpUnit)}"); } }
public void TransportSettingsTest_TransportType_Amqp_WebSocket_Tcp() { var transportSetting = new AmqpTransportSettings(TransportType.Amqp_Tcp_Only, 200); Assert.IsTrue(transportSetting.GetTransportType() == TransportType.Amqp_Tcp_Only, "Should be TransportType.Amqp_Tcp_Only"); Assert.IsTrue(transportSetting.PrefetchCount == 200, "Should be value of 200"); }
public void ConnectionPoolSettingsTest_4SecsIdleTimeout() { var connectionPoolSettings = new AmqpConnectionPoolSettings(); connectionPoolSettings.ConnectionIdleTimeout = TimeSpan.FromSeconds(4); var transportSetting = new AmqpTransportSettings(TransportType.Amqp, 200, connectionPoolSettings); }
public void DeviceScopeMuxConnection_MaxDevicesPerConnectionTest() { // Arrange var amqpConnectionPoolSettings = new AmqpConnectionPoolSettings(); // Reduce poolsize to 1. This will mux all devices onto one connection amqpConnectionPoolSettings.MaxPoolSize = 1; var amqpTransportSettings = new AmqpTransportSettings(TransportType.Amqp_Tcp_Only, 200, amqpConnectionPoolSettings); string connectionString = "HostName=acme.azure-devices.net;DeviceId=device1;SharedAccessKey=CQN2K33r45/0WeIjpqmErV5EIvX8JZrozt3NEHCEkG8="; var iotHubConnectionString = IotHubConnectionStringBuilder.Create(connectionString).ToIotHubConnectionString(); var connectionCache = new Mock <IotHubConnectionCache>(); var connectionPool = new IotHubDeviceScopeConnectionPool(connectionCache.Object, iotHubConnectionString, amqpTransportSettings); // Act // Create 995 Muxed Device Connections for (int i = 0; i < AmqpConnectionPoolSettings.MaxDevicesPerConnection; i++) { connectionPool.GetConnection(iotHubConnectionString + "DeviceId=" + Guid.NewGuid().ToString()); } // try one more. This should throw invalid operation exception var connection = connectionPool.GetConnection(iotHubConnectionString + "DeviceId=" + Guid.NewGuid().ToString()); }
public void TransportSettingsTest_TransportType_Amqp_WebSocket() { var transportSetting = new AmqpTransportSettings(TransportType.Amqp_WebSocket_Only); Assert.IsTrue(transportSetting.GetTransportType() == TransportType.Amqp_WebSocket_Only, "Should be TransportType.Amqp_WebSocket_Only"); Assert.IsTrue(transportSetting.PrefetchCount == 50, "Should be default value of 50"); }
/// <summary> /// Initializes the ModuleClient and sets up the callback to receive /// messages containing temperature information /// </summary> static async Task Init() { // create client instance try{ MqttClient client = new MqttClient("localhost"); // register to message received client.MqttMsgPublishReceived += client_MqttMsgPublishReceived; string clientId = Guid.NewGuid().ToString(); client.Connect(clientId); // subscribe to the topic "/home/temperature" with QoS 2 client.Subscribe(new string[] { "/messages" }, new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE }); } catch (Exception ex) { Console.WriteLine("Cannot connect to MQTT broker"); Console.WriteLine("Exception: " + ex.Message + ex); } //init module client AmqpTransportSettings amqpSetting = new AmqpTransportSettings(TransportType.Amqp_Tcp_Only); ITransportSettings[] settings = { amqpSetting }; moduleClient = await ModuleClient.CreateFromEnvironmentAsync(settings); await moduleClient.OpenAsync(); }
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; }
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; }
public HostSettings(Uri serviceUri) { ServiceUri = serviceUri; OperationTimeout = TimeSpan.FromSeconds(60); RetryMinBackoff = TimeSpan.FromMilliseconds(100); RetryMaxBackoff = TimeSpan.FromSeconds(20); RetryLimit = 10; TransportType = TransportType.Amqp; AmqpTransportSettings = new AmqpTransportSettings() { BatchFlushInterval = TimeSpan.FromMilliseconds(50), }; NetMessagingTransportSettings = new NetMessagingTransportSettings() { BatchFlushInterval = TimeSpan.FromMilliseconds(50), }; }
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; }