示例#1
0
        private static async void SendDeviceToCloudMessagesAsync()
        {
            double minTemperature = 20;
            double minHumidity    = 60;
            int    messageId      = 1;
            Random rand           = new Random();

            for (int i = 0; i < messN; i++)
            {
                double currentTemperature = Math.Round((minTemperature + rand.NextDouble() * 15), 2);
                double currentHumidity    = Math.Round((minHumidity + rand.NextDouble() * 20), 2);
                string level = (currentTemperature > 30 ? "critical" : "normal");

                var telemetryDataPoint = new
                {
                    messageId   = messageId++,
                    deviceId    = deviceID,
                    temperature = currentTemperature,
                    humidity    = currentHumidity,
                };
                var messageString = JsonConvert.SerializeObject(telemetryDataPoint);
                var message       = new Message(Encoding.ASCII.GetBytes(messageString));
                message.Properties.Add("level", level);

                await iotClient.SendEventAsync(message);

                Console.WriteLine("{0} > Sending message - level: {1} - {2}", DateTime.Now, level, messageString);

                await Task.Delay(100);
            }


            Console.WriteLine("Closing...");
            await iotClient.CloseAsync();
        }
示例#2
0
        private async Task ReceiveSingleMessageAsync(TestDeviceType type, Client.TransportType transport)
        {
            TestDevice testDevice = await TestDevice.GetTestDeviceAsync(Logger, s_devicePrefix, type).ConfigureAwait(false);

            using DeviceClient deviceClient = testDevice.CreateDeviceClient(transport);
            using var serviceClient         = ServiceClient.CreateFromConnectionString(Configuration.IoTHub.ConnectionString);

            await deviceClient.OpenAsync().ConfigureAwait(false);

            if (transport == Client.TransportType.Mqtt_Tcp_Only ||
                transport == Client.TransportType.Mqtt_WebSocket_Only)
            {
                // Dummy ReceiveAsync to ensure mqtt subscription registration before SendAsync() is called on service client.
                await deviceClient.ReceiveAsync(s_fiveSeconds).ConfigureAwait(false);
            }

            await serviceClient.OpenAsync().ConfigureAwait(false);

            (Message msg, string payload, string p1Value) = ComposeC2dTestMessage(Logger);
            using (msg)
            {
                await serviceClient.SendAsync(testDevice.Id, msg).ConfigureAwait(false);
                await VerifyReceivedC2DMessageAsync(transport, deviceClient, testDevice.Id, msg, payload, Logger).ConfigureAwait(false);
            }

            await deviceClient.CloseAsync().ConfigureAwait(false);

            await serviceClient.CloseAsync().ConfigureAwait(false);
        }
示例#3
0
        /// <summary>
        /// Shuts down the IoTHub communication.
        /// </summary>
        public void Shutdown()
        {
            // send cancellation token and wait for last IoT Hub message to be sent.
            try
            {
                _tokenSource.Cancel();
                _dequeueAndSendTask.Wait();

                if (_iotHubClient != null)
                {
                    _iotHubClient.CloseAsync().Wait();
                }
                if (_sendTimer != null)
                {
                    _sendTimer.Dispose();
                }
                if (_sendQueueEvent != null)
                {
                    _sendQueueEvent.Dispose();
                }
            }
            catch (Exception e)
            {
                Trace(e, "Failure while shutting down IoTHub messaging.");
            }
        }
示例#4
0
        // INSERT Main method below here
        public static async Task Main(string[] args)
        {
            using (var security = new SecurityProviderSymmetricKey(registrationId,
                                                                   individualEnrollmentPrimaryKey,
                                                                   individualEnrollmentSecondaryKey))
                using (var transport = new ProvisioningTransportHandlerAmqp(TransportFallbackType.TcpOnly))
                {
                    ProvisioningDeviceClient provClient =
                        ProvisioningDeviceClient.Create(GlobalDeviceEndpoint, dpsIdScope, security, transport);

                    using (deviceClient = await ProvisionDevice(provClient, security))
                    {
                        await deviceClient.OpenAsync().ConfigureAwait(false);

                        // INSERT Setup OnDesiredPropertyChanged Event Handling below here
                        await deviceClient.SetDesiredPropertyUpdateCallbackAsync(OnDesiredPropertyChanged, null).ConfigureAwait(false);

                        // INSERT Load Device Twin Properties below here
                        var twin = await deviceClient.GetTwinAsync().ConfigureAwait(false);
                        await OnDesiredPropertyChanged(twin.Properties.Desired, null);

                        // Start reading and sending device telemetry
                        Console.WriteLine("Start reading and sending device telemetry...");
                        await SendDeviceToCloudMessagesAsync();

                        await deviceClient.CloseAsync().ConfigureAwait(false);
                    }
                }
        }
示例#5
0
        static async Task startClient(string IoTHub, string IoTDevicePrefix, int deviceNumber, string commonKey, int maxMessages, int messageDelaySeconds)
        {
            allClientStarted++;
            runningDevices++;
            string       connectionString = "HostName=" + IoTHub + ";DeviceId=" + IoTDevicePrefix + deviceNumber + ";SharedAccessKey=" + commonKey;
            DeviceClient device           = DeviceClient.CreateFromConnectionString(connectionString, Microsoft.Azure.Devices.Client.TransportType.Mqtt);
            await device.OpenAsync();

            Random rnd       = new Random();
            int    mycounter = 1;

            Console.WriteLine("Device " + IoTDevicePrefix + deviceNumber + " started");

            while (mycounter <= maxMessages)
            {
                Thread.Sleep((messageDelaySeconds * 1000) + rnd.Next(1, 100));
                string message = "{ \'loadTest\':\'True\', 'sequenceNumber': " + mycounter + ", \'SubmitTime\': \'" + DateTime.UtcNow + "\', \'randomValue\':" + rnd.Next(1, 4096 * 4096) + " }";
                Microsoft.Azure.Devices.Client.Message IoTMessage = new Microsoft.Azure.Devices.Client.Message(Encoding.UTF8.GetBytes(message));
                await device.SendEventAsync(IoTMessage);

                totalMessageSent++;
                mycounter++;
            }
            await device.CloseAsync();

            Console.WriteLine("Device " + IoTDevicePrefix + deviceNumber + " ended");
            runningDevices--;
        }
示例#6
0
        protected async Task CloseAsync(CancellationToken ct)
        {
            if (_dc == null)
            {
                return;
            }

            _m.ScheduleTime  = null;
            _m.OperationType = TelemetryMetrics.DeviceOperationClose;
            _sw.Restart();

            try
            {
                await _dc.CloseAsync(ct).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                _m.ErrorMessage = $"{ex.GetType().Name} - {ex.Message}";
                throw;
            }
            finally
            {
                _m.ExecuteTime = _sw.ElapsedMilliseconds;
                await _writer.WriteAsync(_m).ConfigureAwait(false);
            }
        }
        private async Task ReceiveSingleMessage(TestDeviceType type, Client.TransportType transport)
        {
            ServiceClient serviceClient = ServiceClient.CreateFromConnectionString(Configuration.IoTHub.ConnectionString);

            TestDevice testDevice = await TestDevice.GetTestDeviceAsync(DevicePrefix, type).ConfigureAwait(false);

            DeviceClient deviceClient = testDevice.CreateDeviceClient(transport);

            try
            {
                await deviceClient.OpenAsync().ConfigureAwait(false);

                if (transport == Client.TransportType.Mqtt_Tcp_Only ||
                    transport == Client.TransportType.Mqtt_WebSocket_Only)
                {
                    _log.WriteLine("Dummy ReceiveAsync to ensure mqtt subscription registration before SendAsync() is called on service client.");
                    await deviceClient.ReceiveAsync(TimeSpan.FromSeconds(2)).ConfigureAwait(false);
                }

                string payload, messageId, p1Value;
                await serviceClient.OpenAsync().ConfigureAwait(false);

                Message msg = ComposeC2DTestMessage(out payload, out messageId, out p1Value);
                await serviceClient.SendAsync(testDevice.Id, msg).ConfigureAwait(false);

                await VerifyReceivedC2DMessage(transport, deviceClient, payload, p1Value).ConfigureAwait(false);
            }
            finally
            {
                await deviceClient.CloseAsync().ConfigureAwait(false);

                await serviceClient.CloseAsync().ConfigureAwait(false);
            }
        }
示例#8
0
        private async Task ReceiveSingleMessageWithCancellationTokenAsync(TestDeviceType type, Client.TransportType transport)
        {
            TestDevice testDevice = await TestDevice.GetTestDeviceAsync(Logger, s_devicePrefix, type).ConfigureAwait(false);

            using DeviceClient deviceClient = testDevice.CreateDeviceClient(transport);
            using var serviceClient         = ServiceClient.CreateFromConnectionString(Configuration.IoTHub.ConnectionString);

            await deviceClient.OpenAsync().ConfigureAwait(false);

            await serviceClient.OpenAsync().ConfigureAwait(false);

            // For Mqtt - the device needs to have subscribed to the devicebound topic, in order for IoT Hub to deliver messages to the device.
            // For this reason we will make a "fake" ReceiveAsync() call, which will result in the device subscribing to the c2d topic.
            // Note: We need this "fake" ReceiveAsync() call even though we (SDK default) CONNECT with a CleanSession flag set to 0.
            // This is because this test device is newly created, and it has never subscribed to IoT hub c2d topic.
            // Hence, IoT hub doesn't know about its CleanSession preference yet.
            if (transport == Client.TransportType.Mqtt_Tcp_Only ||
                transport == Client.TransportType.Mqtt_WebSocket_Only)
            {
                await deviceClient.ReceiveAsync(s_fiveSeconds).ConfigureAwait(false);
            }

            (Message msg, string payload, string p1Value) = ComposeC2dTestMessage(Logger);
            using (msg)
            {
                await serviceClient.SendAsync(testDevice.Id, msg).ConfigureAwait(false);
            }
            await VerifyReceivedC2dMessageWithCancellationTokenAsync(transport, deviceClient, testDevice.Id, payload, p1Value, Logger).ConfigureAwait(false);

            await deviceClient.CloseAsync().ConfigureAwait(false);

            await serviceClient.CloseAsync().ConfigureAwait(false);
        }
        async Task EnsureDeviceQueueLengthAsync(string hostname, Device device, int expectedLength)
        {
            await Task.Delay(TimeSpan.FromSeconds(1));

            DeviceClient deviceClient = null;

            try
            {
                deviceClient = DeviceClient.Create(
                    hostname,
                    new DeviceAuthenticationWithRegistrySymmetricKey(this.deviceId, device.Authentication.SymmetricKey.PrimaryKey));
                int leftToTarget = expectedLength;
                while (true)
                {
                    using (Client.Message message = await deviceClient.ReceiveAsync(TimeSpan.FromSeconds(2)))
                    {
                        if (message == null)
                        {
                            break;
                        }
                        leftToTarget--;
                        Assert.True(leftToTarget >= 0, $"actual device queue length is greater than expected ({expectedLength}).");
                    }
                }
                Assert.True(leftToTarget == 0, $"actual device length is less than expected ({expectedLength}).");
            }
            finally
            {
                if (deviceClient != null)
                {
                    await deviceClient.CloseAsync();
                }
            }
        }
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            deferral = taskInstance.GetDeferral();
            InitGPIO();
            try
            {
                Console.WriteLine("Connecting to hub");
                Client = DeviceClient.CreateFromConnectionString(DeviceConnectionString, TransportType.Mqtt);

                // setup callback for "writeLine" method
                Client.SetMethodHandlerAsync("lightOn", TurnLightOn, null).Wait();
                Client.SetMethodHandlerAsync("lightOff", TurnLightOff, null).Wait();

                Console.WriteLine("Waiting for direct method call\n Press enter to exit.");
                Console.ReadLine();

                Console.WriteLine("Exiting...");

                // as a good practice, remove the "writeLine" handler
                Client.SetMethodHandlerAsync("lightOn", null, null).Wait();
                Client.SetMethodHandlerAsync("lightOff", null, null).Wait();
                Client.CloseAsync().Wait();
            }
            catch (Exception ex)
            {
                Console.WriteLine();
                Console.WriteLine("Error in sample: {0}", ex.Message);
            }
        }
示例#11
0
        private async Task SendMethodAndRespondRecovery(Client.TransportType transport, string faultType, string reason, int delayInSec)
        {
            Tuple <string, string> deviceInfo = TestUtil.CreateDevice(DevicePrefix, hostName, registryManager);

            var          assertResult = new TaskCompletionSource <Tuple <bool, bool> >();
            DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(deviceInfo.Item2, transport);
            await deviceClient.SetMethodHandlerAsync(MethodName,
                                                     (request, context) =>
            {
                assertResult.SetResult(new Tuple <bool, bool>(request.Name.Equals(MethodName), request.DataAsJson.Equals(ServiceRequestJson)));
                return(Task.FromResult(new MethodResponse(Encoding.UTF8.GetBytes(DeviceResponseJson), 200)));
            },
                                                     null);

            await ServiceSendMethodAndVerifyResponse(deviceInfo.Item1, MethodName, DeviceResponseJson, ServiceRequestJson, assertResult);

            // send error command
            await deviceClient.SendEventAsync(TestUtil.ComposeErrorInjectionProperties(faultType, reason, delayInSec));

            // allow time for connection recovery
            await Task.Delay(TimeSpan.FromSeconds(3));

            assertResult = new TaskCompletionSource <Tuple <bool, bool> >();
            await ServiceSendMethodAndVerifyResponse(deviceInfo.Item1, MethodName, DeviceResponseJson, ServiceRequestJson, assertResult);

            await deviceClient.CloseAsync();

            TestUtil.RemoveDevice(deviceInfo.Item1, registryManager);
        }
        public void Dispose()
        {
            if (udpClient != null)
            {
                if (udpClient.Client != null && udpClient.Client.Connected)
                {
                    try { udpClient.Client.Disconnect(false); } catch (Exception ex) { Console.WriteLine($"Udp Client socket disconnecting error: {ex.Message}"); }
                    try { udpClient.Client.Close(); } catch (Exception ex) { Console.WriteLine($"Udp Client socket closing error: {ex.Message}"); }
                    try { udpClient.Client.Dispose(); } catch (Exception ex) { Console.WriteLine($"Udp Client socket disposing error: {ex.Message}"); }
                }

                try { udpClient.Close(); } catch (Exception ex) { Console.WriteLine($"Udp Client closing error: {ex.Message}"); }
                try { udpClient.Dispose(); } catch (Exception ex) { Console.WriteLine($"Udp Client disposing error: {ex.Message}"); }
            }

            if (ioTHubModuleClient != null)
            {
                try { ioTHubModuleClient.CloseAsync().Wait(); } catch (Exception ex) { Console.WriteLine($"IoTHub Module Client closing error: {ex.Message}"); }
                try { ioTHubModuleClient.Dispose(); } catch (Exception ex) { Console.WriteLine($"IoTHub Module Client disposing error: {ex.Message}"); }
            }

            if (messageProcessor != null)
            {
                try { messageProcessor.Dispose(); } catch (Exception ex) { Console.WriteLine($"Message Processor disposing error: {ex.Message}"); }
            }
        }
        private async Task ReceiveSingleMessageWithCancellationToken(TestDeviceType type, Client.TransportType transport)
        {
            TestDevice testDevice = await TestDevice.GetTestDeviceAsync(DevicePrefix, type).ConfigureAwait(false);

            using (DeviceClient deviceClient = testDevice.CreateDeviceClient(transport))
                using (ServiceClient serviceClient = ServiceClient.CreateFromConnectionString(Configuration.IoTHub.ConnectionString))
                {
                    await deviceClient.OpenAsync().ConfigureAwait(false);

                    if (transport == Client.TransportType.Mqtt_Tcp_Only ||
                        transport == Client.TransportType.Mqtt_WebSocket_Only)
                    {
                        // Dummy ReceiveAsync to ensure mqtt subscription registration before SendAsync() is called on service client.
                        await deviceClient.ReceiveAsync(TIMESPAN_FIVE_SECONDS).ConfigureAwait(false);
                    }

                    await serviceClient.OpenAsync().ConfigureAwait(false);

                    (Message msg, string messageId, string payload, string p1Value) = ComposeC2DTestMessage();
                    await serviceClient.SendAsync(testDevice.Id, msg).ConfigureAwait(false);
                    await VerifyReceivedC2DMessageWithCancellationTokenAsync(transport, deviceClient, testDevice.Id, payload, p1Value).ConfigureAwait(false);

                    await deviceClient.CloseAsync().ConfigureAwait(false);

                    await serviceClient.CloseAsync().ConfigureAwait(false);
                }
        }
示例#14
0
        private async Task ReceiveMessageInOperationTimeout(TestDeviceType type, Client.TransportType transport)
        {
            TestDevice testDevice = await TestDevice.GetTestDeviceAsync(DevicePrefix, type).ConfigureAwait(false);

            using (DeviceClient deviceClient = testDevice.CreateDeviceClient(transport))
            {
                await deviceClient.OpenAsync().ConfigureAwait(false);

                if (transport == Client.TransportType.Mqtt_Tcp_Only ||
                    transport == Client.TransportType.Mqtt_WebSocket_Only)
                {
                    // Dummy ReceiveAsync to ensure mqtt subscription registration before SendAsync() is called on service client.
                    await deviceClient.ReceiveAsync(TIMESPAN_FIVE_SECONDS).ConfigureAwait(false);
                }

                try
                {
                    deviceClient.OperationTimeoutInMilliseconds = Convert.ToUInt32(TIMESPAN_ONE_MINUTE.TotalMilliseconds);
                    if (transport == Client.TransportType.Amqp || transport == Client.TransportType.Amqp_Tcp_Only || transport == Client.TransportType.Amqp_WebSocket_Only)
                    {
                        // For AMQP because of static 1 min interval check the cancellation token, in worst case it will block upto extra 1 min to return
                        await ReceiveMessageWithoutTimeoutCheck(deviceClient, TIMESPAN_ONE_MINUTE).ConfigureAwait(false);
                    }
                    else
                    {
                        await ReceiveMessageWithoutTimeoutCheck(deviceClient, TIMESPAN_FIVE_SECONDS).ConfigureAwait(false);
                    }
                }
                finally
                {
                    deviceClient.OperationTimeoutInMilliseconds = DeviceClient.DefaultOperationTimeoutInMilliseconds;
                    await deviceClient.CloseAsync().ConfigureAwait(false);
                }
            }
        }
        private async Task ReuseAuthenticationMethod_SingleDevice(Client.TransportType transport)
        {
            TestDevice testDevice = await TestDevice.GetTestDeviceAsync(Logger, _devicePrefix).ConfigureAwait(false);

            var authenticationMethod = new DeviceAuthenticationSasToken(testDevice.ConnectionString, disposeWithClient: false);

            // Create an instance of the device client, send a test message and then close and dispose it.
            DeviceClient deviceClient = DeviceClient.Create(testDevice.IoTHubHostName, authenticationMethod, transport);

            using var message1 = new Client.Message();
            await deviceClient.SendEventAsync(message1).ConfigureAwait(false);

            await deviceClient.CloseAsync();

            deviceClient.Dispose();
            Logger.Trace("Test with instance 1 completed");

            // Perform the same steps again, reusing the previously created authentication method instance to ensure
            // that the sdk did not dispose the user supplied authentication method instance.
            DeviceClient deviceClient2 = DeviceClient.Create(testDevice.IoTHubHostName, authenticationMethod, transport);

            using var message2 = new Client.Message();
            await deviceClient2.SendEventAsync(message2).ConfigureAwait(false);

            await deviceClient2.CloseAsync();

            deviceClient2.Dispose();
            Logger.Trace("Test with instance 2 completed, reused the previously created authentication method instance for the device client.");

            authenticationMethod.Dispose();
        }
        private async Task AuthenticationMethodDisposesTokenRefresher(Client.TransportType transport)
        {
            TestDevice testDevice = await TestDevice.GetTestDeviceAsync(Logger, _devicePrefix).ConfigureAwait(false);

            var authenticationMethod = new DeviceAuthenticationSasToken(testDevice.ConnectionString, disposeWithClient: true);

            // Create an instance of the device client, send a test message and then close and dispose it.
            DeviceClient deviceClient = DeviceClient.Create(testDevice.IoTHubHostName, authenticationMethod, transport);

            using var message1 = new Client.Message();
            await deviceClient.SendEventAsync(message1).ConfigureAwait(false);

            await deviceClient.CloseAsync();

            deviceClient.Dispose();
            Logger.Trace("Test with instance 1 completed");

            // Perform the same steps again, reusing the previously created authentication method instance.
            // Since the default behavior is to dispose AuthenticationWithTokenRefresh authentication method on DeviceClient disposal,
            // this should now throw an ObjectDisposedException.
            DeviceClient deviceClient2 = DeviceClient.Create(testDevice.IoTHubHostName, authenticationMethod, transport);

            using var message2 = new Client.Message();

            Func <Task> act = async() => await deviceClient2.SendEventAsync(message2).ConfigureAwait(false);

            await act.Should().ThrowAsync <ObjectDisposedException>();
        }
示例#17
0
        private static async void SendDeviceToCloudMessagesAsync()
        {
            int      i     = 0;
            DateTime start = DateTime.Now;

            while (run)
            {
                i++;
                string       telemetry    = GenerateMessage(i, $"message:{i}");
                DeviceClient deviceClient = CreateDeviceClient(deviceId, deviceKey);
                await deviceClient.SendEventAsync(new Microsoft.Azure.Devices.Client.Message(Encoding.UTF8.GetBytes(telemetry)));

                await deviceClient.CloseAsync();

                Console.WriteLine("{0} ==> Sending message: {1}", DateTime.Now, telemetry);

                Thread.Sleep(1000);

                var time = DateTime.Now - start;
                if (time.Seconds >= duration)
                {
                    Success($"Sent {i} messages, druation {time.Seconds} seconds");
                    run = false;
                }
            }
            Log("Exit SendMessage()...");
        }
        private static async Task Main()
        {
            if (readTheFile)
            {
                // If you want to decode an output file, put the path in ReadOneRowFromFile(),
                //   uncomment the call here and the return command, then run this application.
                ReadOneRowFromFile();
            }
            else
            {
                // Send messages to the simulated device. Each message will contain a randomly generated
                //   Temperature and Humidity.
                // The "level" of each message is set randomly to "storage", "critical", or "normal".
                // The messages are routed to different endpoints depending on the level, temperature, and humidity.
                //  This is set in the tutorial that goes with this sample:
                //  http://docs.microsoft.com/azure/iot-hub/tutorial-routing

                Console.WriteLine("Routing Tutorial: Simulated device\n");
                s_deviceClient = DeviceClient.Create(s_iotHubUri,
                                                     new DeviceAuthenticationWithRegistrySymmetricKey(s_myDeviceId, s_deviceKey), TransportType.Mqtt);

                using var cts = new CancellationTokenSource();
                var messages = SendDeviceToCloudMessagesAsync(cts.Token);
                Console.WriteLine("Press the Enter key to stop.");
                Console.ReadLine();
                await s_deviceClient.CloseAsync(cts.Token);

                cts.Cancel();
                await messages;
            }
        }
示例#19
0
        // Device SDK caches the AmqpTransportSettings that are set the first time and ignores
        // all the settings used thereafter from that process. So set up a dummy connection using the test
        // AmqpTransportSettings, so that Device SDK caches it and uses it thereafter
        static async Task ConnectToIotHub(string connectionString)
        {
            DeviceClient dc = DeviceClient.CreateFromConnectionString(connectionString, TestSettings.AmqpTransportSettings);
            await dc.OpenAsync();

            await dc.CloseAsync();
        }
        internal bool SendMessages(int numMessages, int sleepMilisecs)
        {
            var colors = Enum.GetValues(typeof(KnownColor));

            try
            {
                // Note that MQTT is required for the device twin stuff to work.
                Me = DeviceClient.Create(Program.IotHubUri, new DeviceAuthenticationWithX509Certificate(MyDevId, MyCert),
                                         Microsoft.Azure.Devices.Client.TransportType.Mqtt);
                Me.OpenAsync().Wait();
                QueryFWStatus();
                for (byte j = 0; j < numMessages; j++)
                {
                    int colorVal = (int)colors.GetValue(rr.Next(colors.Length));
                    var t        = Me.SendEventAsync(MakeMessage(MyDevId, colorVal, MessageCount++));
                    t.Wait();
                    Thread.Sleep(sleepMilisecs);
                }
                Me.CloseAsync().Wait();
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"Error in Create or SendMessages {ex.ToString()}");
                if (ex.InnerException != null)
                {
                    Debug.WriteLine($"Error in SendMessages (inner exception is) {ex.InnerException.ToString()}");
                }
                return(false);
            }

            return(true);
        }
示例#21
0
        private async Task ReceiveSingleMessageUsingCallbackAsync(TestDeviceType type, Client.TransportType transport)
        {
            TestDevice testDevice = await TestDevice.GetTestDeviceAsync(Logger, s_devicePrefix, type).ConfigureAwait(false);

            using DeviceClient deviceClient     = testDevice.CreateDeviceClient(transport);
            using var testDeviceCallbackHandler = new TestDeviceCallbackHandler(deviceClient, testDevice, Logger);

            using var serviceClient = ServiceClient.CreateFromConnectionString(Configuration.IoTHub.ConnectionString);

            (Message msg, string payload, string p1Value) = ComposeC2dTestMessage(Logger);
            using (msg)
            {
                await testDeviceCallbackHandler.SetMessageReceiveCallbackHandlerAsync().ConfigureAwait(false);

                testDeviceCallbackHandler.ExpectedMessageSentByService = msg;

                using var cts = new CancellationTokenSource(s_tenSeconds);
                Logger.Trace($"Sending C2D message from service, messageId={msg.MessageId}");
                await Task
                .WhenAll(
                    serviceClient.SendAsync(testDevice.Id, msg),
                    testDeviceCallbackHandler.WaitForReceiveMessageCallbackAsync(cts.Token))
                .ConfigureAwait(false);
            }

            await deviceClient.CloseAsync().ConfigureAwait(false);

            await serviceClient.CloseAsync().ConfigureAwait(false);
        }
        private async Task SendMethodAndRespondRecovery(Client.TransportType transport, string faultType, string reason, int delayInSec)
        {
            Tuple <string, string> deviceInfo = TestUtil.CreateDevice("E2E_Method_CSharp_", hostName, registryManager);
            string deviceResponseJson         = "{\"name\":\"e2e_test\"}";
            string serviceRequestJson         = "{\"a\":123}";
            string methodName = "MethodE2ETest";

            var          assertResult = new TaskCompletionSource <Tuple <bool, bool> >();
            DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(deviceInfo.Item2, transport);
            await deviceClient.SetMethodHandlerAsync(methodName,
                                                     (request, context) =>
            {
                assertResult.SetResult(new Tuple <bool, bool>(request.Name.Equals(methodName), request.DataAsJson.Equals(serviceRequestJson)));
                return(Task.FromResult(new MethodResponse(Encoding.UTF8.GetBytes(deviceResponseJson), 200)));
            },
                                                     null);

            await ServiceSendMethodAndVerifyResponse(deviceInfo.Item1, methodName, deviceResponseJson, serviceRequestJson, assertResult);

            // send error command
            await deviceClient.SendEventAsync(TestUtil.ComposeErrorInjectionProperties(faultType, reason, delayInSec));

            Debug.WriteLine("Drop command sent from device client.");

            // allow time for connection recovery
            await Task.Delay(TimeSpan.FromSeconds(3));

            assertResult = new TaskCompletionSource <Tuple <bool, bool> >();
            await ServiceSendMethodAndVerifyResponse(deviceInfo.Item1, methodName, deviceResponseJson, serviceRequestJson, assertResult);

            await deviceClient.CloseAsync();

            TestUtil.RemoveDevice(deviceInfo.Item1, registryManager);
        }
        async Task CleanupDeviceQueueAsync(string hostname, Device device)
        {
            await Task.Delay(TimeSpan.FromSeconds(1));

            DeviceClient deviceClient = null;

            try
            {
                deviceClient = DeviceClient.Create(
                    hostname,
                    new DeviceAuthenticationWithRegistrySymmetricKey(this.deviceId, device.Authentication.SymmetricKey.PrimaryKey));
                while (true)
                {
                    using (Client.Message message = await deviceClient.ReceiveAsync(TimeSpan.FromSeconds(2)))
                    {
                        if (message == null)
                        {
                            break;
                        }
                        if (message.LockToken != null)
                        {
                            await deviceClient.CompleteAsync(message.LockToken);
                        }
                    }
                }
            }
            finally
            {
                if (deviceClient != null)
                {
                    await deviceClient.CloseAsync();
                }
            }
        }
示例#24
0
        private static async Task Main(string[] args)
        {
            Console.WriteLine("IoT Hub Quickstarts #1 - Simulated device.");

            // This sample accepts the device connection string as a parameter, if present
            ValidateConnectionString(args);

            // Connect to the IoT hub using the MQTT protocol
            s_deviceClient = DeviceClient.CreateFromConnectionString(s_connectionString, s_transportType);

            // Set up a condition to quit the sample
            Console.WriteLine("Press control-C to exit.");
            using var cts           = new CancellationTokenSource();
            Console.CancelKeyPress += (sender, eventArgs) =>
            {
                eventArgs.Cancel = true;
                cts.Cancel();
                Console.WriteLine("Exiting...");
            };

            // Run the telemetry loop
            await SendDeviceToCloudMessagesAsync(cts.Token);

            // SendDeviceToCloudMessagesAsync is designed to run until cancellation has been explicitly requested by Console.CancelKeyPress.
            // As a result, by the time the control reaches the call to close the device client, the cancellation token source would
            // have already had cancellation requested.
            // Hence, if you want to pass a cancellation token to any subsequent calls, a new token needs to be generated.
            // For device client APIs, you can also call them without a cancellation token, which will set a default
            // cancellation timeout of 4 minutes: https://github.com/Azure/azure-iot-sdk-csharp/blob/64f6e9f24371bc40ab3ec7a8b8accbfb537f0fe1/iothub/device/src/InternalClient.cs#L1922
            await s_deviceClient.CloseAsync();

            s_deviceClient.Dispose();
            Console.WriteLine("Device simulator finished.");
        }
        public async Task DeviceClient_TokenConnectionDoubleRelease_Ok()
        {
            TestDevice testDevice = await TestDevice.GetTestDeviceAsync(Logger, DevicePrefix).ConfigureAwait(false);

            string deviceConnectionString = testDevice.ConnectionString;

            var    config   = new Configuration.IoTHub.DeviceConnectionStringParser(deviceConnectionString);
            string iotHub   = config.IoTHub;
            string deviceId = config.DeviceID;
            string key      = config.SharedAccessKey;

            SharedAccessSignatureBuilder builder = new SharedAccessSignatureBuilder()
            {
                Key        = key,
                TimeToLive = new TimeSpan(0, 10, 0),
                Target     = $"{iotHub}/devices/{WebUtility.UrlEncode(deviceId)}",
            };

            DeviceAuthenticationWithToken auth = new DeviceAuthenticationWithToken(deviceId, builder.ToSignature());

            using (DeviceClient deviceClient = DeviceClient.Create(iotHub, auth, Client.TransportType.Amqp_Tcp_Only))
            {
                Logger.Trace($"{deviceId}: Created {nameof(DeviceClient)} ID={TestLogger.IdOf(deviceClient)}");

                Logger.Trace($"{deviceId}: DeviceClient OpenAsync.");
                await deviceClient.OpenAsync().ConfigureAwait(false);

                Logger.Trace($"{deviceId}: DeviceClient SendEventAsync.");
                await deviceClient.SendEventAsync(new Client.Message(Encoding.UTF8.GetBytes("TestMessage"))).ConfigureAwait(false);

                Logger.Trace($"{deviceId}: DeviceClient CloseAsync.");
                await deviceClient.CloseAsync().ConfigureAwait(false);   // First release
            } // Second release
        }
        public static async Task RunAsync(ProvisioningDeviceClient provisioningDeviceClient, SecurityProvider security)
        {
            Console.WriteLine($"RegistrationID = {security.GetRegistrationID()}");

            Console.Write("ProvisioningClient RegisterAsync . . . ");
            DeviceRegistrationResult result = await provisioningDeviceClient.RegisterAsync().ConfigureAwait(false);

            Console.WriteLine($"{result.Status}");
            Console.WriteLine($"ProvisioningClient AssignedHub: {result.AssignedHub}; DeviceID: {result.DeviceId}");

            if (result.Status == ProvisioningRegistrationStatusType.Assigned)
            {
                X509Certificate2 certificate = (security as SecurityProviderX509).GetAuthenticationCertificate();
                Console.WriteLine($"Registration certificate thumbprint: {certificate.Thumbprint}");
                IAuthenticationMethod auth = new DeviceAuthenticationWithX509Certificate(result.DeviceId, certificate);
                using (DeviceClient iotClient = DeviceClient.Create(result.AssignedHub, auth, TransportType.Amqp))
                {
                    Console.WriteLine("DeviceClient OpenAsync.");
                    await iotClient.OpenAsync().ConfigureAwait(false);

                    Console.WriteLine("DeviceClient SendEventAsync.");
                    await iotClient.SendEventAsync(new Message(Encoding.UTF8.GetBytes("TestMessage"))).ConfigureAwait(false);

                    Console.WriteLine("DeviceClient CloseAsync.");
                    await iotClient.CloseAsync().ConfigureAwait(false);
                }
            }
        }
示例#27
0
        async Task Cleanup(DeviceClient deviceClient, ServiceClient serviceClient, RegistryManager rm, string deviceName)
        {
            if (deviceClient != null)
            {
                try
                {
                    await deviceClient.CloseAsync();
                }
                catch
                {
                    // ignore
                }
            }

            if (serviceClient != null)
            {
                await serviceClient.CloseAsync();
            }

            // wait for the connection to be closed on the Edge side
            await Task.Delay(TimeSpan.FromSeconds(20));

            if (rm != null)
            {
                await RegistryManagerHelper.RemoveDevice(deviceName, rm);

                await rm.CloseAsync();
            }
        }
        public static async Task RunSample(X509Certificate2 certificate)
        {
            using (var security = new SecurityClientX509(certificate))
                using (var transport = new ProvisioningTransportHandlerAmqp(TransportFallbackType.TcpOnly))
                {
                    ProvisioningDeviceClient provClient = ProvisioningDeviceClient.Create(s_idScope, security, transport);

                    Console.Write("ProvisioningClient RegisterAsync . . . ");
                    DeviceRegistrationResult result = await provClient.RegisterAsync();

                    Console.WriteLine($"{result.Status}");
                    Console.WriteLine($"ProvisioningClient AssignedHub: {result.AssignedHub}; DeviceID: {result.DeviceId}");

                    if (result.Status != ProvisioningRegistrationStatusType.Assigned)
                    {
                        return;
                    }

                    IAuthenticationMethod auth = new DeviceAuthenticationWithX509Certificate(result.DeviceId, certificate);
                    using (DeviceClient iotClient = DeviceClient.Create(result.AssignedHub, auth))
                    {
                        Console.WriteLine("DeviceClient OpenAsync.");
                        await iotClient.OpenAsync();

                        Console.WriteLine("DeviceClient SendEventAsync.");
                        await iotClient.SendEventAsync(new Message(Encoding.UTF8.GetBytes("TestMessage")));

                        Console.WriteLine("DeviceClient CloseAsync.");
                        await iotClient.CloseAsync();
                    }
                }
        }
        public async Task SendTelemetry(TelemetryData telemetry)
        {
            try {
#if false
                DeviceClient dc = DeviceClient.Create(iotHubUri,
                                                      new DeviceAuthenticationWithRegistrySymmetricKey(
                                                          telemetry.DeviceId,
                                                          GetDeviceKey(telemetry.DeviceId)
                                                          ));
#else
                var key = await GetDeviceKey(telemetry.DeviceId);

                DeviceClient dc = DeviceClient.CreateFromConnectionString(
                    $"HostName={iotHubUri};DeviceId={telemetry.DeviceId};SharedAccessKey={key}",
                    Microsoft.Azure.Devices.Client.TransportType.Amqp);
#endif
                var text   = JsonConvert.SerializeObject(telemetry);
                var buffer = Encoding.UTF8.GetBytes(text);
                await dc.SendEventAsync(new Microsoft.Azure.Devices.Client.Message(buffer));

                await dc.CloseAsync();
            }
            catch (Exception exp)
            {
                System.Diagnostics.Trace.WriteLine($"[SendTelemetry]{exp.Message}");
                System.Diagnostics.Trace.WriteLine($"Stack Trace: {exp.StackTrace}");
                if (exp.InnerException != null)
                {
                    System.Diagnostics.Trace.WriteLine($"      - {exp.InnerException.Message}");
                    System.Diagnostics.Trace.WriteLine($"      - {exp.InnerException.StackTrace}");
                }
                throw;
            }
        }
        private async Task InitializeAndSetupClientAsync(CancellationToken cancellationToken)
        {
            if (ShouldClientBeInitialized(s_connectionStatus))
            {
                // Allow a single thread to dispose and initialize the client instance.
                await _initSemaphore.WaitAsync(cancellationToken);

                try
                {
                    if (ShouldClientBeInitialized(s_connectionStatus))
                    {
                        _logger.LogDebug($"Attempting to initialize the client instance, current status={s_connectionStatus}");

                        // If the device client instance has been previously initialized, close and dispose it.
                        if (s_deviceClient != null)
                        {
                            try
                            {
                                await s_deviceClient.CloseAsync(cancellationToken);
                            }
                            catch (UnauthorizedException) { } // if the previous token is now invalid, this call may fail
                            s_deviceClient.Dispose();
                        }

                        s_deviceClient = DeviceClient.CreateFromConnectionString(_deviceConnectionStrings.First(), _transportType, _clientOptions);
                        s_deviceClient.SetConnectionStatusChangesHandler(ConnectionStatusChangeHandler);
                        _logger.LogDebug("Initialized the client instance.");
                    }
                }
                finally
                {
                    _initSemaphore.Release();
                }

                // Force connection now.
                // We have set the "shouldExecuteOperation" function to always try to open the connection.
                // OpenAsync() is an idempotent call, it has the same effect if called once or multiple times on the same client.
                await RetryOperationHelper.RetryTransientExceptionsAsync(
                    operationName : "OpenConnection",
                    asyncOperation : async() => await s_deviceClient.OpenAsync(cancellationToken),
                    shouldExecuteOperation : () => true,
                    logger : _logger,
                    exceptionsToBeIgnored : _exceptionsToBeIgnored,
                    cancellationToken : cancellationToken);

                _logger.LogDebug($"The client instance has been opened.");

                // You will need to subscribe to the client callbacks any time the client is initialized.
                await RetryOperationHelper.RetryTransientExceptionsAsync(
                    operationName : "SubscribeTwinUpdates",
                    asyncOperation : async() => await s_deviceClient.SetDesiredPropertyUpdateCallbackAsync(HandleTwinUpdateNotificationsAsync, cancellationToken),
                    shouldExecuteOperation : () => IsDeviceConnected,
                    logger : _logger,
                    exceptionsToBeIgnored : _exceptionsToBeIgnored,
                    cancellationToken : cancellationToken);

                _logger.LogDebug("The client has subscribed to desired property update notifications.");
            }
        }