static async Task <int> MainAsync() { Console.WriteLine($"[{DateTime.UtcNow.ToString("MM/dd/yyyy hh:mm:ss.fff tt", CultureInfo.InvariantCulture)}] Main()"); IConfiguration configuration = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("config/appsettings.json", optional: true) .AddEnvironmentVariables() .Build(); TimeSpan dmDelay = configuration.GetValue("DMDelay", TimeSpan.FromSeconds(5)); string targetModuleId = configuration.GetValue("TargetModuleId", "DirectMethodReceiver"); // Get deviced id of this device, exposed as a system variable by the iot edge runtime string targetDeviceId = configuration.GetValue <string>("IOTEDGE_DEVICEID"); TransportType transportType = configuration.GetValue("ClientTransportType", TransportType.Amqp_Tcp_Only); Console.WriteLine($"Using transport {transportType.ToString()}"); ModuleClient moduleClient = await InitModuleClient(transportType); (CancellationTokenSource cts, ManualResetEventSlim completed, Option <object> handler) = ShutdownHandler.Init(TimeSpan.FromSeconds(5), null); Console.WriteLine($"Target device Id = [{targetDeviceId}], Target module Id = [{targetModuleId}]"); await CallDirectMethod(moduleClient, dmDelay, targetDeviceId, targetModuleId, cts).ConfigureAwait(false); await moduleClient.CloseAsync(); completed.Set(); handler.ForEach(h => GC.KeepAlive(h)); return(0); }
static async Task <int> MainAsync() { Logger.LogInformation("DirectMethodSender Main() started."); IConfiguration configuration = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("config/appsettings.json", optional: true) .AddEnvironmentVariables() .Build(); TimeSpan dmDelay = configuration.GetValue("DirectMethodDelay", TimeSpan.FromSeconds(5)); // Get device id of this device, exposed as a system variable by the iot edge runtime string targetDeviceId = configuration.GetValue <string>("IOTEDGE_DEVICEID"); string targetModuleId = configuration.GetValue("TargetModuleId", "DirectMethodReceiver"); TransportType transportType = configuration.GetValue("ClientTransportType", TransportType.Amqp_Tcp_Only); ModuleClient moduleClient = await ModuleUtil.CreateModuleClientAsync( transportType, ModuleUtil.DefaultTimeoutErrorDetectionStrategy, ModuleUtil.DefaultTransientRetryStrategy, Logger); (CancellationTokenSource cts, ManualResetEventSlim completed, Option <object> handler) = ShutdownHandler.Init(TimeSpan.FromSeconds(5), Logger); await CallDirectMethod(moduleClient, dmDelay, targetDeviceId, targetModuleId, cts); await moduleClient.CloseAsync(); completed.Set(); handler.ForEach(h => GC.KeepAlive(h)); Logger.LogInformation("DirectMethodSender Main() finished."); return(0); }
static async Task Main(string[] args) { Logger.LogInformation($"Starting Relayer with the following settings: \r\n{Settings.Current}"); ModuleClient moduleClient = null; try { moduleClient = await ModuleUtil.CreateModuleClientAsync( Settings.Current.TransportType, ModuleUtil.DefaultTimeoutErrorDetectionStrategy, ModuleUtil.DefaultTransientRetryStrategy, Logger); (CancellationTokenSource cts, ManualResetEventSlim completed, Option <object> handler) = ShutdownHandler.Init(TimeSpan.FromSeconds(5), Logger); // Receive a message and call ProcessAndSendMessageAsync to send it on its way await moduleClient.SetInputMessageHandlerAsync(Settings.Current.InputName, ProcessAndSendMessageAsync, moduleClient); await cts.Token.WhenCanceled(); completed.Set(); handler.ForEach(h => GC.KeepAlive(h)); Logger.LogInformation("Relayer Main() finished."); } catch (Exception ex) { Logger.LogError(ex, "Error occurred during Relayer."); } finally { moduleClient?.CloseAsync(); moduleClient?.Dispose(); } }
static async Task Main() { Logger.LogInformation($"Starting load gen with the following settings:\r\n{Settings.Current}"); ModuleClient moduleClient = null; try { (CancellationTokenSource cts, ManualResetEventSlim completed, Option <object> handler) = ShutdownHandler.Init(TimeSpan.FromSeconds(5), Logger); Guid batchId = Guid.NewGuid(); Logger.LogInformation($"Batch Id={batchId}"); ClientOptions options = new ClientOptions(); Settings.Current.ModelId.ForEach(m => options.ModelId = m); moduleClient = await ModuleUtil.CreateModuleClientAsync( Settings.Current.TransportType, options, ModuleUtil.DefaultTimeoutErrorDetectionStrategy, ModuleUtil.DefaultTransientRetryStrategy, Logger); Logger.LogInformation($"Load gen delay start for {Settings.Current.TestStartDelay}."); await Task.Delay(Settings.Current.TestStartDelay); LoadGenSenderBase sender; switch (Settings.Current.SenderType) { case LoadGenSenderType.PriorityMessageSender: sender = new PriorityMessageSender(Logger, moduleClient, batchId, Settings.Current.TrackingId); break; case LoadGenSenderType.DefaultSender: default: sender = new DefaultMessageSender(Logger, moduleClient, batchId, Settings.Current.TrackingId); break; } DateTime testStartAt = DateTime.UtcNow; await sender.RunAsync(cts, testStartAt); Logger.LogInformation("Finish sending messages."); await cts.Token.WhenCanceled(); completed.Set(); handler.ForEach(h => GC.KeepAlive(h)); } catch (Exception ex) { Logger.LogError(ex, "Error occurred during load gen."); } finally { Logger.LogInformation("Closing connection to Edge Hub."); moduleClient?.CloseAsync(); moduleClient?.Dispose(); } Logger.LogInformation("Load Gen complete. Exiting."); }
static async Task Main() { Logger.LogInformation($"Starting load gen with the following settings:\r\n{Settings.Current}"); ModuleClient moduleClient = null; try { (CancellationTokenSource cts, ManualResetEventSlim completed, Option <object> handler) = ShutdownHandler.Init(TimeSpan.FromSeconds(5), Logger); Guid batchId = Guid.NewGuid(); Logger.LogInformation($"Batch Id={batchId}"); moduleClient = await ModuleUtil.CreateModuleClientAsync( Settings.Current.TransportType, ModuleUtil.DefaultTimeoutErrorDetectionStrategy, ModuleUtil.DefaultTransientRetryStrategy, Logger); Logger.LogInformation($"Load gen delay start for {Settings.Current.TestStartDelay}."); await Task.Delay(Settings.Current.TestStartDelay); DateTime testStartAt = DateTime.UtcNow; long messageIdCounter = 1; while (!cts.IsCancellationRequested && (Settings.Current.TestDuration == TimeSpan.Zero || DateTime.UtcNow - testStartAt < Settings.Current.TestDuration)) { try { await SendEventAsync(moduleClient, batchId, Settings.Current.TrackingId, messageIdCounter); messageIdCounter++; await Task.Delay(Settings.Current.MessageFrequency); if (messageIdCounter % 1000 == 0) { Logger.LogInformation($"Sent {messageIdCounter} messages."); } } catch (Exception ex) { Logger.LogError(ex, $"[SendEventAsync] Sequence number {messageIdCounter}, BatchId: {batchId.ToString()};"); } } Logger.LogInformation("Closing connection to Edge Hub."); await moduleClient.CloseAsync(); completed.Set(); handler.ForEach(h => GC.KeepAlive(h)); } catch (Exception ex) { Logger.LogError(ex, "Error occurred during load gen."); moduleClient?.Dispose(); } Logger.LogInformation("Load Gen complete. Exiting."); }
private async Task SendSingleMessageModule(TestDeviceType type, ITransportSettings[] transportSettings) { TestModule testModule = await TestModule.GetTestModuleAsync(DevicePrefix, ModulePrefix).ConfigureAwait(false); using (ModuleClient moduleClient = ModuleClient.CreateFromConnectionString(testModule.ConnectionString, transportSettings)) { await moduleClient.OpenAsync().ConfigureAwait(false); await SendSingleMessageModuleAndVerifyAsync(moduleClient, testModule.DeviceId).ConfigureAwait(false); await moduleClient.CloseAsync().ConfigureAwait(false); } }
static async Task Main() { Logger.LogInformation($"Starting load gen with the following settings:\r\n{Settings.Current}"); try { ModuleClient moduleClient = await ModuleUtil.CreateModuleClientAsync( Settings.Current.TransportType, ModuleUtil.DefaultTimeoutErrorDetectionStrategy, ModuleUtil.DefaultTransientRetryStrategy, Logger); using (var timers = new Timers()) { Guid batchId = Guid.NewGuid(); Logger.LogInformation($"Batch Id={batchId}"); // setup the message timer timers.Add( Settings.Current.MessageFrequency, Settings.Current.JitterFactor, () => GenerateMessageAsync(moduleClient, batchId)); // setup the twin update timer timers.Add( Settings.Current.TwinUpdateFrequency, Settings.Current.JitterFactor, () => GenerateTwinUpdateAsync(moduleClient, batchId)); timers.Start(); (CancellationTokenSource cts, ManualResetEventSlim completed, Option <object> handler) = ShutdownHandler.Init(TimeSpan.FromSeconds(5), Logger); Logger.LogInformation("Load gen running."); await cts.Token.WhenCanceled(); Logger.LogInformation("Stopping timers."); timers.Stop(); Logger.LogInformation("Closing connection to Edge Hub."); await moduleClient.CloseAsync(); completed.Set(); handler.ForEach(h => GC.KeepAlive(h)); Logger.LogInformation("Load Gen complete. Exiting."); } } catch (Exception ex) { Logger.LogError($"Error occurred during load gen.\r\n{ex}"); } }
private async Task TestSecurityMessageModule(Client.TransportType transport) { TestModule testModule = await TestModule.GetTestModuleAsync(_devicePrefix, _modulePrefix).ConfigureAwait(false); using (ModuleClient moduleClient = ModuleClient.CreateFromConnectionString(testModule.ConnectionString, transport)) { try { await SendSingleSecurityMessageModule(moduleClient, testModule.DeviceId, _logAnalyticsClient).ConfigureAwait(false); } finally { await moduleClient.CloseAsync().ConfigureAwait(false); } } }
private async Task SendSingleMessageModule(TestDeviceType type, ITransportSettings[] transportSettings) { TestModule testModule = await TestModule.GetTestModuleAsync(DevicePrefix, ModulePrefix).ConfigureAwait(false); using (ModuleClient moduleClient = ModuleClient.CreateFromConnectionString(testModule.ConnectionString, transportSettings)) { await moduleClient.OpenAsync().ConfigureAwait(false); string payload; string p1Value; Client.Message testMessage = ComposeD2CTestMessage(out payload, out p1Value); await moduleClient.SendEventAsync(testMessage).ConfigureAwait(false); await moduleClient.CloseAsync().ConfigureAwait(false); } }
public async Task StartAsync() { if (client != null) { await client.CloseAsync(); } #if DEBUG client = ModuleClient.CreateFromConnectionString(System.Environment.GetEnvironmentVariable("MODULE_CONNECTIONSTRING")); #else client = await ModuleClient.CreateFromEnvironmentAsync(); #endif await client.OpenAsync(); var moduleTwin = await client.GetTwinAsync(); await OnDesiredPropertiesUpdate(moduleTwin.Properties.Desired, client); await client.SetDesiredPropertyUpdateCallbackAsync(OnDesiredPropertiesUpdate, null); }
public static async Task <int> MainAsync() { Logger.LogInformation($"Starting DirectMethodSender with the following settings:\r\n{Settings.Current}"); try { ModuleClient moduleClient = await ModuleUtil.CreateModuleClientAsync( Settings.Current.TransportType, ModuleUtil.DefaultTimeoutErrorDetectionStrategy, ModuleUtil.DefaultTransientRetryStrategy, Logger); Uri analyzerUrl = Settings.Current.AnalyzerUrl; AnalyzerClient analyzerClient = new AnalyzerClient { BaseUrl = analyzerUrl.AbsoluteUri }; (CancellationTokenSource cts, ManualResetEventSlim completed, Option <object> handler) = ShutdownHandler.Init(TimeSpan.FromSeconds(5), Logger); await CallDirectMethod(moduleClient, analyzerClient, Settings.Current.DirectMethodDelay, cts); await moduleClient.CloseAsync(); await cts.Token.WhenCanceled(); completed.Set(); handler.ForEach(h => GC.KeepAlive(h)); Logger.LogInformation("DirectMethodSender Main() finished."); } catch (Exception e) { Logger.LogError(e, "Error occurred during direct method sender test setup"); } return(0); }
static async Task Main() { Microsoft.Extensions.Logging.ILogger logger = InitLogger().CreateLogger("loadgen"); Log.Information($"Starting load run with the following settings:\r\n{Settings.Current.ToString()}"); try { var retryPolicy = new RetryPolicy(TimeoutErrorDetectionStrategy, TransientRetryStrategy); retryPolicy.Retrying += (_, args) => { Log.Error($"Creating ModuleClient failed with exception {args.LastException}"); if (args.CurrentRetryCount < RetryCount) { Log.Information("Retrying..."); } }; ModuleClient client = await retryPolicy.ExecuteAsync(() => InitModuleClient(Settings.Current.TransportType)); using (var timers = new Timers()) { var random = new Random(); SHA256 sha = SHA256Managed.Create(); var bufferPool = new BufferPool(); // setup the message timer timers.Add( Settings.Current.MessageFrequency, Settings.Current.JitterFactor, () => GenMessage(client, random, sha, bufferPool)); // setup the twin update timer timers.Add( Settings.Current.TwinUpdateFrequency, Settings.Current.JitterFactor, () => GenTwinUpdate(client)); timers.Start(); ( CancellationTokenSource cts, ManualResetEventSlim completed, Option <object> handler ) = ShutdownHandler.Init(TimeSpan.FromSeconds(5), logger); Log.Information("Load gen running."); await cts.Token.WhenCanceled(); Log.Information("Stopping timers."); timers.Stop(); Log.Information("Closing connection to Edge Hub."); await client.CloseAsync(); completed.Set(); handler.ForEach(h => GC.KeepAlive(h)); Log.Information("Load run complete. Exiting."); } } catch (Exception ex) { Log.Error($"Error occurred during load run. \r\n{ex.ToString()}"); } }
static async Task CallDirectMethodFromCloud( string serviceClientConnectionString, string deviceId, string moduleId, TransportType transportType, TimeSpan delay, CancellationTokenSource cts) { Logger.LogInformation("CallDirectMethodFromCloud started."); ModuleClient moduleClient = null; ServiceClient serviceClient = null; try { Guid batchId = Guid.NewGuid(); int count = 1; IotHubConnectionStringBuilder iotHubConnectionStringBuilder = IotHubConnectionStringBuilder.Create(serviceClientConnectionString); Logger.LogInformation($"Prepare to call Direct Method from cloud ({iotHubConnectionStringBuilder.IotHubName}) on device [{deviceId}] module [{moduleId}]"); serviceClient = ServiceClient.CreateFromConnectionString(serviceClientConnectionString, Microsoft.Azure.Devices.TransportType.Amqp); var cloudToDeviceMethod = new CloudToDeviceMethod("HelloWorldMethod").SetPayloadJson("{ \"Message\": \"Hello\" }"); moduleClient = await ModuleUtil.CreateModuleClientAsync( transportType, ModuleUtil.DefaultTimeoutErrorDetectionStrategy, ModuleUtil.DefaultTransientRetryStrategy, Logger); while (!cts.Token.IsCancellationRequested) { Logger.LogInformation($"Calling Direct Method from cloud ({iotHubConnectionStringBuilder.IotHubName}) on device [{deviceId}] module [{moduleId}] of count {count}."); try { CloudToDeviceMethodResult result = await serviceClient.InvokeDeviceMethodAsync(deviceId, moduleId, cloudToDeviceMethod, CancellationToken.None); if (result.Status == (int)HttpStatusCode.OK) { var eventMessage = new Message(Encoding.UTF8.GetBytes($"Direct Method [{transportType}] Call succeeded.")); eventMessage.Properties.Add("sequenceNumber", count.ToString()); eventMessage.Properties.Add("batchId", batchId.ToString()); Logger.LogInformation($"Calling Direct Method from cloud with count {count} succeeded."); await moduleClient.SendEventAsync(RouteOutputName, eventMessage); } else { Logger.LogError($"Calling Direct Method from cloud with count {count} failed with status code {result.Status}."); } count++; } catch (Exception e) { Logger.LogError($"Exception caught with count {count}: {e}"); } await Task.Delay(delay, cts.Token); } } catch (Exception e) { Logger.LogError($"Exception caught: {e}"); throw; } finally { Logger.LogInformation("Close connection for service client and module client"); if (serviceClient != null) { await serviceClient.CloseAsync(); } if (moduleClient != null) { await moduleClient.CloseAsync(); } } Logger.LogInformation("CallDirectMethodFromCloud finished."); }
public async Task CloseAsync(CancellationToken cancellationToken) { await moduleClient.CloseAsync(cancellationToken); }
public async Task InvokeMethodOnModuleTest(ITransportSettings[] transportSettings) { // Arrange string iotHubConnectionString = await SecretsHelper.GetSecretFromConfigKey("iotHubConnStrKey"); string edgeDeviceConnectionString = await SecretsHelper.GetSecretFromConfigKey("edgeCapableDeviceConnStrKey"); IotHubConnectionStringBuilder connectionStringBuilder = IotHubConnectionStringBuilder.Create(edgeDeviceConnectionString); RegistryManager rm = RegistryManager.CreateFromConnectionString(edgeDeviceConnectionString); ModuleClient receiver = null; var request = new TestMethodRequest("Prop1", 10); var response = new TestMethodResponse("RespProp1", 20); TestMethodRequest receivedRequest = null; Task <MethodResponse> MethodHandler(MethodRequest methodRequest, object context) { receivedRequest = JsonConvert.DeserializeObject <TestMethodRequest>(methodRequest.DataAsJson); return(Task.FromResult(new MethodResponse( Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(response)), 200))); } try { string receiverModuleName = "receiver1"; ServiceClient sender = ServiceClient.CreateFromConnectionString(iotHubConnectionString); string receiverModuleConnectionString = await RegistryManagerHelper.CreateModuleIfNotExists(rm, connectionStringBuilder.HostName, connectionStringBuilder.DeviceId, receiverModuleName); receiver = ModuleClient.CreateFromConnectionString(receiverModuleConnectionString, transportSettings); await receiver.OpenAsync(); await receiver.SetMethodHandlerAsync("poke", MethodHandler, null); // Act CloudToDeviceMethodResult cloudToDeviceMethodResult = await sender.InvokeDeviceMethodAsync( connectionStringBuilder.DeviceId, receiverModuleName, new CloudToDeviceMethod("poke").SetPayloadJson(JsonConvert.SerializeObject(request))); // Assert Assert.NotNull(cloudToDeviceMethodResult); Assert.NotNull(receivedRequest); Assert.Equal(receivedRequest.RequestProp1, request.RequestProp1); Assert.Equal(receivedRequest.RequestProp2, request.RequestProp2); Assert.Equal(200, cloudToDeviceMethodResult.Status); var receivedResponse = JsonConvert.DeserializeObject <TestMethodResponse>(cloudToDeviceMethodResult.GetPayloadAsJson()); Assert.NotNull(receivedResponse); Assert.Equal(receivedResponse.ResponseProp1, response.ResponseProp1); Assert.Equal(receivedResponse.ResponseProp2, response.ResponseProp2); } finally { if (rm != null) { await rm.CloseAsync(); } if (receiver != null) { await receiver.CloseAsync(); } } // wait for the connection to be closed on the Edge side await Task.Delay(TimeSpan.FromSeconds(10)); }
public async Task RunSampleAsync(bool acceptDeviceStreamingRequest) { byte[] buffer = new byte[1024]; using (var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromMinutes(5))) { DeviceStreamRequest streamRequest = null; if (this._deviceClient != null) { streamRequest = await _deviceClient.WaitForDeviceStreamRequestAsync(cancellationTokenSource.Token).ConfigureAwait(false); } else if (this._moduleClient != null) { streamRequest = await _moduleClient.WaitForDeviceStreamRequestAsync(cancellationTokenSource.Token).ConfigureAwait(false); } if (streamRequest != null) { if (acceptDeviceStreamingRequest) { if (this._deviceClient != null) { await _deviceClient.AcceptDeviceStreamRequestAsync(streamRequest, cancellationTokenSource.Token).ConfigureAwait(false); } else if (this._moduleClient != null) { await _moduleClient.AcceptDeviceStreamRequestAsync(streamRequest, cancellationTokenSource.Token).ConfigureAwait(false); } using (ClientWebSocket webSocket = await DeviceStreamingCommon.GetStreamingClientAsync(streamRequest.Url, streamRequest.AuthorizationToken, cancellationTokenSource.Token).ConfigureAwait(false)) { WebSocketReceiveResult receiveResult = await webSocket.ReceiveAsync(new ArraySegment <byte>(buffer, 0, buffer.Length), cancellationTokenSource.Token).ConfigureAwait(false); Console.WriteLine("Received stream data: {0}", Encoding.UTF8.GetString(buffer, 0, receiveResult.Count)); await webSocket.SendAsync(new ArraySegment <byte>(buffer, 0, receiveResult.Count), WebSocketMessageType.Binary, true, cancellationTokenSource.Token).ConfigureAwait(false); Console.WriteLine("Sent stream data: {0}", Encoding.UTF8.GetString(buffer, 0, receiveResult.Count)); await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, String.Empty, cancellationTokenSource.Token).ConfigureAwait(false); } } else { if (this._deviceClient != null) { await _deviceClient.RejectDeviceStreamRequestAsync(streamRequest, cancellationTokenSource.Token).ConfigureAwait(false); } else if (this._moduleClient != null) { await _moduleClient.RejectDeviceStreamRequestAsync(streamRequest, cancellationTokenSource.Token).ConfigureAwait(false); } } } if (this._deviceClient != null) { await _deviceClient.CloseAsync().ConfigureAwait(false); } else if (this._moduleClient != null) { await _moduleClient.CloseAsync().ConfigureAwait(false); } } }
public async Task Terminate() { await moduleClient.CloseAsync(); }
private async Task SendMessageModuleMuxedOverAmqp( Client.TransportType transport, int poolSize, int devicesCount, bool useSameDevice = false) { var transportSettings = new ITransportSettings[] { new AmqpTransportSettings(transport) { AmqpConnectionPoolSettings = new AmqpConnectionPoolSettings() { MaxPoolSize = unchecked ((uint)poolSize), Pooling = true } } }; ICollection <ModuleClient> moduleClients = new List <ModuleClient>(); Dictionary <ModuleClient, int> moduleClientConnectionStatusChangeCount = new Dictionary <ModuleClient, int>(); try { _log.WriteLine($"{nameof(MessageSendE2EMultiplexingTests)}: Starting the test execution for {devicesCount} modules"); for (int i = 0; i < devicesCount; i++) { ConnectionStatus? lastConnectionStatus = null; ConnectionStatusChangeReason?lastConnectionStatusChangeReason = null; int setConnectionStatusChangesHandlerCount = 0; string devicePrefix = useSameDevice ? DevicePrefix : $"{DevicePrefix}_{i}_"; string modulePrefix = useSameDevice ? $"{ModulePrefix}_{i}_" : ModulePrefix; TestModule testModule = await TestModule.GetTestModuleAsync(devicePrefix, modulePrefix).ConfigureAwait(false); ModuleClient moduleClient = ModuleClient.CreateFromConnectionString(testModule.ConnectionString, transportSettings); moduleClients.Add(moduleClient); moduleClient.SetConnectionStatusChangesHandler((status, statusChangeReason) => { setConnectionStatusChangesHandlerCount++; lastConnectionStatus = status; lastConnectionStatusChangeReason = statusChangeReason; _log.WriteLine($"{nameof(MessageSendE2EMultiplexingTests)}.{nameof(ConnectionStatusChangesHandler)}: status={status} statusChangeReason={statusChangeReason} count={setConnectionStatusChangesHandlerCount}"); moduleClientConnectionStatusChangeCount[moduleClient] = setConnectionStatusChangesHandlerCount; }); _log.WriteLine($"{nameof(MessageSendE2EMultiplexingTests)}: Preparing to send message for module {i}"); await moduleClient.OpenAsync().ConfigureAwait(false); await MessageSend.SendSingleMessageModuleAndVerifyAsync(moduleClient, testModule.DeviceId).ConfigureAwait(false); } } finally { // Close and dispose all of the module client instances here foreach (ModuleClient moduleClient in moduleClients) { await moduleClient.CloseAsync().ConfigureAwait(false); // The connection status change count should be 2: connect (open) and disabled (close) Assert.IsTrue(moduleClientConnectionStatusChangeCount[moduleClient] == 2, $"Connection status change count for deviceClient {TestLogging.GetHashCode(moduleClient)} is {moduleClientConnectionStatusChangeCount[moduleClient]}"); _log.WriteLine($"{nameof(MessageSendE2EMultiplexingTests)}: Disposing moduleClient {TestLogging.GetHashCode(moduleClient)}"); moduleClient.Dispose(); } } }
public async Task CloseAsync() { await ModuleClient.CloseAsync(); Log.Information("Closed ModuleClient"); }
public async Task DisconnectAsync() { Log.Information("Disconnecting Edge Hub Client Connection"); await ModuleClient.CloseAsync(); }
public async Task InvokeMethodOnModuleTest(ITransportSettings[] transportSettings) { // Arrange string iotHubConnectionString = await SecretsHelper.GetSecretFromConfigKey("iotHubConnStrKey"); IotHubConnectionStringBuilder connectionStringBuilder = IotHubConnectionStringBuilder.Create(iotHubConnectionString); RegistryManager rm = RegistryManager.CreateFromConnectionString(iotHubConnectionString); ModuleClient receiver = null; string edgeDeviceConnectionString = ConfigHelper.TestConfig[EdgeHubConstants.ConfigKey.IotHubConnectionString]; Client.IotHubConnectionStringBuilder edgeHubConnectionStringBuilder = Client.IotHubConnectionStringBuilder.Create(edgeDeviceConnectionString); string edgeDeviceId = edgeHubConnectionStringBuilder.DeviceId; var request = new TestMethodRequest("Prop1", 10); var response = new TestMethodResponse("RespProp1", 20); TestMethodRequest receivedRequest = null; Task <MethodResponse> MethodHandler(MethodRequest methodRequest, object context) { receivedRequest = JsonConvert.DeserializeObject <TestMethodRequest>(methodRequest.DataAsJson); return(Task.FromResult( new MethodResponse( Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(response)), 200))); } string receiverModuleName = "method-module"; try { ServiceClient sender = ServiceClient.CreateFromConnectionString(iotHubConnectionString); string receiverModuleConnectionString = await RegistryManagerHelper.CreateModuleIfNotExists(rm, connectionStringBuilder.HostName, edgeDeviceId, receiverModuleName); receiver = ModuleClient.CreateFromConnectionString(receiverModuleConnectionString, transportSettings); await receiver.OpenAsync(); await receiver.SetMethodHandlerAsync("poke", MethodHandler, null); var waitStart = DateTime.Now; var isConnected = false; while (!isConnected && (DateTime.Now - waitStart) < TimeSpan.FromSeconds(30)) { var connectedDevice = await rm.GetModuleAsync(edgeDeviceId, receiverModuleName); isConnected = connectedDevice.ConnectionState == DeviceConnectionState.Connected; } Assert.True(isConnected); // Need longer sleep to ensure receiver is completely initialized await Task.Delay(TimeSpan.FromSeconds(10)); // Act CloudToDeviceMethodResult cloudToDeviceMethodResult = await sender.InvokeDeviceMethodAsync( edgeDeviceId, receiverModuleName, new CloudToDeviceMethod("poke").SetPayloadJson(JsonConvert.SerializeObject(request))); // Assert Assert.NotNull(cloudToDeviceMethodResult); Assert.NotNull(receivedRequest); Assert.Equal(receivedRequest.RequestProp1, request.RequestProp1); Assert.Equal(receivedRequest.RequestProp2, request.RequestProp2); Assert.Equal(200, cloudToDeviceMethodResult.Status); var receivedResponse = JsonConvert.DeserializeObject <TestMethodResponse>(cloudToDeviceMethodResult.GetPayloadAsJson()); Assert.NotNull(receivedResponse); Assert.Equal(receivedResponse.ResponseProp1, response.ResponseProp1); Assert.Equal(receivedResponse.ResponseProp2, response.ResponseProp2); } finally { await rm.CloseAsync(); if (receiver != null) { await receiver.CloseAsync(); } try { await RegistryManagerHelper.RemoveModule(edgeDeviceId, receiverModuleName, rm); } catch (Exception) { // ignored } } // wait for the connection to be closed on the Edge side await Task.Delay(TimeSpan.FromSeconds(10)); }
static async Task Main() { Logger.LogInformation($"Starting load gen with the following settings:\r\n{Settings.Current}"); ModuleClient moduleClient = null; try { (CancellationTokenSource cts, ManualResetEventSlim completed, Option <object> handler) = ShutdownHandler.Init(TimeSpan.FromSeconds(5), Logger); Guid batchId = Guid.NewGuid(); Logger.LogInformation($"Batch Id={batchId}"); moduleClient = await ModuleUtil.CreateModuleClientAsync( Settings.Current.TransportType, ModuleUtil.DefaultTimeoutErrorDetectionStrategy, ModuleUtil.DefaultTransientRetryStrategy, Logger); Logger.LogInformation($"Load gen delay start for {Settings.Current.TestStartDelay}."); await Task.Delay(Settings.Current.TestStartDelay); DateTime testStartAt = DateTime.UtcNow; long messageIdCounter = 1; while (!cts.IsCancellationRequested && (Settings.Current.TestDuration == TimeSpan.Zero || DateTime.UtcNow - testStartAt < Settings.Current.TestDuration)) { try { await SendEventAsync(moduleClient, batchId, Settings.Current.TrackingId, messageIdCounter); // Report sending message successfully to Test Result Coordinator await Settings.Current.TestResultCoordinatorUrl.ForEachAsync( async trcUrl => { Uri testResultCoordinatorUrl = new Uri( trcUrl, UriKind.Absolute); TestResultCoordinatorClient trcClient = new TestResultCoordinatorClient { BaseUrl = testResultCoordinatorUrl.AbsoluteUri }; await ModuleUtil.ReportStatus( trcClient, Logger, Settings.Current.ModuleId + ".send", ModuleUtil.FormatMessagesTestResultValue( Settings.Current.TrackingId, batchId.ToString(), messageIdCounter.ToString()), TestOperationResultType.Messages.ToString()); }); if (messageIdCounter % 1000 == 0) { Logger.LogInformation($"Sent {messageIdCounter} messages."); } await Task.Delay(Settings.Current.MessageFrequency); messageIdCounter++; } catch (Exception ex) { Logger.LogError(ex, $"[SendEventAsync] Sequence number {messageIdCounter}, BatchId: {batchId.ToString()};"); } } Logger.LogInformation("Finish sending messages."); await cts.Token.WhenCanceled(); completed.Set(); handler.ForEach(h => GC.KeepAlive(h)); } catch (Exception ex) { Logger.LogError(ex, "Error occurred during load gen."); } finally { Logger.LogInformation("Closing connection to Edge Hub."); moduleClient?.CloseAsync(); moduleClient?.Dispose(); } Logger.LogInformation("Load Gen complete. Exiting."); }
public async Task ModulesClient_InvokeMethodOnModule() { if (!this.IsAsync) { // TODO: Tim: The module client doesn't appear to open a connection to iothub or start // listening for method invocations when this test is run in Sync mode. Not sure why though. // calls to track 1 library don't throw, but seem to silently fail return; } string testDeviceId = $"InvokeMethodDevice{GetRandom()}"; string testModuleId = $"InvokeMethodModule{GetRandom()}"; DeviceIdentity device = null; ModuleIdentity module = null; ModuleClient moduleClient = null; IotHubServiceClient serviceClient = GetClient(); try { // Create a device to house the modules device = (await serviceClient.Devices .CreateOrUpdateIdentityAsync( new DeviceIdentity { DeviceId = testDeviceId }) .ConfigureAwait(false)) .Value; // Create the module on the device module = (await serviceClient.Modules.CreateOrUpdateIdentityAsync( new ModuleIdentity { DeviceId = testDeviceId, ModuleId = testModuleId }).ConfigureAwait(false)).Value; // Method expectations string expectedMethodName = "someMethodToInvoke"; int expectedStatus = 222; object expectedRequestPayload = null; // Create module client instance to receive the method invocation string moduleClientConnectionString = $"HostName={GetHostName()};DeviceId={testDeviceId};ModuleId={testModuleId};SharedAccessKey={module.Authentication.SymmetricKey.PrimaryKey}"; moduleClient = ModuleClient.CreateFromConnectionString(moduleClientConnectionString, TransportType.Mqtt_Tcp_Only); // These two methods are part of our track 1 device client. When the test fixture runs when isAsync = true, // these methods work. When isAsync = false, these methods silently don't work. await moduleClient.OpenAsync().ConfigureAwait(false); await moduleClient.SetMethodHandlerAsync( expectedMethodName, (methodRequest, userContext) => { return(Task.FromResult(new MethodResponse(expectedStatus))); }, null).ConfigureAwait(false); // Invoke the method on the module CloudToDeviceMethodRequest methodRequest = new CloudToDeviceMethodRequest() { MethodName = expectedMethodName, Payload = expectedRequestPayload, ConnectTimeoutInSeconds = 5, ResponseTimeoutInSeconds = 5 }; var methodResponse = (await serviceClient.Modules.InvokeMethodAsync(testDeviceId, testModuleId, methodRequest).ConfigureAwait(false)).Value; Assert.AreEqual(expectedStatus, methodResponse.Status); } finally { if (moduleClient != null) { await moduleClient.CloseAsync().ConfigureAwait(false); } await CleanupAsync(serviceClient, device).ConfigureAwait(false); } }
public async Task InvokeMethodOnModuleTest(ITransportSettings[] transportSettings) { // Arrange string deviceName = string.Format("moduleMethodTest-{0}", transportSettings.First().GetTransportType().ToString("g")); string iotHubConnectionString = await SecretsHelper.GetSecretFromConfigKey("iotHubConnStrKey"); IotHubConnectionStringBuilder connectionStringBuilder = IotHubConnectionStringBuilder.Create(iotHubConnectionString); RegistryManager rm = RegistryManager.CreateFromConnectionString(iotHubConnectionString); ModuleClient receiver = null; var request = new TestMethodRequest("Prop1", 10); var response = new TestMethodResponse("RespProp1", 20); TestMethodRequest receivedRequest = null; Task <MethodResponse> MethodHandler(MethodRequest methodRequest, object context) { receivedRequest = JsonConvert.DeserializeObject <TestMethodRequest>(methodRequest.DataAsJson); return(Task.FromResult( new MethodResponse( Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(response)), 200))); } string receiverModuleName = "method-module"; (string edgeDeviceId, string deviceConnStr) = await RegistryManagerHelper.CreateDevice(deviceName, iotHubConnectionString, rm, true, false); try { ServiceClient sender = ServiceClient.CreateFromConnectionString(iotHubConnectionString); string receiverModuleConnectionString = await RegistryManagerHelper.CreateModuleIfNotExists(rm, connectionStringBuilder.HostName, edgeDeviceId, receiverModuleName); receiver = ModuleClient.CreateFromConnectionString(receiverModuleConnectionString, transportSettings); await receiver.OpenAsync(); await receiver.SetMethodHandlerAsync("poke", MethodHandler, null); // Need longer sleep to ensure receiver is completely initialized await Task.Delay(TimeSpan.FromSeconds(10)); // Act CloudToDeviceMethodResult cloudToDeviceMethodResult = await sender.InvokeDeviceMethodAsync( edgeDeviceId, receiverModuleName, new CloudToDeviceMethod("poke").SetPayloadJson(JsonConvert.SerializeObject(request))); // Assert Assert.NotNull(cloudToDeviceMethodResult); Assert.NotNull(receivedRequest); Assert.Equal(receivedRequest.RequestProp1, request.RequestProp1); Assert.Equal(receivedRequest.RequestProp2, request.RequestProp2); Assert.Equal(200, cloudToDeviceMethodResult.Status); var receivedResponse = JsonConvert.DeserializeObject <TestMethodResponse>(cloudToDeviceMethodResult.GetPayloadAsJson()); Assert.NotNull(receivedResponse); Assert.Equal(receivedResponse.ResponseProp1, response.ResponseProp1); Assert.Equal(receivedResponse.ResponseProp2, response.ResponseProp2); } finally { if (rm != null) { await rm.CloseAsync(); } if (receiver != null) { await receiver.CloseAsync(); } try { await RegistryManagerHelper.RemoveDevice(edgeDeviceId, rm); } catch (Exception) { // ignored } } // wait for the connection to be closed on the Edge side await Task.Delay(TimeSpan.FromSeconds(10)); }