private static async Task UpdateDeviceIdInDeviceSettings(string deviceId, string environmentName)
        {
            //Get the device settings related Options
            string deviceSettingsFilePath = "devicesettings.json";

            if (!string.IsNullOrEmpty(environmentName))
            {
                deviceSettingsFilePath = $"devicesettings.{environmentName}.json";
            }

            if (!File.Exists(deviceSettingsFilePath))
            {
                throw new Exception("Device settings path not found to update the device id coming from the environment settings.");
            }

            string settingsData = File.ReadAllText(deviceSettingsFilePath);

            if (!string.IsNullOrEmpty(settingsData))
            {
                DeviceSettings settings = JsonConvert.DeserializeObject <DeviceSettings>(settingsData);

                if (settings != null)
                {
                    Console.WriteLine($"Updating the settings with the new device id: {deviceId}.");

                    settings.DeviceId         = deviceId;
                    settings.ConnectionString = string.Empty;
                    await ConfigurationHelpers.WriteDeviceSettings(settings, environmentName);

                    Console.WriteLine($"Settings updated with the new device id: {deviceId}.");
                }
            }
        }
Exemplo n.º 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}.");
            }
        }