示例#1
0
        public async Task InitiateSimulationAsync()
        {
            string logPrefix = "system".BuildLogPrefix();

            try
            {
                IoTTools.CheckDeviceConnectionStringData(_deviceSettings.ConnectionString, _logger);

                // Connect to the IoT hub using the MQTT protocol
                _deviceClient = DeviceClient.CreateFromConnectionString(_deviceSettings.ConnectionString, Microsoft.Azure.Devices.Client.TransportType.Mqtt);
                _logger.LogDebug($"{logPrefix}::{_deviceSettings.ArtifactId}::Device client created.");

                if (_simulationSettings.EnableTwinPropertiesDesiredChangesNotifications)
                {
                    await _deviceClient.SetDesiredPropertyUpdateCallbackAsync(OnDesiredPropertyChange, null);

                    _logger.LogDebug($"{logPrefix}::{_deviceSettings.ArtifactId}::Twin Desired Properties update callback handler registered.");
                }

                //Configuration
                if (_simulationSettings.EnableC2DDirectMethods)
                {
                    //Register C2D Direct methods handlers
                    await RegisterC2DDirectMethodsHandlersAsync();
                }

                if (_simulationSettings.EnableC2DMessages)
                {
                    //Start receiving C2D messages
                    ReceiveC2DMessagesAsync();
                }

                //Messages
                if (_simulationSettings.EnableLatencyTests)
                {
                    SendDeviceToCloudLatencyTestAsync(_deviceId, _simulationSettings.LatencyTestsFrecuency);
                }

                if (_simulationSettings.EnableTelemetryMessages)
                {
                    SendDeviceToCloudMessagesAsync(_deviceId); //interval is a global variable changed by processes
                }
                if (_simulationSettings.EnableErrorMessages)
                {
                    SendDeviceToCloudErrorAsync(_deviceId, _simulationSettings.ErrorFrecuency);
                }

                if (_simulationSettings.EnableCommissioningMessages)
                {
                    SendDeviceToCloudCommissioningAsync(_deviceId, _simulationSettings.CommissioningFrecuency);
                }

                if (_simulationSettings.EnableReadingTwinProperties)
                {
                    //Twins
                    _logger.LogDebug($"{logPrefix}::{_deviceSettings.ArtifactId}::INITIALIZATION::Retrieving twin.");
                    Twin twin = await _deviceClient.GetTwinAsync();

                    if (twin != null)
                    {
                        _logger.LogDebug($"{logPrefix}::{_deviceSettings.ArtifactId}::INITIALIZATION::Device twin: {JsonConvert.SerializeObject(twin, Formatting.Indented)}.");
                    }
                    else
                    {
                        _logger.LogDebug($"{logPrefix}::{_deviceSettings.ArtifactId}::INITIALIZATION::No device twin.");
                    }
                }

                if (_simulationSettings.EnableFileUpload)
                {
                    throw new NotImplementedException("File upload feature has not been implemented yet.");
                }

                _deviceClient.SetConnectionStatusChangesHandler(new ConnectionStatusChangesHandler(ConnectionStatusChanged));
            }
            catch (Exception ex)
            {
                _logger.LogError($"{logPrefix}::{_deviceSettings.ArtifactId}::ERROR::InitiateSimulationAsync:{ex.Message}.");
            }
        }
示例#2
0
        public async Task InitiateSimulationAsync()
        {
            string logPrefix = "system".BuildLogPrefix();


            //Connectivity tests
            //Control if a connection string exists (ideally, stored in TPM/HSM or any secured location.
            //If there is no connection string, check if the DPS settings are provided.
            //If so, provision the device and persist the connection string for upcoming boots.
            if (string.IsNullOrEmpty(_deviceSettingsDelegate.CurrentValue.ConnectionString))
            {
                string connectionString = await _provisioningService.ProvisionDevice();

                if (!string.IsNullOrEmpty(connectionString))
                {
                    _deviceSettingsDelegate.CurrentValue.ConnectionString = connectionString;
                }
                else
                {
                    throw new Exception($"{logPrefix}::{_deviceSettingsDelegate.CurrentValue.ArtifactId}::An issue occured during the provisioning process or the connetion string building process.");
                }

                _logger.LogWarning($"{logPrefix}::{_deviceSettingsDelegate.CurrentValue.ArtifactId}::Device connection string being persisted.");
                await ConfigurationHelpers.WriteDeviceSettings(_deviceSettingsDelegate.CurrentValue, _environmentName);
            }

            //At this stage, the connection string should be set properly and the device client should be able to communicate with the IoT Hub with no issues.
            try
            {
                IoTTools.CheckDeviceConnectionStringData(_deviceSettingsDelegate.CurrentValue.ConnectionString, _logger);

                // Connect to the IoT hub using the MQTT protocol
                if (_dpsSettings.GroupEnrollment != null)
                {
                    if (_dpsSettings.GroupEnrollment.SecurityType == SecurityType.SymmetricKey)
                    {
                        _deviceClient = DeviceClient.CreateFromConnectionString(
                            _deviceSettingsDelegate.CurrentValue.ConnectionString,
                            _dpsSettings.GroupEnrollment.SymmetricKeySettings.TransportType);
                    }
                    else if (_dpsSettings.GroupEnrollment.SecurityType == SecurityType.X509CA)
                    {
                        string           deviceCertificateFullPath         = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, _dpsSettings.GroupEnrollment.CAX509Settings.DeviceX509Path);
                        X509Certificate2 deviceLeafProvisioningCertificate = new X509Certificate2(deviceCertificateFullPath, _dpsSettings.GroupEnrollment.CAX509Settings.Password);

                        IAuthenticationMethod auth = new DeviceAuthenticationWithX509Certificate(_deviceSettingsDelegate.CurrentValue.DeviceId, deviceLeafProvisioningCertificate);

                        _deviceClient = DeviceClient.Create(_deviceSettingsDelegate.CurrentValue.HostName, auth, _dpsSettings.GroupEnrollment.CAX509Settings.TransportType);
                    }
                    else
                    {
                        _logger.LogError($"{logPrefix}::{_deviceSettingsDelegate.CurrentValue.ArtifactId}::Feature not implemented.");
                    }

                    _logger.LogDebug($"{logPrefix}::{_deviceSettingsDelegate.CurrentValue.ArtifactId}::Device client created.");

                    if (_simulationSettings.EnableTwinPropertiesDesiredChangesNotifications)
                    {
                        await _deviceClient.SetDesiredPropertyUpdateCallbackAsync(OnDesiredPropertyChange, null);

                        _logger.LogDebug($"{logPrefix}::{_deviceSettingsDelegate.CurrentValue.ArtifactId}::Twin Desired Properties update callback handler registered.");
                    }

                    //Configuration
                    if (_simulationSettings.EnableC2DDirectMethods)
                    {
                        //Register C2D Direct methods handlers
                        await RegisterC2DDirectMethodsHandlersAsync();
                    }

                    if (_simulationSettings.EnableC2DMessages)
                    {
                        //Start receiving C2D messages
                        ReceiveC2DMessagesAsync();
                    }

                    //Messages
                    if (_simulationSettings.EnableLatencyTests)
                    {
                        SendDeviceToCloudLatencyTestAsync(_deviceSettingsDelegate.CurrentValue.DeviceId, _simulationSettings.LatencyTestsFrecuency);
                    }

                    if (_simulationSettings.EnableTelemetryMessages)
                    {
                        SendDeviceToCloudMessagesAsync(_deviceSettingsDelegate.CurrentValue.DeviceId); //interval is a global variable changed by processes
                    }
                    if (_simulationSettings.EnableErrorMessages)
                    {
                        SendDeviceToCloudErrorAsync(_deviceSettingsDelegate.CurrentValue.DeviceId, _simulationSettings.ErrorFrecuency);
                    }

                    if (_simulationSettings.EnableCommissioningMessages)
                    {
                        SendDeviceToCloudCommissioningAsync(_deviceSettingsDelegate.CurrentValue.DeviceId, _simulationSettings.CommissioningFrecuency);
                    }

                    if (_simulationSettings.EnableReadingTwinProperties)
                    {
                        //Twins
                        _logger.LogDebug($"{logPrefix}::{_deviceSettingsDelegate.CurrentValue.ArtifactId}::INITIALIZATION::Retrieving twin.");
                        Twin twin = await _deviceClient.GetTwinAsync();

                        if (twin != null)
                        {
                            _logger.LogDebug($"{logPrefix}::{_deviceSettingsDelegate.CurrentValue.ArtifactId}::INITIALIZATION::Device twin: {JsonConvert.SerializeObject(twin, Formatting.Indented)}.");
                        }
                        else
                        {
                            _logger.LogDebug($"{logPrefix}::{_deviceSettingsDelegate.CurrentValue.ArtifactId}::INITIALIZATION::No device twin.");
                        }
                    }

                    if (_simulationSettings.EnableFileUpload)
                    {
                        throw new NotImplementedException("File upload feature has not been implemented yet.");
                    }

                    _deviceClient.SetConnectionStatusChangesHandler(new ConnectionStatusChangesHandler(ConnectionStatusChanged));
                }
                else
                {
                    _logger.LogWarning($"{logPrefix}::{_deviceSettingsDelegate.CurrentValue.ArtifactId}::No enrollment group has been found.");
                }
            }
            catch (Exception ex)
            {
                _logger.LogError($"{logPrefix}::{_deviceSettingsDelegate.CurrentValue.ArtifactId}::ERROR::InitiateSimulationAsync:{ex.Message}.");
            }
        }