示例#1
0
        static void Main(string[] args)
        {
            try
            {
                DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(DeviceConnectionString);

                if (deviceClient == null)
                {
                    Console.WriteLine("Failed to create DeviceClient!");
                }
                else
                {
                    SendEvent(deviceClient).Wait();
                    ReceiveCommands(deviceClient).Wait();
                }

                Console.WriteLine("Exited!\n");
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error in sample: {0}", ex.Message);
            }
        }
示例#2
0
        public async Task DeviceClient_OnMethodCalled_MethodRequestHasEmptyBody_With_SetMethodHandler()
        {
            DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(fakeConnectionString);
            var          innerHandler = Substitute.For <IDelegatingHandler>();

            deviceClient.InnerHandler = innerHandler;

            bool isMethodHandlerCalled = false;

            deviceClient.SetMethodHandler("TestMethodName", (payload, context) =>
            {
                isMethodHandlerCalled = true;
                return(Task.FromResult(new MethodResponse(Encoding.UTF8.GetBytes("{\"name\":\"ABC\"}"), 200)));
            }, "custom data");

            var methodRequestInternal = new MethodRequestInternal("TestMethodName", "4B810AFC-CF5B-4AE8-91EB-245F7C7751F9", new MemoryStream(new byte[0]));

            await deviceClient.OnMethodCalled(methodRequestInternal);

            await innerHandler.Received().SendMethodResponseAsync(Arg.Any <MethodResponseInternal>(), Arg.Any <CancellationToken>());

            Assert.IsTrue(isMethodHandlerCalled);
        }
        private static void Main(string[] args)
        {
            Console.WriteLine("IoT Hub Quickstarts #1 - Simulated device. Ctrl-C to exit.\n");

            var deviceId = Environment.GetEnvironmentVariable("DEVICE_ID");

            if (deviceId != null)
            {
                s_deviceId = deviceId;
            }

            var pushInvalidData = Environment.GetEnvironmentVariable("PUSH_INVALID_DATA");

            if (pushInvalidData != null)
            {
                PushInvalidData = bool.Parse(pushInvalidData);
            }

            // Connect to the IoT hub using the MQTT protocol
            s_deviceClient = DeviceClient.CreateFromConnectionString(s_connectionString, s_deviceId, TransportType.Mqtt);
            SendDeviceToCloudMessagesAsync();
            Console.ReadLine();
        }
        private void StartSimulation()
        {
            // set true the switch for launch simulation
            isSimulationInProgress = true;

            foreach (DeviceEntity device in listOfDevices)
            {
                try
                {
                    // Connect to the IoT hub using the device's ConnectionString MQTT protocol
                    DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(device.ConnectionString,
                                                                                        Microsoft.Azure.Devices.Client.TransportType.Mqtt);

                    // send a message to cloud
                    SendD2CMessages_Async(deviceClient, device.Id);
                }
                catch (Exception ex)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine(ex.Message);
                }
            }
        }
示例#5
0
        private static void Main(string[] args)
        {
            Console.WriteLine("Device Simulation");
            Console.WriteLine("This app simulations Temperature and Humidity sensors from the following devices:");
            Console.WriteLine(" - Container: The shipping container.");
            Console.WriteLine(" - Truck: The truck transporting the container.");
            Console.WriteLine(" - Airplain: The airplane transporting the container.");
            Console.WriteLine(string.Empty);
            Console.WriteLine("The Container is being shipped via Truck and Airplain, and the container sensor readings will vary depending on which transport vehicle is currently transporting the container.");
            Console.WriteLine(string.Empty);
            Console.WriteLine("Press Ctrl-C to exit.");
            Console.WriteLine(string.Empty);

            // Connect to the IoT hub using the MQTT protocol
            // Create a DeviceClient for each IoT Device being simulated
            deviceClient_Truck     = DeviceClient.CreateFromConnectionString(connectionString_Truck, TransportType.Mqtt);
            deviceClient_Airplane  = DeviceClient.CreateFromConnectionString(connectionString_Airplane, TransportType.Mqtt);
            deviceClient_Container = DeviceClient.CreateFromConnectionString(connectionString_Container, TransportType.Mqtt);

            SendDeviceToCloudMessagesAsync();

            Console.ReadLine();
        }
        /// <summary>
        /// A sample to illustrate how to upload files from a device.
        /// </summary>
        /// <param name="args">
        /// Run with `--help` to see a list of required and optional parameters.
        /// </param>
        /// <returns></returns>
        public static async Task <int> Main(string[] args)
        {
            // Parse application parameters
            Parameters parameters            = null;
            ParserResult <Parameters> result = Parser.Default.ParseArguments <Parameters>(args)
                                               .WithParsed(parsedParams =>
            {
                parameters = parsedParams;
            })
                                               .WithNotParsed(errors =>
            {
                Environment.Exit(1);
            });

            using var deviceClient = DeviceClient.CreateFromConnectionString(
                      parameters.PrimaryConnectionString,
                      parameters.TransportType);
            var sample = new FileUploadSample(deviceClient);
            await sample.RunSampleAsync();

            Console.WriteLine("Done.");
            return(0);
        }
示例#7
0
        public static async Task <int> MainAsync()
        {
            IConfiguration configuration = new ConfigurationBuilder()
                                           .AddJsonFile("config/dev.json", optional: true)
                                           .AddEnvironmentVariables()
                                           .Build();

            connectionString   = configuration.GetValue <string>("deviceConnectionString");
            deviceClient       = DeviceClient.CreateFromConnectionString(connectionString, mqttTransport);
            IoTHubModuleClient = await ModuleClient.CreateFromEnvironmentAsync(settings);

            await IoTHubModuleClient.OpenAsync();

            Console.WriteLine("Command handler started!");

            HandleCommandMessages();

            // listenForCommands(); //basically forked
            await UntilCancelled().Task;


            return(0);
        }
示例#8
0
        static async Task SimulateDeviceAsync(string deviceName, string connectionString)
        {
            var deviceClient = DeviceClient.CreateFromConnectionString(connectionString);

            while (true)
            {
                double currentTemperature = avgTemperature + rand.NextDouble() * 4 - 3;
                double currentHumidity    = avgHumidity + rand.NextDouble() * 4 - 3;

                var telemetryMessage = new
                {
                    Temperature = currentTemperature,
                    Humidity    = currentHumidity
                };

                var messageString = JsonConvert.SerializeObject(telemetryMessage);
                var message       = new Message(Encoding.ASCII.GetBytes(messageString));
                await deviceClient.SendEventAsync(message);

                Console.WriteLine("{0} > Sending message for Device {1}: {2}", DateTime.Now, deviceName, messageString);
                await Task.Delay(5000);
            }
        }
        private async Task Twin_ServiceSetsDesiredPropertyAndDeviceReceivesItOnNextGet(Client.TransportType transport)
        {
            var propName  = Guid.NewGuid().ToString();
            var propValue = Guid.NewGuid().ToString();

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

            using (RegistryManager registryManager = RegistryManager.CreateFromConnectionString(Configuration.IoTHub.ConnectionString))
                using (DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(testDevice.ConnectionString, transport))
                {
                    var twinPatch = new Twin();
                    twinPatch.Properties.Desired[propName] = propValue;
                    await registryManager.UpdateTwinAsync(testDevice.Id, twinPatch, "*").ConfigureAwait(false);

                    var deviceTwin = await deviceClient.GetTwinAsync().ConfigureAwait(false);

                    Assert.AreEqual <string>(deviceTwin.Properties.Desired[propName].ToString(), propValue);

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

                    await registryManager.CloseAsync().ConfigureAwait(false);
                }
        }
示例#10
0
        private async Task Twin_DeviceSetsReportedPropertyAndServiceReceivesIt(Client.TransportType transport)
        {
            var propName  = Guid.NewGuid().ToString();
            var propValue = Guid.NewGuid().ToString();

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

            using (RegistryManager registryManager = RegistryManager.CreateFromConnectionString(Configuration.IoTHub.ConnectionString))
                using (DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(testDevice.ConnectionString, transport))
                {
                    var patch = new TwinCollection();
                    patch[propName] = propValue;
                    await deviceClient.UpdateReportedPropertiesAsync(patch).ConfigureAwait(false);

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

                    var serviceTwin = await registryManager.GetTwinAsync(testDevice.Id).ConfigureAwait(false);

                    Assert.AreEqual <string>(serviceTwin.Properties.Reported[propName].ToString(), propValue);

                    _log.WriteLine("verified " + serviceTwin.Properties.Reported[propName].ToString() + "=" + propValue);
                }
        }
示例#11
0
        private async Task sendMethodAndRespondWithObseletedSetMethodHandler(Client.TransportType transport)
        {
            Tuple <string, string> deviceInfo = TestUtil.CreateDevice(DevicePrefix, hostName, registryManager);
            var assertResult = new TaskCompletionSource <Tuple <bool, bool> >();
            var deviceClient = DeviceClient.CreateFromConnectionString(deviceInfo.Item2, transport);

            deviceClient?.SetMethodHandler(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);

            // sleep to ensure async tasks started in SetMethodHandler has completed
            Thread.Sleep(5000);

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

            await deviceClient.CloseAsync();

            TestUtil.RemoveDevice(deviceInfo.Item1, registryManager);
        }
示例#12
0
        public MainPage()
        {
            this.InitializeComponent();


            try
            {
                Task.Run(async() =>
                {
                    string myConnectionDevice = "HostName=gabp2017.azure-devices.net;DeviceId=TestDevice;SharedAccessKey=3bG0qc+rxpaIyNT8ckCzM1BWJFRav+29mfGimdM7kig=";
                    DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(myConnectionDevice);

                    StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Images/GAB.png"));
                    var fileName     = file.Name;
                    using (Windows.Storage.Streams.IRandomAccessStreamWithContentType stream = await file.OpenReadAsync())
                        await deviceClient.UploadToBlobAsync(fileName, stream.AsStream());
                }).Wait();
            }
            catch (Exception ex)
            {
                var a = ex;
            }
        }
示例#13
0
        private async Task Twin_ClientHandlesRejectionInvalidPropertyName(Client.TransportType transport)
        {
            var propName1 = "$" + Guid.NewGuid().ToString();
            var propName2 = Guid.NewGuid().ToString();

            TestDevice testDevice = await TestDevice.GetTestDeviceAsync(DevicePrefix).ConfigureAwait(false);
            RegistryManager registryManager = RegistryManager.CreateFromConnectionString(Configuration.IoTHub.ConnectionString);
            
            using (var deviceClient = DeviceClient.CreateFromConnectionString(testDevice.ConnectionString, transport))
            {
                var exceptionThrown = false;
                try
                {
                    await deviceClient.UpdateReportedPropertiesAsync(new TwinCollection
                    {
                        [propName1] = 123,
                        [propName2] = "abcd"
                    }).ConfigureAwait(false);
                }
                catch (Exception)
                {
                    exceptionThrown = true;
                }

                if (!exceptionThrown)
                {
                    throw new AssertFailedException("Exception was expected, but not thrown.");
                }

                var serviceTwin = await registryManager.GetTwinAsync(testDevice.Id).ConfigureAwait(false);
                Assert.IsFalse(serviceTwin.Properties.Reported.Contains(propName1));

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

            await registryManager.CloseAsync().ConfigureAwait(false);
        }
示例#14
0
        /// <summary>
        /// Initializes the DeviceClient and sets up the callback to receive
        /// messages containing temperature information
        /// </summary>
        static async Task Init(string connectionString, bool bypassCertVerification = false)
        {
            Console.WriteLine("Connection String {0}", connectionString);

            MqttTransportSettings mqttSetting = new MqttTransportSettings(TransportType.Mqtt_Tcp_Only);

            // During dev you might want to bypass the cert verification. It is highly recommended to verify certs systematically in production
            if (bypassCertVerification)
            {
                mqttSetting.RemoteCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;
            }
            ITransportSettings[] settings = { mqttSetting };

            // Open a connection to the Edge runtime
            DeviceClient ioTHubModuleClient = DeviceClient.CreateFromConnectionString(connectionString, settings);
            await ioTHubModuleClient.OpenAsync();

            Console.WriteLine("IoT Hub module client initialized.");

            var moduleTwin = await ioTHubModuleClient.GetTwinAsync();

            var moduleTwinCollection = moduleTwin.Properties.Desired;

            if (moduleTwinCollection["fall"] != null)
            {
                fall = moduleTwinCollection["fall"];
            }

            await ioTHubModuleClient.SetDesiredPropertyUpdateCallbackAsync(onDesiredPropertiesUpdate, null);

            while (true)
            {
                await SendAccelMessage(ioTHubModuleClient);

                Thread.Sleep(500);
            }
        }
示例#15
0
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            if (GpioControllerPresent && GpioController.GetDefault() != null)
            {
                _pin4 = GpioController.GetDefault().OpenPin(4, GpioSharingMode.Exclusive);

                _dht1 = new Dht22(_pin4, GpioPinDriveMode.Input);
                if (readSensor2)
                {
                    _dht2  = new Dht11(_pin17, GpioPinDriveMode.Input);
                    _pin17 = GpioController.GetDefault().OpenPin(17, GpioSharingMode.Exclusive);
                }
                _timer.Start();
                _startedAt = DateTimeOffset.Now;
                Task.Delay(1000);
                storageTimer.Start();
            }
            else
            {
                Humi2.Text = "no sensor found.";
            }
            //if(!deviceClient...) say: regiser your device.

            var    resources         = ResourceLoader.GetForCurrentView("Resources");
            var    blobStorageKey    = resources.GetString("BlobStorageKey");
            string storageConnection = "DefaultEndpointsProtocol=https;AccountName=envirodata;AccountKey=" + blobStorageKey;
            //string storageConnection = "***replace with your azure connection string***";

            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(storageConnection);
            CloudBlobClient     blobClient     = storageAccount.CreateCloudBlobClient();

            container = blobClient.GetContainerReference("default"); // container name = sensorId - from Alljoyn (create container in Azure if not exists)

            DeviceConnectionString = "DeviceId=" + sensorID + ";" + resources.GetString("IotHubCS");
            deviceClient           = DeviceClient.CreateFromConnectionString(DeviceConnectionString);
        }
        public async Task <Twin> SetModelId(string deviceConnectionString, string deviceModelId)
        {
            Twin twin  = null;
            int  retry = 10;

            var options = new ClientOptions
            {
                ModelId = deviceModelId,
            };

            if (_deviceClient == null)
            {
                _deviceClient = DeviceClient.CreateFromConnectionString(deviceConnectionString, Microsoft.Azure.Devices.Client.TransportType.Mqtt, options);
                _deviceClient.SetConnectionStatusChangesHandler(ConnectionStatusChangedHandler);
                await _deviceClient.OpenAsync();

                while (_isConnected == false && retry > 0)
                {
                    await Task.Delay(1000);

                    retry--;
                }

                twin = await _deviceClient.GetTwinAsync();
            }
            else
            {
                twin = await _deviceClient.GetTwinAsync();

                await _deviceClient.CloseAsync();

                _deviceClient.Dispose();
                _deviceClient = null;
            }

            return(twin);
        }
        /// <summary>
        /// Initializes the DeviceClient and sets up the callback to receive
        /// messages containing temperature information
        /// </summary>
        static async Task Init(string connectionString, bool bypassCertVerification = false)
        {
            Console.WriteLine("Connection String {0}", connectionString);

            MqttTransportSettings mqttSetting = new MqttTransportSettings(TransportType.Mqtt_Tcp_Only);

            // During dev you might want to bypass the cert verification. It is highly recommended to verify certs systematically in production
            if (bypassCertVerification)
            {
                mqttSetting.RemoteCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;
            }
            ITransportSettings[] settings = { mqttSetting };

            // Open a connection to the Edge runtime
            DeviceClient ioTHubModuleClient = DeviceClient.CreateFromConnectionString(connectionString, settings);
            await ioTHubModuleClient.OpenAsync();

            Console.WriteLine("IoT Hub module client initialized.");

            // Register callback to be called when a message is received by the module
            //await ioTHubModuleClient.SetInputMessageHandlerAsync("input1", PipeMessage, ioTHubModuleClient);
            var moduleTwin = await ioTHubModuleClient.GetTwinAsync();

            var moduleTwinCollection = moduleTwin.Properties.Desired;

            // process received module twin setup data
            processDesiredPropertiesUpdate(moduleTwinCollection, ioTHubModuleClient);

            // Attach callback for Twin desired properties updates
            await ioTHubModuleClient.SetDesiredPropertyUpdateCallbackAsync(onDesiredPropertiesUpdate, null);

            // Register callback to be called when a message is received by the module
            await ioTHubModuleClient.SetInputMessageHandlerAsync("input1", PacketForwarderHostMessages, ioTHubModuleClient);

            // Direct method handler to reset (recycle) the packet forwarder
            //await ioTHubModuleClient.SetMethodHandlerAsync("Reset", resetHandler, packetForwarderProcess);
        }
示例#18
0
        static async Task Main(string[] args)
        {
            Console.WriteLine("Initializing Band Agent...");

            var device = DeviceClient.CreateFromConnectionString(DeviceConnectionString);
            await device.OpenAsync();

            var twinProperties = new TwinCollection();

            twinProperties["connectionType"]     = "wi-fi";
            twinProperties["connectionStrength"] = "weak";

            await device.UpdateReportedPropertiesAsync(twinProperties);

            //var count = 1;
            //while (true)
            //{
            //    var telemetry = new Telemetry
            //    {
            //        Message = "Sending complex object...",
            //        StatusCode = count++
            //    };

            //    var telemetryJson = JsonConvert.SerializeObject(telemetry);

            //    var message = new Message(Encoding.ASCII.GetBytes(telemetryJson));
            //    await device.SendEventAsync(message);

            //    Console.WriteLine("Message sent to the cloud!");

            //    Thread.Sleep(2000);
            //}

            Console.WriteLine("Device is connected!");
            Console.WriteLine("Press any key to exit...");
            Console.ReadKey();
        }
示例#19
0
        /// <summary>
        /// Initializes the Azure IoT Client for the Edge Module
        /// </summary>
        static async Task InitEdgeModule()
        {
            try
            {
                // Open a connection to the Edge runtime using MQTT transport and
                // the connection string provided as an environment variable
                string connectionString = Environment.GetEnvironmentVariable("EdgeHubConnectionString");

                MqttTransportSettings mqttSettings = new MqttTransportSettings(TransportType.Mqtt_Tcp_Only);
                // Suppress cert validation on Windows for now
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    mqttSettings.RemoteCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;
                }
                ITransportSettings[] settings = { mqttSettings };

                DeviceClient ioTHubModuleClient = DeviceClient.CreateFromConnectionString(connectionString, settings);
                await ioTHubModuleClient.OpenAsync();

                Console.WriteLine("IoT Hub module client initialized.");

                // Read config from Twin and Start
                Twin moduleTwin = await ioTHubModuleClient.GetTwinAsync();
                await UpdateStartFromTwin(moduleTwin.Properties.Desired, ioTHubModuleClient);

                // Attach callback for Twin desired properties updates
                await ioTHubModuleClient.SetDesiredPropertyUpdateCallbackAsync(OnDesiredPropertiesUpdate, ioTHubModuleClient);
            }
            catch (AggregateException ex)
            {
                foreach (Exception exception in ex.InnerExceptions)
                {
                    Console.WriteLine();
                    Console.WriteLine("Error when initializing module: {0}", exception);
                }
            }
        }
示例#20
0
        public async void Receive_C2D_NotSubscribed_OfflineSingleMessage_ShouldThrow()
        {
            // 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();

                // 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);
            }
        }
示例#21
0
        static void Main(string[] args)
        {
            try
            {
                MqttTransportSettings mqttSetting = new MqttTransportSettings(TransportType.Mqtt_Tcp_Only);
                mqttSetting.RemoteCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) =>
                {
                    return(true);
                };
                mqttSetting.PublishToServerQoS = DotNetty.Codecs.Mqtt.Packets.QualityOfService.AtLeastOnce;

                ITransportSettings[] settings = new MqttTransportSettings[1];
                settings[0] = mqttSetting;
                DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(DeviceConnectionString, settings);

                deviceClient.OpenAsync().Wait();
                SendEvent(deviceClient).Wait();
                ReceiveCommands(deviceClient).Wait();

                Console.WriteLine("Exited!");
            }
            catch (AggregateException ex)
            {
                foreach (Exception exception in ex.InnerExceptions)
                {
                    Console.WriteLine();
                    Console.WriteLine("Error in sample: {0}", exception);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine();
                Console.WriteLine("Error in sample: {0}", ex.Message);
            }
            Console.WriteLine("Press enter to exit...");
            Console.ReadLine();
        }
示例#22
0
        private static TimeSpan s_telemetryInterval = TimeSpan.FromSeconds(1); // Seconds

        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);

            // Create a handler for the direct method call
            await s_deviceClient.SetMethodHandlerAsync("SetTelemetryInterval", SetTelemetryInterval, null);

            // 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.");
        }
示例#23
0
        /// <summary>
        /// Initializes the DeviceClient and sets up the callback to receive
        /// messages containing temperature information
        /// </summary>
        static async Task Init(string connectionString, bool bypassCertVerification = false)
        {
            Console.WriteLine("Connection String {0}", connectionString);

            var mqttSetting = new MqttTransportSettings(TransportType.Mqtt_Tcp_Only);

            // During dev you might want to bypass the cert verification. It is highly recommended to verify certs systematically in production
            if (bypassCertVerification)
            {
                mqttSetting.RemoteCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;
            }
            ITransportSettings[] settings = { mqttSetting };

            // Open a connection to the Edge runtime
            var ioTHubModuleClient = DeviceClient.CreateFromConnectionString(connectionString, settings);
            await ioTHubModuleClient.OpenAsync();

            Console.WriteLine("IoT Hub module client initialized.");

            var moduleTwin = await ioTHubModuleClient.GetTwinAsync();

            var moduleTwinCollection = moduleTwin.Properties.Desired;

            desiredPropertiesData = new DesiredPropertiesData(moduleTwinCollection);

            // callback for updating desired properties through the portal or rest api
            await ioTHubModuleClient.SetDesiredPropertyUpdateCallbackAsync(OnDesiredPropertiesUpdate, null);

            // this direct method will allow to reset the temperature sensor values back to their initial state
            await ioTHubModuleClient.SetMethodHandlerAsync("reset", ResetMethod, null);

            // we don't pass ioTHubModuleClient as we're not sending any messages out to the message bus
            await ioTHubModuleClient.SetInputMessageHandlerAsync("control", ControlMessageHandler, null);

            // as this runs in a loop we don't await
            SendSimulationData(ioTHubModuleClient);
        }
        private void CreateDeviceClient()
        {
            if (deviceClient == null)
            {
                try
                {
                    string partConnection      = createIoTHubConnectionString();
                    string deviceConnectionStr = $"{partConnection}DeviceId={DevEUI};SharedAccessKey={PrimaryKey}";

                    deviceClient = DeviceClient.CreateFromConnectionString(deviceConnectionStr, TransportType.Amqp_Tcp_Only);



                    //we set the retry only when sending msgs
                    setRetry(false);

                    //if the server disconnects dispose the deviceclient and new one will be created when a new d2c msg comes in.
                    deviceClient.SetConnectionStatusChangesHandler((status, reason) =>
                    {
                        if (status == ConnectionStatus.Disconnected)
                        {
                            //if (deviceClient != null)
                            //{
                            //    deviceClient.Dispose();
                            //    deviceClient = null;
                            //}
                            //todo ronnie should we log the closing of the connection?
                            //Logger.Log(DevEUI, $"connection closed by the server",Logger.LoggingLevel.Info);
                        }
                    });
                }
                catch (Exception ex)
                {
                    Logger.Log(DevEUI, $"could not create IoT Hub DeviceClient with error: {ex.Message}", Logger.LoggingLevel.Error);
                }
            }
        }
        internal async Task SendSingleMessage(Client.TransportType transport)
        {
            TestDevice testDevice = await TestDevice.GetTestDeviceAsync(DevicePrefix).ConfigureAwait(false);

            EventHubClient   eventHubClient;
            EventHubReceiver eventHubReceiver = CreateEventHubReceiver(testDevice.Id, out eventHubClient);
            var deviceClient = DeviceClient.CreateFromConnectionString(testDevice.ConnectionString, transport);

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

                string         payload;
                string         p1Value;
                Client.Message testMessage = ComposeD2CTestMessage(out payload, out p1Value);
                await deviceClient.SendEventAsync(testMessage).ConfigureAwait(false);

                bool      isReceived = false;
                Stopwatch sw         = new Stopwatch();
                sw.Start();
                while (!isReceived && sw.Elapsed.Minutes < 1)
                {
                    var events = await eventHubReceiver.ReceiveAsync(int.MaxValue, TimeSpan.FromSeconds(5)).ConfigureAwait(false);

                    isReceived = VerifyTestMessage(events, testDevice.Id, payload, p1Value);
                }
                sw.Stop();

                Assert.IsTrue(isReceived, "Message is not received.");
            }
            finally
            {
                await deviceClient.CloseAsync().ConfigureAwait(false);

                await eventHubReceiver.CloseAsync().ConfigureAwait(false);
            }
        }
        //private static TransportType s_transportType = TransportType.Mqtt;
        //private static TransportType s_transportType = TransportType.Amqp_WebSocket_Only;
        //private static TransportType s_transportType = TransportType.Mqtt_WebSocket_Only;

        public static int Main(string[] args)
        {
            Console.WriteLine("Starting Device");
            if (string.IsNullOrEmpty(s_deviceConnectionString) && args.Length > 0)
            {
                s_deviceConnectionString = args[0];
            }

            if (string.IsNullOrEmpty(s_deviceConnectionString))
            {
                s_deviceConnectionString = AzureConnections.MyConnections.DeviceConnectionString;

                if (string.IsNullOrEmpty(s_deviceConnectionString))
                {
                    Console.WriteLine("Please provide a device connection string");
                    Console.WriteLine("Usage: DeviceClientC2DStreamingSample [iotHubDeviceConnString]");
                    return(1);
                }
            }

            using (DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(s_deviceConnectionString, s_transportType))
            {
                if (deviceClient == null)
                {
                    Console.WriteLine("Failed to create DeviceClient!");
                    return(1);
                }

                var sample = new DeviceStreamSample(deviceClient);
                sample.RunSampleAsync().GetAwaiter().GetResult();
            }

            Console.WriteLine("Done Device.\n\nPress any key to finish.");
            Console.ReadKey();

            return(0);
        }
        public async Task RunDeviceAsync()
        {
            deviceClient = DeviceClient.CreateFromConnectionString(connectionString,
                                                                   TransportType.Mqtt, new ClientOptions {
                ModelId = modelId
            });

            tempSensor = new PnPComponent(deviceClient, "tempSensor1", logger);
            diag       = new PnPComponent(deviceClient, "diag");
            deviceInfo = new PnPComponent(deviceClient, "deviceInfo");
            sdkInfo    = new PnPComponent(deviceClient, "sdkInfo");

            await deviceInfo.ReportPropertyCollectionAsync(DeviceInfo.ThisDeviceInfo.ToDictionary());

            await sdkInfo.ReportPropertyCollectionAsync(SdkInformation.ThisSdkInfo);

            await diag.SetPnPCommandHandlerAsync("reboot", Diag_RebootCommandHadler, this);

            await tempSensor.SetPnPDesiredPropertyHandlerAsync <double>("targetTemperature", tempSensor_tergetTemperature_UpdateHandler, this);

            var targetTemperature = await tempSensor.ReadDesiredPropertyAsync <double>("targetTemperature");

            await this.ProcessTempUpdateAsync(targetTemperature);

            await Task.Run(async() =>
            {
                logger.LogWarning("Entering Device Loop");
                while (!quitSignal.IsCancellationRequested)
                {
                    await tempSensor.SendTelemetryValueAsync(JsonConvert.SerializeObject(new { temperature = CurrentTemperature }));
                    await diag.SendTelemetryValueAsync(JsonConvert.SerializeObject(new { workingSet = Environment.WorkingSet }));

                    logger.LogInformation("Sending workingset and temp " + CurrentTemperature);
                    await Task.Delay(5000);
                }
            });
        }
示例#28
0
        public async Task InitAsync(string host, int port,
                                    string deviceConnStr,
                                    DesiredPropertyUpdateCallback desiredPropertyUpdateCallback,
                                    string currentDeviceid = "modbusdevice")
        {
            modbusClient = new ModbusClient(host, port);
            deviceId     = currentDeviceid;
            try
            {
                modbusClient.Init();
                modbusClientAlive = true;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[EXCEPTION] Exception while instantiating Modbus client: {ex.Message}");
                Environment.Exit(-1);
            }

            deviceClient = DeviceClient.CreateFromConnectionString(deviceConnStr);
            var twin = await deviceClient.GetTwinAsync();

            if (twin.Properties.Desired["pollingInterval"] != PoolingInterval)
            {
                Console.WriteLine("[DEBUG] Setting new pollingInterval: " +
                                  $"{twin.Properties.Desired["pollingInterval"]} seconds");
                try
                {
                    PoolingInterval = twin.Properties.Desired["pollingInterval"];
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"[EXCEPTION] Unable to set pollingInterval: {ex.Message}");
                }
            }

            await deviceClient.SetDesiredPropertyUpdateCallbackAsync(desiredPropertyUpdateCallback, null);
        }
示例#29
0
        public async Task CheckInitializeDeviceClient()
        {
            //Close Connection if expired..
            try
            {
                if (DateTimeOffset.Now.Ticks > _expiryTime.Ticks)
                {
                    if (_deviceClient != null)
                    {
                        try
                        {
                            await _deviceClient.CloseAsync();
                        }
                        catch
                        {
                        }
                        _deviceClient = null;
                    }
                }
            }
            catch
            {
            }

            //Create New Client if needed..
            if (_deviceClient == null)
            {
                try
                {
                    _deviceClient = DeviceClient.CreateFromConnectionString(_connectionString);
                    _expiryTime   = DateTimeOffset.Now.AddSeconds(240);
                }
                catch
                {
                }
            }
        }
示例#30
0
        private async Task _Twin_ServiceSetsDesiredPropertyAndDeviceReceivesEvent_WithObseleteCallbackSetter(Client.TransportType transport)
        {
            var tcs       = new TaskCompletionSource <bool>();
            var propName  = Guid.NewGuid().ToString();
            var propValue = Guid.NewGuid().ToString();

            Tuple <string, string> deviceInfo = TestUtil.CreateDevice(DevicePrefix, hostName, registryManager);
            var deviceClient = DeviceClient.CreateFromConnectionString(deviceInfo.Item2, transport);
            await deviceClient.SetDesiredPropertyUpdateCallback((patch, context) =>
            {
                return(Task.Run(() =>
                {
                    try
                    {
                        Assert.AreEqual(patch[propName].ToString(), propValue);
                    }
                    catch (Exception e)
                    {
                        tcs.SetException(e);
                    }
                    finally
                    {
                        tcs.SetResult(true);
                    }
                }));
            }, null);

            var twinPatch = new Twin();

            twinPatch.Properties.Desired[propName] = propValue;
            await registryManager.UpdateTwinAsync(deviceInfo.Item1, twinPatch, "*");

            await tcs.Task;
            await deviceClient.CloseAsync();

            TestUtil.RemoveDevice(deviceInfo.Item1, registryManager);
        }