// [InlineData(TransportType.Mqtt_WebSocket_Only)] // Disabled: need a valid server cert for WebSocket to work public async void Receive_C2D_SingleMessage_ShouldSucceed(TransportType transportType) { // Arrange string iotHubConnectionString = await SecretsHelper.GetSecretFromConfigKey("iotHubConnStrKey"); RegistryManager rm = RegistryManager.CreateFromConnectionString(iotHubConnectionString); (string deviceName, string deviceConnectionString) = await RegistryManagerHelper.CreateDevice(DeviceNamePrefix, iotHubConnectionString, rm); ServiceClient serviceClient = null; DeviceClient deviceClient = null; try { serviceClient = ServiceClient.CreateFromConnectionString(iotHubConnectionString); await serviceClient.OpenAsync(); ITransportSettings[] settings = this.GetTransportSettings(transportType); deviceClient = DeviceClient.CreateFromConnectionString(deviceConnectionString, settings); // Dummy ReceiveAsync to ensure mqtt subscription registration before SendAsync() is called on service client. await deviceClient.ReceiveAsync(TimeSpan.FromSeconds(2)); // Act Message message = this.CreateMessage(out string payload); await serviceClient.SendAsync(deviceName, message); // Assert await this.VerifyReceivedC2DMessage(deviceClient, payload, message.Properties[MessagePropertyName]); } finally { await this.Cleanup(deviceClient, serviceClient, rm, deviceName); } }
public async void Receive_C2D_SingleMessage_AfterOfflineMessage_ShouldSucceed() { // Arrange string iotHubConnectionString = await SecretsHelper.GetSecretFromConfigKey("iotHubConnStrKey"); string edgeDeviceId = ConnectionStringHelper.GetDeviceId(ConfigHelper.TestConfig[Service.Constants.ConfigKey.IotHubConnectionString]); RegistryManager rm = RegistryManager.CreateFromConnectionString(iotHubConnectionString); var edgeDevice = await rm.GetDeviceAsync(edgeDeviceId); (string deviceName, string deviceConnectionString) = await RegistryManagerHelper.CreateDevice(DeviceNamePrefix, iotHubConnectionString, rm, scope : edgeDevice.Scope); ServiceClient serviceClient = null; DeviceClient deviceClient = null; try { serviceClient = ServiceClient.CreateFromConnectionString(iotHubConnectionString); await serviceClient.OpenAsync(); ITransportSettings[] settings = this.GetTransportSettings(); deviceClient = DeviceClient.CreateFromConnectionString(deviceConnectionString, settings); // Dummy ReceiveAsync to ensure mqtt subscription registration before SendAsync() is called on service client. await deviceClient.ReceiveAsync(TimeSpan.FromSeconds(1)); var device = await rm.GetDeviceAsync(deviceName); // Wait for device to be connected to cloud await this.WaitForDeviceConnectionStateTimeoutAfter(rm, deviceName, DeviceConnectionState.Connected, TimeSpan.FromSeconds(60)); await deviceClient.CloseAsync(); // Wait for the connection to be closed on the Edge side by checking device connection state await this.WaitForDeviceConnectionStateTimeoutAfter(rm, deviceName, DeviceConnectionState.Disconnected, TimeSpan.FromSeconds(60)); // Act // Send message before device is listening Message message = this.CreateMessage(out string payload); await serviceClient.SendAsync(deviceName, message); deviceClient = DeviceClient.CreateFromConnectionString(deviceConnectionString, settings); // Assert await this.VerifyReceivedC2DMessage(deviceClient, payload, message.Properties[MessagePropertyName]); // Act // send new message after offline was received message = this.CreateMessage(out payload); await serviceClient.SendAsync(deviceName, message); // Assert await this.VerifyReceivedC2DMessage(deviceClient, payload, message.Properties[MessagePropertyName]); } finally { await this.Cleanup(deviceClient, serviceClient, rm, deviceName); } }
async Task SendCommandAsync(string iotHubConnectionString) { ServiceClient serviceClient = ServiceClient.CreateFromConnectionString(iotHubConnectionString); string qosPropertyName = ConfigurationManager.AppSettings["QoSPropertyName"]; var qos2Notification = new Message(Encoding.UTF8.GetBytes(MethodContent)); qos2Notification.Properties[qosPropertyName] = "2"; qos2Notification.Properties["subTopic"] = "critical-alert"; await serviceClient.SendAsync(this.deviceId, qos2Notification); }
Message CreateMessage(out string payload) { payload = Guid.NewGuid().ToString(); string messageId = Guid.NewGuid().ToString(); string property1Value = Guid.NewGuid().ToString(); var message = new Message(Encoding.UTF8.GetBytes(payload)) { MessageId = messageId, Properties = { [MessagePropertyName] = property1Value } }; return(message); }
public static async void Run([BlobTrigger("c2d-messages/{name}", Connection = "CONNECTION_STORAGE")] Stream myBlob, string name, ILogger log) { log.LogInformation($"C# Blob trigger function Processed blob\n Name:{name} \n Size: {myBlob.Length} Bytes"); var iothubConnectionString = System.Environment.GetEnvironmentVariable("AZURE_IOT_HUB_CONNECTION_STRING_SERVICE", EnvironmentVariableTarget.Process); if (name.EndsWith(".json")) { var receivedBlobNames = name.Split('-'); if (receivedBlobNames.Length > 0) { var targetDevice = receivedBlobNames[0]; for (int i = 1; i < receivedBlobNames.Length - 1; i++) { targetDevice += "-"; targetDevice += receivedBlobNames[i]; } var serviceClient = Microsoft.Azure.Devices.ServiceClient.CreateFromConnectionString(iothubConnectionString); await serviceClient.OpenAsync(); var methodInvocation = new Microsoft.Azure.Devices.CloudToDeviceMethod("sensehat-display.ShowText"); var reader = new System.IO.StreamReader(myBlob); var jsonMessage = reader.ReadToEnd(); methodInvocation.SetPayloadJson(jsonMessage); #if (USE_C2D_MESSAGE) var c2dMessage = new Microsoft.Azure.Devices.Message(myBlob); log.LogInformation($"Send received via blob to {targetDevice}"); await serviceClient.SendAsync(targetDevice, c2dMessage); #endif #if (USE_DEVICE_METHOD) log.LogInformation($"Invoke method via blob to {targetDevice}"); var invocationResult = await serviceClient.InvokeDeviceMethodAsync(targetDevice, methodInvocation); var invokedStatus = invocationResult.Status; var invokedPayload = invocationResult.GetPayloadAsJson(); log.LogInformation($"Invocation Result - {invokedStatus}:{invokedPayload}"); #endif await serviceClient.CloseAsync(); } } }
public async void Receive_C2D_NotSubscribed_OfflineSingleMessage_ShouldThrow() { // Arrange string iotHubConnectionString = await SecretsHelper.GetSecretFromConfigKey("iotHubConnStrKey"); string edgeDeviceId = ConnectionStringHelper.GetDeviceId(ConfigHelper.TestConfig[Service.Constants.ConfigKey.IotHubConnectionString]); RegistryManager rm = RegistryManager.CreateFromConnectionString(iotHubConnectionString); var edgeDevice = await rm.GetDeviceAsync(edgeDeviceId); (string deviceName, string deviceConnectionString) = await RegistryManagerHelper.CreateDevice(DeviceNamePrefix, iotHubConnectionString, rm, scope : edgeDevice.Scope); ServiceClient serviceClient = null; DeviceClient deviceClient = null; try { serviceClient = ServiceClient.CreateFromConnectionString(iotHubConnectionString); await serviceClient.OpenAsync(); // Act // Send message before device is listening Message message = this.CreateMessage(out string payload); await serviceClient.SendAsync(deviceName, message); // Wait to make sure message is not received because of ClockSkewAdjustment await Task.Delay(ClockSkewAdjustment); ITransportSettings[] settings = this.GetTransportSettings(); deviceClient = DeviceClient.CreateFromConnectionString(deviceConnectionString, settings); await deviceClient.OpenAsync(); // Assert await Assert.ThrowsAsync <TimeoutException>(() => this.VerifyReceivedC2DMessage(deviceClient, payload, message.Properties[MessagePropertyName])); } finally { await this.Cleanup(deviceClient, serviceClient, rm, deviceName); } }
public async Task BasicFunctionalityTest() { await this.EnsureServerInitializedAsync(); int protocolGatewayPort = this.ProtocolGatewayPort; string iotHubConnectionString = ConfigurationManager.AppSettings["IotHubClient.ConnectionString"]; IotHubConnectionStringBuilder hubConnectionStringBuilder = IotHubConnectionStringBuilder.Create(iotHubConnectionString); bool deviceNameProvided; this.deviceId = ConfigurationManager.AppSettings["End2End.DeviceName"]; if (!string.IsNullOrEmpty(this.deviceId)) { deviceNameProvided = true; } else { deviceNameProvided = false; this.deviceId = Guid.NewGuid().ToString("N"); } RegistryManager registryManager = RegistryManager.CreateFromConnectionString(iotHubConnectionString); if (!deviceNameProvided) { await registryManager.AddDeviceAsync(new Device(this.deviceId)); this.ScheduleCleanup(async () => { await registryManager.RemoveDeviceAsync(this.deviceId); await registryManager.CloseAsync(); }); } Device device = await registryManager.GetDeviceAsync(this.deviceId); this.deviceSas = new SharedAccessSignatureBuilder { Key = device.Authentication.SymmetricKey.PrimaryKey, Target = $"{hubConnectionStringBuilder.HostName}/devices/{this.deviceId}", KeyName = null, TimeToLive = TimeSpan.FromMinutes(20) } .ToSignature(); EventHubClient eventHubClient = EventHubClient.CreateFromConnectionString(iotHubConnectionString, "messages/events"); EventHubConsumerGroup ehGroup = eventHubClient.GetDefaultConsumerGroup(); string[] partitionIds = (await eventHubClient.GetRuntimeInformationAsync()).PartitionIds; EventHubReceiver[] receivers = await Task.WhenAll(partitionIds.Select(pid => ehGroup.CreateReceiverAsync(pid.Trim(), DateTime.UtcNow))); ServiceClient serviceClient = ServiceClient.CreateFromConnectionString(iotHubConnectionString); Stopwatch sw = Stopwatch.StartNew(); await this.CleanupDeviceQueueAsync(hubConnectionStringBuilder.HostName, device); var clientScenarios = new ClientScenarios(hubConnectionStringBuilder.HostName, this.deviceId, this.deviceSas); var group = new MultithreadEventLoopGroup(); string targetHost = this.tlsCertificate.GetNameInfo(X509NameType.DnsName, false); var readHandler1 = new ReadListeningHandler(CommunicationTimeout); Bootstrap bootstrap = new Bootstrap() .Group(group) .Channel<TcpSocketChannel>() .Option(ChannelOption.TcpNodelay, true) .Handler(this.ComposeClientChannelInitializer(targetHost, readHandler1)); IChannel clientChannel = await bootstrap.ConnectAsync(this.ServerAddress, protocolGatewayPort); this.ScheduleCleanup(() => clientChannel.CloseAsync()); Task testWorkTask = Task.Run(async () => { Tuple<EventData, string>[] ehMessages = await CollectEventHubMessagesAsync(receivers, 2); Tuple<EventData, string> qos0Event = Assert.Single(ehMessages.Where(x => TelemetryQoS0Content.Equals(x.Item2, StringComparison.Ordinal))); Tuple<EventData, string> qos1Event = Assert.Single(ehMessages.Where(x => TelemetryQoS1Content.Equals(x.Item2, StringComparison.Ordinal))); string qosPropertyName = ConfigurationManager.AppSettings["QoSPropertyName"]; var qos0Notification = new Message(Encoding.UTF8.GetBytes(NotificationQoS0Content)); qos0Notification.Properties[qosPropertyName] = "0"; qos0Notification.Properties["subTopic"] = "tips"; await serviceClient.SendAsync(this.deviceId, qos0Notification); var qos1Notification = new Message(Encoding.UTF8.GetBytes(NotificationQoS1Content)); qos1Notification.Properties["subTopic"] = "firmware-update"; await serviceClient.SendAsync(this.deviceId, qos1Notification); var qos2Notification = new Message(Encoding.UTF8.GetBytes(NotificationQoS2Content)); qos2Notification.Properties[qosPropertyName] = "2"; qos2Notification.Properties["subTopic"] = "critical-alert"; await serviceClient.SendAsync(this.deviceId, qos2Notification); var qos2Notification2 = new Message(Encoding.UTF8.GetBytes(NotificationQoS2Content2)); qos2Notification2.Properties[qosPropertyName] = "2"; await serviceClient.SendAsync(this.deviceId, qos2Notification2); }); await clientScenarios.RunPart1StepsAsync(clientChannel, readHandler1).WithTimeout(TestTimeout); await testWorkTask.WithTimeout(TestTimeout); this.output.WriteLine($"part 1 completed in {sw.Elapsed}"); await this.EnsureDeviceQueueLengthAsync(hubConnectionStringBuilder.HostName, device, 1); this.output.WriteLine($"part 1 clean completed in {sw.Elapsed}"); string part2Payload = Guid.NewGuid().ToString("N"); await serviceClient.SendAsync(this.deviceId, new Message(Encoding.ASCII.GetBytes(part2Payload))); var readHandler2 = new ReadListeningHandler(CommunicationTimeout); IChannel clientChannelPart2 = await bootstrap .Handler(this.ComposeClientChannelInitializer(targetHost, readHandler2)) .ConnectAsync(this.ServerAddress, protocolGatewayPort); this.ScheduleCleanup(async () => { await clientChannelPart2.CloseAsync(); await group.ShutdownGracefullyAsync(); }); await clientScenarios.RunPart2StepsAsync(clientChannelPart2, readHandler2).WithTimeout(TestTimeout); this.output.WriteLine($"Core test completed in {sw.Elapsed}"); await this.EnsureDeviceQueueLengthAsync(hubConnectionStringBuilder.HostName, device, 0); }
public async Task BasicFunctionalityTest() { await this.EnsureServerInitializedAsync(); int protocolGatewayPort = this.ProtocolGatewayPort; string iotHubConnectionString = ConfigurationManager.AppSettings["IoTHubConnectionString"]; IotHubConnectionStringBuilder hubConnectionStringBuilder = IotHubConnectionStringBuilder.Create(iotHubConnectionString); bool deviceNameProvided; this.deviceId = ConfigurationManager.AppSettings["End2End.DeviceName"]; if (!string.IsNullOrEmpty(this.deviceId)) { deviceNameProvided = true; } else { deviceNameProvided = false; this.deviceId = Guid.NewGuid().ToString("N"); } RegistryManager registryManager = RegistryManager.CreateFromConnectionString(iotHubConnectionString); if (!deviceNameProvided) { await registryManager.AddDeviceAsync(new Device(this.deviceId)); this.ScheduleCleanup(async() => { await registryManager.RemoveDeviceAsync(this.deviceId); await registryManager.CloseAsync(); }); } Device device = await registryManager.GetDeviceAsync(this.deviceId); this.deviceSas = new SharedAccessSignatureBuilder { Key = device.Authentication.SymmetricKey.PrimaryKey, Target = string.Format("{0}/devices/{1}", hubConnectionStringBuilder.HostName, this.deviceId), KeyName = null, TimeToLive = TimeSpan.FromMinutes(20) } .ToSignature(); EventHubClient eventHubClient = EventHubClient.CreateFromConnectionString(iotHubConnectionString, "messages/events"); EventHubConsumerGroup ehGroup = eventHubClient.GetDefaultConsumerGroup(); string[] partitionIds = (await eventHubClient.GetRuntimeInformationAsync()).PartitionIds; EventHubReceiver[] receivers = await Task.WhenAll(partitionIds.Select(pid => ehGroup.CreateReceiverAsync(pid.Trim(), DateTime.UtcNow))); ServiceClient serviceClient = ServiceClient.CreateFromConnectionString(iotHubConnectionString); Stopwatch sw = Stopwatch.StartNew(); var testPromise = new TaskCompletionSource(); var group = new MultithreadEventLoopGroup(); string targetHost = this.tlsCertificate.GetNameInfo(X509NameType.DnsName, false); Bootstrap bootstrap = new Bootstrap() .Group(group) .Channel <TcpSocketChannel>() .Option(ChannelOption.TcpNodelay, true) .Handler(new ActionChannelInitializer <ISocketChannel>(ch => ch.Pipeline.AddLast( TlsHandler.Client(targetHost, null, (sender, certificate, chain, errors) => true), MqttEncoder.Instance, new MqttDecoder(false, 256 * 1024), new TestScenarioRunner(cmf => GetClientScenario(cmf, hubConnectionStringBuilder.HostName, this.deviceId, this.deviceSas), testPromise, CommunicationTimeout, CommunicationTimeout), new XUnitLoggingHandler(this.output)))); IChannel clientChannel = await bootstrap.ConnectAsync(this.ServerAddress, protocolGatewayPort); this.ScheduleCleanup(async() => { await clientChannel.CloseAsync(); await group.ShutdownGracefullyAsync(); }); Task testWorkTask = Task.Run(async() => { Tuple <EventData, string>[] ehMessages = await CollectEventHubMessagesAsync(receivers, 2); Tuple <EventData, string> qos0Event = Assert.Single(ehMessages.Where(x => TelemetryQoS0Content.Equals(x.Item2, StringComparison.Ordinal))); //Assert.Equal((string)qos0Event.Item1.Properties["level"], "verbose"); //Assert.Equal((string)qos0Event.Item1.Properties["subject"], "n/a"); Tuple <EventData, string> qos1Event = Assert.Single(ehMessages.Where(x => TelemetryQoS1Content.Equals(x.Item2, StringComparison.Ordinal))); string qosPropertyName = ConfigurationManager.AppSettings["QoSPropertyName"]; var qos0Notification = new Message(Encoding.UTF8.GetBytes(NotificationQoS0Content)); qos0Notification.Properties[qosPropertyName] = "0"; qos0Notification.Properties["subTopic"] = "tips"; await serviceClient.SendAsync(this.deviceId, qos0Notification); var qos1Notification = new Message(Encoding.UTF8.GetBytes(NotificationQoS1Content)); qos1Notification.Properties["subTopic"] = "firmware-update"; await serviceClient.SendAsync(this.deviceId, qos1Notification); var qos2Notification = new Message(Encoding.UTF8.GetBytes(NotificationQoS2Content)); qos2Notification.Properties[qosPropertyName] = "2"; qos2Notification.Properties["subTopic"] = "critical-alert"; await serviceClient.SendAsync(this.deviceId, qos2Notification); }); Task timeoutTask = Task.Run(async() => { await Task.Delay(TestTimeout); throw new TimeoutException("Test has timed out."); }); await TaskExtensions.WhenSome(new[] { testPromise.Task, testWorkTask, timeoutTask }, 2); this.output.WriteLine(string.Format("Core test completed in {0}", sw.Elapsed)); // making sure that device queue is empty. await Task.Delay(TimeSpan.FromSeconds(3)); DeviceClient deviceClient = DeviceClient.Create( hubConnectionStringBuilder.HostName, new DeviceAuthenticationWithRegistrySymmetricKey(this.deviceId, device.Authentication.SymmetricKey.PrimaryKey)); Client.Message message = await deviceClient.ReceiveAsync(TimeSpan.FromSeconds(1)); Assert.True(message == null, string.Format("Message is not null: {0}", message)); }
public async Task BasicFunctionalityTest() { await this.EnsureServerInitializedAsync(); int protocolGatewayPort = this.ProtocolGatewayPort; string iotHubConnectionString = ConfigurationManager.AppSettings["IoTHubConnectionString"]; IotHubConnectionStringBuilder hubConnectionStringBuilder = IotHubConnectionStringBuilder.Create(iotHubConnectionString); bool deviceNameProvided; this.deviceId = ConfigurationManager.AppSettings["End2End.DeviceName"]; if (!string.IsNullOrEmpty(this.deviceId)) { deviceNameProvided = true; } else { deviceNameProvided = false; this.deviceId = Guid.NewGuid().ToString("N"); } RegistryManager registryManager = RegistryManager.CreateFromConnectionString(iotHubConnectionString); if (!deviceNameProvided) { await registryManager.AddDeviceAsync(new Device(this.deviceId)); this.ScheduleCleanup(async () => { await registryManager.RemoveDeviceAsync(this.deviceId); await registryManager.CloseAsync(); }); } Device device = await registryManager.GetDeviceAsync(this.deviceId); this.deviceSas = new SharedAccessSignatureBuilder { Key = device.Authentication.SymmetricKey.PrimaryKey, Target = string.Format("{0}/devices/{1}", hubConnectionStringBuilder.HostName, this.deviceId), KeyName = null, TimeToLive = TimeSpan.FromMinutes(20) } .ToSignature(); EventHubClient eventHubClient = EventHubClient.CreateFromConnectionString(iotHubConnectionString, "messages/events"); EventHubConsumerGroup ehGroup = eventHubClient.GetDefaultConsumerGroup(); string[] partitionIds = (await eventHubClient.GetRuntimeInformationAsync()).PartitionIds; EventHubReceiver[] receivers = await Task.WhenAll(partitionIds.Select(pid => ehGroup.CreateReceiverAsync(pid.Trim(), DateTime.UtcNow))); ServiceClient serviceClient = ServiceClient.CreateFromConnectionString(iotHubConnectionString); Stopwatch sw = Stopwatch.StartNew(); var testPromise = new TaskCompletionSource(); var group = new MultithreadEventLoopGroup(); string targetHost = this.tlsCertificate.GetNameInfo(X509NameType.DnsName, false); Bootstrap bootstrap = new Bootstrap() .Group(group) .Channel<TcpSocketChannel>() .Option(ChannelOption.TcpNodelay, true) .Handler(new ActionChannelInitializer<ISocketChannel>(ch => ch.Pipeline.AddLast( TlsHandler.Client(targetHost, null, (sender, certificate, chain, errors) => true), MqttEncoder.Instance, new MqttDecoder(false, 256 * 1024), new TestScenarioRunner(cmf => GetClientScenario(cmf, hubConnectionStringBuilder.HostName, this.deviceId, this.deviceSas), testPromise, CommunicationTimeout, CommunicationTimeout), new XUnitLoggingHandler(this.output)))); IChannel clientChannel = await bootstrap.ConnectAsync(this.ServerAddress, protocolGatewayPort); this.ScheduleCleanup(async () => { await clientChannel.CloseAsync(); await group.ShutdownGracefullyAsync(); }); Task testWorkTask = Task.Run(async () => { Tuple<EventData, string>[] ehMessages = await CollectEventHubMessagesAsync(receivers, 2); Tuple<EventData, string> qos0Event = Assert.Single(ehMessages.Where(x => TelemetryQoS0Content.Equals(x.Item2, StringComparison.Ordinal))); //Assert.Equal((string)qos0Event.Item1.Properties["level"], "verbose"); //Assert.Equal((string)qos0Event.Item1.Properties["subject"], "n/a"); Tuple<EventData, string> qos1Event = Assert.Single(ehMessages.Where(x => TelemetryQoS1Content.Equals(x.Item2, StringComparison.Ordinal))); string qosPropertyName = ConfigurationManager.AppSettings["QoSPropertyName"]; var qos0Notification = new Message(Encoding.UTF8.GetBytes(NotificationQoS0Content)); qos0Notification.Properties[qosPropertyName] = "0"; qos0Notification.Properties["subTopic"] = "tips"; await serviceClient.SendAsync(this.deviceId, qos0Notification); var qos1Notification = new Message(Encoding.UTF8.GetBytes(NotificationQoS1Content)); qos1Notification.Properties["subTopic"] = "firmware-update"; await serviceClient.SendAsync(this.deviceId, qos1Notification); var qos2Notification = new Message(Encoding.UTF8.GetBytes(NotificationQoS2Content)); qos2Notification.Properties[qosPropertyName] = "2"; qos2Notification.Properties["subTopic"] = "critical-alert"; await serviceClient.SendAsync(this.deviceId, qos2Notification); }); Task timeoutTask = Task.Run(async () => { await Task.Delay(TestTimeout); throw new TimeoutException("Test has timed out."); }); await TaskExtensions.WhenSome(new[] { testPromise.Task, testWorkTask, timeoutTask }, 2); this.output.WriteLine(string.Format("Core test completed in {0}", sw.Elapsed)); // making sure that device queue is empty. await Task.Delay(TimeSpan.FromSeconds(3)); DeviceClient deviceClient = DeviceClient.Create( hubConnectionStringBuilder.HostName, new DeviceAuthenticationWithRegistrySymmetricKey(this.deviceId, device.Authentication.SymmetricKey.PrimaryKey)); Client.Message message = await deviceClient.ReceiveAsync(TimeSpan.FromSeconds(1)); Assert.True(message == null, string.Format("Message is not null: {0}", message)); }