public async Task InitiateSimulationAsync()
        {
            string logPrefix = "system".BuildLogPrefix();

            IoTTools.CheckModuleConnectionStringData(ModuleSettings.ConnectionString, _logger);

            // Connect to the IoT hub using the MQTT protocol

            _logger.LogDebug($"{logPrefix}::{ModuleSettings.ArtifactId}::Module client created.");

            if (SimulationSettings.EnableTwinPropertiesDesiredChangesNotifications)
            {
                await _moduleClient.SetDesiredPropertyUpdateCallbackAsync(OnDesiredPropertyChange, null);

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

            //Configuration
            if (SimulationSettings.EnableC2DDirectMethods)
            {
                //Register C2D Direct methods handlers
                await RegisterC2DDirectMethodsHandlersAsync(_moduleClient, ModuleSettings, _logger);
            }

            if (SimulationSettings.EnableC2DMessages)
            {
                //Start receiving C2D messages

                ReceiveC2DMessagesAsync(_moduleClient, ModuleSettings, _logger);
            }

            //Messages
            if (SimulationSettings.EnableTelemetryMessages)
            {
                SendDeviceToCloudMessagesAsync(_moduleClient, ModuleSettings.DeviceId, ModuleSettings.ModuleId, _logger); //interval is a global variable changed by processes
            }
            if (SimulationSettings.EnableReadingTwinProperties)
            {
                //Twins
                _logger.LogDebug($"{logPrefix}::{ModuleSettings.ArtifactId}::INITIALIZATION::Retrieving twin.");
                Twin twin = await _moduleClient.GetTwinAsync();

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

            _moduleClient.SetConnectionStatusChangesHandler(new ConnectionStatusChangesHandler(ConnectionStatusChanged));
        }
예제 #2
0
        public async Task <string> GetMessageAsync(string deviceId, string moduleId)
        {
            string logPrefix  = "SimpleErrorMessageService".BuildLogPrefix();
            string artifactId = string.IsNullOrEmpty(moduleId) ? deviceId : moduleId;

            string messageString = await GetMessageAsync();

            _logger.LogTrace($"{logPrefix}::{artifactId}::error.json file loaded.");

            messageString = IoTTools.UpdateIds(messageString, deviceId, moduleId);
            _logger.LogTrace($"{logPrefix}::{artifactId}::DeviceId and moduleId updated in the message template.");

            return(messageString);
        }
        public async Task <string> GetRandomizedMessageAsync(string deviceId, string moduleId)
        {
            string artifactId = string.IsNullOrEmpty(moduleId) ? deviceId : moduleId;

            string messageString = await this.GetMessageAsync(deviceId, moduleId);

            string logPrefix = "SimpleTelemetryMessageService".BuildLogPrefix();

            //Randomize data
            messageString = IoTTools.RandomizeData(messageString);
            _logger.LogTrace($"{logPrefix}::{artifactId}::Randomized data to update template's values before sending the message.");

            return(messageString);
        }
        public async Task <string> GetMessageAsync(string deviceId, string moduleId)
        {
            string artifactId = string.IsNullOrEmpty(moduleId) ? deviceId : moduleId;

            string logPrefix     = "SimpleTelemetryMessageService".BuildLogPrefix();
            string messageString = await GetMessageAsync();

            if (string.IsNullOrEmpty(messageString))
            {
                throw new ArgumentNullException(nameof(messageString), "DATA: The message to send is empty or not found.");
            }

            _logger.LogTrace($"{logPrefix}::{artifactId}::measureddata.json file loaded.");

            messageString = IoTTools.UpdateIds(messageString, deviceId, moduleId);
            _logger.LogTrace($"{logPrefix}::{artifactId}::DeviceId and moduleId updated in the message template.");

            return(messageString);
        }
예제 #5
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}.");
            }
        }
예제 #6
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}.");
            }
        }
        public async Task InitiateSimulationAsync()
        {
            string logPrefix = "system".BuildLogPrefix();

            try
            {
                //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(ModuleSettings.ConnectionString))
                {
                    ModuleSettings.ConnectionString = await _provisioningService.AddModuleIdentityToDevice(ModuleSettings.ModuleId);

                    if (string.IsNullOrEmpty(ModuleSettings.ConnectionString))
                    {
                        _logger.LogWarning($"{logPrefix}::{ModuleSettings.ArtifactId}::No module connection string has been created.");
                    }
                    else
                    {
                        _logger.LogDebug($"{logPrefix}::{ModuleSettings.ArtifactId}::Module connection string being persisted.");
                        await ConfigurationHelpers.WriteModulesSettings(ModuleSettings, _environmentName);
                    }
                }

                IoTTools.CheckModuleConnectionStringData(ModuleSettings.ConnectionString, _logger);

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

                if (SimulationSettings.EnableTwinPropertiesDesiredChangesNotifications)
                {
                    await _moduleClient.SetDesiredPropertyUpdateCallbackAsync(OnDesiredPropertyChange, null);

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

                //Configuration
                if (SimulationSettings.EnableC2DDirectMethods)
                {
                    //Register C2D Direct methods handlers
                    await RegisterC2DDirectMethodsHandlersAsync(_moduleClient, ModuleSettings, _logger);
                }

                if (SimulationSettings.EnableC2DMessages)
                {
                    //Start receiving C2D messages

                    ReceiveC2DMessagesAsync(_moduleClient, ModuleSettings, _logger);
                }

                //Messages
                if (SimulationSettings.EnableTelemetryMessages)
                {
                    SendDeviceToCloudMessagesAsync(_moduleClient, ModuleSettings.DeviceId, ModuleSettings.ModuleId, _logger); //interval is a global variable changed by processes
                }
                if (SimulationSettings.EnableErrorMessages)
                {
                    SendDeviceToCloudErrorAsync(_moduleClient, ModuleSettings.DeviceId, ModuleSettings.ModuleId, SimulationSettings.ErrorFrecuency, _logger);
                }

                if (SimulationSettings.EnableCommissioningMessages)
                {
                    SendDeviceToCloudCommissioningAsync(_moduleClient, ModuleSettings.DeviceId, ModuleSettings.ModuleId, SimulationSettings.CommissioningFrecuency, _logger);
                }

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

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

                _moduleClient.SetConnectionStatusChangesHandler(new ConnectionStatusChangesHandler(ConnectionStatusChanged));
            }
            catch (ConnectionStringException ex)
            {
                _logger.LogError($"{logPrefix}::{ModuleSettings.ArtifactId}::ConnectionStringException:{ex.Message}");
            }
            catch (Exception ex)
            {
                _logger.LogError($"{logPrefix}::{ModuleSettings.ArtifactId}::{ex.Message}");
            }
        }