diff --git a/NucuCar.Domain/Http/MockMinimalHttpClient.cs b/NucuCar.Domain/Http/MockMinimalHttpClient.cs index 58f8a09..4faa11d 100644 --- a/NucuCar.Domain/Http/MockMinimalHttpClient.cs +++ b/NucuCar.Domain/Http/MockMinimalHttpClient.cs @@ -6,8 +6,8 @@ namespace NucuCar.Domain.Http { public class MockMinimalHttpClient : MinimalHttpClient { - public List SendAsyncArgCalls; - public List SendAsyncResponses; + public readonly List SendAsyncArgCalls; + public readonly List SendAsyncResponses; private int _sendAsyncCallCounter; diff --git a/NucuCar.Sensors/Abstractions/SensorStatecs.cs b/NucuCar.Sensors/Abstractions/SensorStatecs.cs index 7f14757..97ee462 100644 --- a/NucuCar.Sensors/Abstractions/SensorStatecs.cs +++ b/NucuCar.Sensors/Abstractions/SensorStatecs.cs @@ -1,6 +1,4 @@ -using System; - -namespace NucuCar.Sensors.Abstractions +namespace NucuCar.Sensors.Abstractions { public enum SensorStateEnum : ushort { diff --git a/NucuCar.Sensors/BaseSensorConfig.cs b/NucuCar.Sensors/BaseSensorConfig.cs index b9bd647..5f22122 100644 --- a/NucuCar.Sensors/BaseSensorConfig.cs +++ b/NucuCar.Sensors/BaseSensorConfig.cs @@ -1,5 +1,9 @@ -namespace NucuCar.Sensors +using System.Diagnostics.CodeAnalysis; + +namespace NucuCar.Sensors { + [SuppressMessage("ReSharper", "RedundantDefaultMemberInitializer")] + [SuppressMessage("ReSharper", "AutoPropertyCanBeMadeGetOnly.Global")] public class BaseSensorConfig { public bool Enabled { get; set; } = false; diff --git a/NucuCar.Sensors/Modules/Environment/Bme680Sensor.cs b/NucuCar.Sensors/Modules/Environment/Bme680Sensor.cs index 8b1d02c..628418a 100644 --- a/NucuCar.Sensors/Modules/Environment/Bme680Sensor.cs +++ b/NucuCar.Sensors/Modules/Environment/Bme680Sensor.cs @@ -97,7 +97,7 @@ namespace NucuCar.Sensors.Modules.Environment CurrentState = SensorStateEnum.Initialized; - Logger?.LogInformation($"{DateTimeOffset.Now}:BME680 Sensor initialization OK."); + Logger?.LogInformation("{DateTime}:BME680 Sensor initialization OK", DateTimeOffset.Now); } catch (System.IO.IOException e) { @@ -135,12 +135,12 @@ namespace NucuCar.Sensors.Modules.Environment _lastMeasurement.Humidity = Math.Round(humidity.Percent, 2); _lastMeasurement.VolatileOrganicCompounds = Math.Round(gasResistance.Kiloohms, 2); - Logger?.LogDebug($"{DateTimeOffset.Now}:BME680: reading"); + Logger?.LogDebug("{DateTime}:BME680: reading", DateTimeOffset.Now); Logger?.LogInformation( - $"temperature:{_lastMeasurement.Temperature:N2} \u00B0C|" + - $"pressure:{_lastMeasurement.Pressure:N2} hPa|" + - $"humidity:{_lastMeasurement.Humidity:N2} %rH|" + - $"voc:{_lastMeasurement.VolatileOrganicCompounds}"); + // ReSharper disable once TemplateIsNotCompileTimeConstantProblem + string.Format("temperature:{0:N2} °C|pressure:{1:N2} hPa|humidity:{2:N2} %rH|voc:{3}", + _lastMeasurement.Temperature, _lastMeasurement.Pressure, _lastMeasurement.Humidity, + _lastMeasurement.VolatileOrganicCompounds)); } public override string GetIdentifier() @@ -175,8 +175,8 @@ namespace NucuCar.Sensors.Modules.Environment private void HandleInitializationException(Exception e) { - Logger?.LogError($"{DateTimeOffset.Now}:BME680 Sensor initialization FAIL."); - Logger?.LogDebug(e.Message); + Logger?.LogError("{DateTime}:BME680 Sensor initialization FAIL", DateTimeOffset.Now); + Logger?.LogDebug("{Message}", e.Message); CurrentState = SensorStateEnum.Error; } } diff --git a/NucuCar.Sensors/Modules/Health/CpuTempSensor.cs b/NucuCar.Sensors/Modules/Health/CpuTempSensor.cs index 74eecfc..e24567b 100644 --- a/NucuCar.Sensors/Modules/Health/CpuTempSensor.cs +++ b/NucuCar.Sensors/Modules/Health/CpuTempSensor.cs @@ -59,7 +59,7 @@ namespace NucuCar.Sensors.Modules.Health _lastTemperatureCelsius = Math.Round(_lastTemperatureCelsius, 2); } } - Logger?.LogInformation($"CPU Temperature {_lastTemperatureCelsius} \u00B0C."); + Logger?.LogInformation("CPU Temperature {CpuTemperature} \u00B0C", _lastTemperatureCelsius); return Task.FromResult(_lastTemperatureCelsius); } diff --git a/NucuCar.Sensors/SensorWorker.cs b/NucuCar.Sensors/SensorWorker.cs index 57bac78..34b951e 100644 --- a/NucuCar.Sensors/SensorWorker.cs +++ b/NucuCar.Sensors/SensorWorker.cs @@ -29,7 +29,7 @@ namespace NucuCar.Sensors } var sensorIdentifier = Sensor.GetIdentifier(); - Logger?.LogInformation($"Starting sensor worker for {sensorIdentifier}"); + Logger?.LogInformation("Starting sensor worker for {SensorId}", sensorIdentifier); try { TelemetryPublisher?.RegisterTelemeter(Sensor); @@ -41,7 +41,7 @@ namespace NucuCar.Sensors /* If sensor is ok attempt to read. */ if (sensorState == SensorStateEnum.Initialized) { - Logger?.LogTrace($"{sensorIdentifier} is taking a measurement!"); + Logger?.LogTrace("{SensorId} is taking a measurement!", sensorIdentifier); await Sensor.TakeMeasurementAsync(); } /* Else attempt to re-initialize. */ @@ -49,7 +49,8 @@ namespace NucuCar.Sensors sensorState == SensorStateEnum.Error) { Logger?.LogWarning( - $"{sensorIdentifier} is in {sensorState}! Attempting to re-initialize in {_intializationDelay}ms."); + "{SensorId} is in {SensorState}! Attempting to re-initialize in {InitDelay}ms", + sensorIdentifier, sensorState, _intializationDelay); _intializationDelay += 10000; await Task.Delay(_intializationDelay, stoppingToken); Sensor.Initialize(); @@ -57,7 +58,7 @@ namespace NucuCar.Sensors else if (sensorState == SensorStateEnum.Disabled) { // Break from while. - Logger?.LogInformation($"{sensorIdentifier} has been disabled!"); + Logger?.LogInformation("{SensorIdentifier} has been disabled!", sensorIdentifier); break; } @@ -68,12 +69,13 @@ namespace NucuCar.Sensors } catch (TaskCanceledException) { - Logger?.LogInformation("The SensorWorker task was canceled."); + Logger?.LogInformation("The SensorWorker task was canceled"); } catch (Exception e) { - Logger?.LogError($"Unhandled exception in SensorWorker {sensorIdentifier}. {e.GetType()}: {e.Message}"); - Logger?.LogDebug(e.StackTrace); + Logger?.LogError("Unhandled exception in SensorWorker {SensorId}. {Type}: {Message}", + sensorIdentifier, e.GetType(), e.Message); + Logger?.LogDebug("{StackTrace}", e.StackTrace); } } } diff --git a/NucuCar.Telemetry/Abstractions/TelemetryPublisher.cs b/NucuCar.Telemetry/Abstractions/TelemetryPublisher.cs index 61919da..a662715 100644 --- a/NucuCar.Telemetry/Abstractions/TelemetryPublisher.cs +++ b/NucuCar.Telemetry/Abstractions/TelemetryPublisher.cs @@ -3,7 +3,6 @@ using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; -using NucuCar.Telemetry.Publishers; namespace NucuCar.Telemetry.Abstractions { @@ -64,7 +63,7 @@ namespace NucuCar.Telemetry.Abstractions public bool RegisterTelemeter(ITelemeter t) { if (RegisteredTelemeters.Contains(t) || !t.IsTelemetryEnabled()) return false; - Logger?.LogDebug($"Registering telemeter {t.GetIdentifier()}"); + Logger?.LogDebug("Registering telemeter {Identifier}", t.GetIdentifier()); RegisteredTelemeters.Add(t); return true; } @@ -77,7 +76,7 @@ namespace NucuCar.Telemetry.Abstractions public bool UnRegisterTelemeter(ITelemeter t) { if (!RegisteredTelemeters.Contains(t)) return false; - Logger?.LogDebug($"UnRegistering telemeter {t.GetIdentifier()}"); + Logger?.LogDebug("UnRegistering telemeter {Identifier}", t.GetIdentifier()); RegisteredTelemeters.Remove(t); return true; } @@ -107,7 +106,7 @@ namespace NucuCar.Telemetry.Abstractions var telemetryData = telemeter.GetTelemetryData(); if (telemetryData == null) { - Logger?.LogWarning($"Warning! Data for {telemeter.GetIdentifier()} is null!"); + Logger?.LogWarning("Warning! Data for {Identifier} is null!", telemeter.GetIdentifier()); continue; } diff --git a/NucuCar.Telemetry/Publishers/TelemetryPublisherAzure.cs b/NucuCar.Telemetry/Publishers/TelemetryPublisherAzure.cs index edbc9c8..853e1f1 100644 --- a/NucuCar.Telemetry/Publishers/TelemetryPublisherAzure.cs +++ b/NucuCar.Telemetry/Publishers/TelemetryPublisherAzure.cs @@ -40,7 +40,7 @@ namespace NucuCar.Telemetry.Publishers var data = GetTelemetry(); var messageString = JsonConvert.SerializeObject(data); - Logger?.LogDebug($"Telemetry message: {messageString}"); + Logger?.LogDebug("Telemetry message: {Message}", messageString); var message = new Message(Encoding.UTF8.GetBytes(messageString)); await PublishToCloudAsync(message, cancellationToken); @@ -70,7 +70,7 @@ namespace NucuCar.Telemetry.Publishers catch (OperationCanceledException) { retry += 1; - Logger?.LogWarning($"Telemetry not sent! Retry {retry}."); + Logger?.LogWarning("Telemetry not sent! Retry attempt #{Retry}", retry); } } } diff --git a/NucuCar.Telemetry/Publishers/TelemetryPublisherConsole.cs b/NucuCar.Telemetry/Publishers/TelemetryPublisherConsole.cs index 06c9671..c35c954 100644 --- a/NucuCar.Telemetry/Publishers/TelemetryPublisherConsole.cs +++ b/NucuCar.Telemetry/Publishers/TelemetryPublisherConsole.cs @@ -17,8 +17,7 @@ namespace NucuCar.Telemetry.Publishers { var data = GetTelemetry(); var messageString = JsonConvert.SerializeObject(data); - Logger?.LogDebug($"Telemetry message: {messageString}"); - Logger?.LogInformation(messageString); + Logger?.LogDebug("Telemetry message: {Message}", messageString); return Task.CompletedTask; } diff --git a/NucuCar.Telemetry/Publishers/TelemetryPublisherDisk.cs b/NucuCar.Telemetry/Publishers/TelemetryPublisherDisk.cs index df04ab1..34220cb 100644 --- a/NucuCar.Telemetry/Publishers/TelemetryPublisherDisk.cs +++ b/NucuCar.Telemetry/Publishers/TelemetryPublisherDisk.cs @@ -38,8 +38,10 @@ namespace NucuCar.Telemetry.Publishers var bufferSize = connectionStringParams.GetValueOrDefault("BufferSize", "4096"); _separator = connectionStringParams.GetValueOrDefault("Separator", ","); - _fileStream = new FileStream(NormalizeFilename(fileName, fileExtension), FileMode.Append, FileAccess.Write, - FileShare.Read, int.Parse(bufferSize), true); + _fileStream = new FileStream( + NormalizeFilename(fileName, fileExtension), FileMode.Append, FileAccess.Write, FileShare.Read, + // ReSharper disable once AssignNullToNotNullAttribute + int.Parse(bufferSize), true); Logger?.LogDebug("Initialized the TelemetryPublisherDisk!"); } @@ -47,7 +49,7 @@ namespace NucuCar.Telemetry.Publishers { var data = GetTelemetry(); var messageString = JsonConvert.SerializeObject(data); - Logger?.LogDebug($"Telemetry message: {messageString}"); + Logger?.LogDebug("Telemetry message: {Message}", messageString); var encodedText = Encoding.UTF8.GetBytes($"{messageString}{_separator}"); try @@ -58,7 +60,7 @@ namespace NucuCar.Telemetry.Publishers } catch (ObjectDisposedException e) { - Logger.LogCritical(e.Message); + Logger.LogCritical("{Message}", e.Message); } } diff --git a/NucuCar.Telemetry/Publishers/TelemetryPublisherFirestore.cs b/NucuCar.Telemetry/Publishers/TelemetryPublisherFirestore.cs index e256e04..6980789 100644 --- a/NucuCar.Telemetry/Publishers/TelemetryPublisherFirestore.cs +++ b/NucuCar.Telemetry/Publishers/TelemetryPublisherFirestore.cs @@ -45,16 +45,16 @@ namespace NucuCar.Telemetry.Publishers if (!options.TryGetValue("ProjectId", out var firestoreProjectId)) { Logger?.LogCritical( - $"Can't start {nameof(TelemetryPublisherFirestore)}! Malformed connection string! " + - $"Missing ProjectId!"); + "Can't start {Name}! Malformed connection string! Missing ProjectId!", + nameof(TelemetryPublisherFirestore)); throw new ArgumentException("Malformed connection string!"); } if (!options.TryGetValue("CollectionName", out var firestoreCollection)) { Logger?.LogCritical( - $"Can't start {nameof(TelemetryPublisherFirestore)}! Malformed connection string! " + - $"Missing CollectionName!"); + "Can't start {Name}! Malformed connection string! Missing CollectionName!", + nameof(TelemetryPublisherFirestore)); throw new ArgumentException("Malformed connection string!"); } @@ -67,14 +67,15 @@ namespace NucuCar.Telemetry.Publishers var requestUrl = $"https://firestore.googleapis.com/v1/projects/{firestoreProjectId}/" + $"databases/(default)/documents/{firestoreCollection}/"; HttpClient = new MinimalHttpClient(requestUrl) {Timeout = timeout, Logger = Logger}; - Logger?.LogInformation($"Initialized {nameof(TelemetryPublisherFirestore)}"); - Logger?.LogInformation($"ProjectId: {firestoreProjectId}; CollectionName: {firestoreCollection}."); + Logger?.LogInformation("Initialized {Name}", nameof(TelemetryPublisherFirestore)); + Logger?.LogInformation("ProjectId: {FirestoreProjectId}; CollectionName: {FirestoreCollection}", + firestoreProjectId, firestoreCollection); } private async Task SetupAuthorization() { HttpClient.ClearAuthorizationHeader(); - + // https://cloud.google.com/identity-platform/docs/use-rest-api#section-sign-in-email-password var requestUrl = $"https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key={_webApiKey}"; var data = new Dictionary() @@ -83,7 +84,7 @@ namespace NucuCar.Telemetry.Publishers ["password"] = _webPassword, ["returnSecureToken"] = true }; - + var response = await HttpClient.PostAsync(requestUrl, data); if (response?.StatusCode == HttpStatusCode.OK) @@ -98,11 +99,11 @@ namespace NucuCar.Telemetry.Publishers } else { - Logger?.LogError($"Firestore authentication request failed! {response?.StatusCode}!"); + Logger?.LogError("Firestore authentication request failed! {StatusCode}!", response?.StatusCode); if (response != null) { var contentBody = await response.Content.ReadAsStringAsync(); - Logger?.LogDebug(contentBody); + Logger?.LogDebug("{Body}", contentBody); } } } @@ -142,7 +143,7 @@ namespace NucuCar.Telemetry.Publishers // ArgumentException occurs during json serialization errors. catch (ArgumentException e) { - Logger?.LogWarning(e.Message); + Logger?.LogWarning("{Message}", e.Message); } @@ -154,7 +155,8 @@ namespace NucuCar.Telemetry.Publishers case HttpStatusCode.Forbidden: case HttpStatusCode.Unauthorized: { - Logger?.LogError($"Failed to publish telemetry data! {responseMessage.StatusCode}. Retrying..."); + Logger?.LogError("Failed to publish telemetry data! {StatusCode}. Retrying...", + responseMessage.StatusCode); await SetupAuthorization(); responseMessage = await HttpClient.PostAsync("", data); if (responseMessage != null && responseMessage.IsSuccessStatusCode) @@ -163,13 +165,13 @@ namespace NucuCar.Telemetry.Publishers } else { - Logger?.LogError($"Failed to publish telemetry data! {responseMessage?.StatusCode}"); + Logger?.LogError("Failed to publish telemetry data! {StatusCode}", responseMessage?.StatusCode); } break; } default: - Logger?.LogError($"Failed to publish telemetry data! {responseMessage?.StatusCode}"); + Logger?.LogError("Failed to publish telemetry data! {StatusCode}", responseMessage?.StatusCode); break; } } diff --git a/NucuCar.Telemetry/TelemetryWorker.cs b/NucuCar.Telemetry/TelemetryWorker.cs index 7f18ed0..01bfebc 100644 --- a/NucuCar.Telemetry/TelemetryWorker.cs +++ b/NucuCar.Telemetry/TelemetryWorker.cs @@ -53,12 +53,12 @@ namespace NucuCar.Telemetry } catch (TaskCanceledException) { - _logger?.LogInformation("The TelemetryWorker task was canceled."); + _logger?.LogInformation("The TelemetryWorker task was canceled"); } catch (Exception e) { - _logger?.LogError($"Unhandled exception in TelemetryWorker. {e.Message}"); - _logger?.LogDebug(e.StackTrace); + _logger?.LogError("Unhandled exception in TelemetryWorker. {Message}",e.Message); + _logger?.LogDebug("{StackTrace}", e.StackTrace); } } }