Clean up code by applying suggestions from Rider.

This commit is contained in:
Denis-Cosmin Nutiu 2021-08-01 21:01:19 +03:00
parent 25b6005b21
commit d35464d4ac
12 changed files with 57 additions and 51 deletions

View file

@ -6,8 +6,8 @@ namespace NucuCar.Domain.Http
{ {
public class MockMinimalHttpClient : MinimalHttpClient public class MockMinimalHttpClient : MinimalHttpClient
{ {
public List<HttpRequestMessage> SendAsyncArgCalls; public readonly List<HttpRequestMessage> SendAsyncArgCalls;
public List<HttpResponseMessage> SendAsyncResponses; public readonly List<HttpResponseMessage> SendAsyncResponses;
private int _sendAsyncCallCounter; private int _sendAsyncCallCounter;

View file

@ -1,6 +1,4 @@
using System; namespace NucuCar.Sensors.Abstractions
namespace NucuCar.Sensors.Abstractions
{ {
public enum SensorStateEnum : ushort public enum SensorStateEnum : ushort
{ {

View file

@ -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 class BaseSensorConfig
{ {
public bool Enabled { get; set; } = false; public bool Enabled { get; set; } = false;

View file

@ -97,7 +97,7 @@ namespace NucuCar.Sensors.Modules.Environment
CurrentState = SensorStateEnum.Initialized; 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) catch (System.IO.IOException e)
{ {
@ -135,12 +135,12 @@ namespace NucuCar.Sensors.Modules.Environment
_lastMeasurement.Humidity = Math.Round(humidity.Percent, 2); _lastMeasurement.Humidity = Math.Round(humidity.Percent, 2);
_lastMeasurement.VolatileOrganicCompounds = Math.Round(gasResistance.Kiloohms, 2); _lastMeasurement.VolatileOrganicCompounds = Math.Round(gasResistance.Kiloohms, 2);
Logger?.LogDebug($"{DateTimeOffset.Now}:BME680: reading"); Logger?.LogDebug("{DateTime}:BME680: reading", DateTimeOffset.Now);
Logger?.LogInformation( Logger?.LogInformation(
$"temperature:{_lastMeasurement.Temperature:N2} \u00B0C|" + // ReSharper disable once TemplateIsNotCompileTimeConstantProblem
$"pressure:{_lastMeasurement.Pressure:N2} hPa|" + string.Format("temperature:{0:N2} °C|pressure:{1:N2} hPa|humidity:{2:N2} %rH|voc:{3}",
$"humidity:{_lastMeasurement.Humidity:N2} %rH|" + _lastMeasurement.Temperature, _lastMeasurement.Pressure, _lastMeasurement.Humidity,
$"voc:{_lastMeasurement.VolatileOrganicCompounds}"); _lastMeasurement.VolatileOrganicCompounds));
} }
public override string GetIdentifier() public override string GetIdentifier()
@ -175,8 +175,8 @@ namespace NucuCar.Sensors.Modules.Environment
private void HandleInitializationException(Exception e) private void HandleInitializationException(Exception e)
{ {
Logger?.LogError($"{DateTimeOffset.Now}:BME680 Sensor initialization FAIL."); Logger?.LogError("{DateTime}:BME680 Sensor initialization FAIL", DateTimeOffset.Now);
Logger?.LogDebug(e.Message); Logger?.LogDebug("{Message}", e.Message);
CurrentState = SensorStateEnum.Error; CurrentState = SensorStateEnum.Error;
} }
} }

View file

@ -59,7 +59,7 @@ namespace NucuCar.Sensors.Modules.Health
_lastTemperatureCelsius = Math.Round(_lastTemperatureCelsius, 2); _lastTemperatureCelsius = Math.Round(_lastTemperatureCelsius, 2);
} }
} }
Logger?.LogInformation($"CPU Temperature {_lastTemperatureCelsius} \u00B0C."); Logger?.LogInformation("CPU Temperature {CpuTemperature} \u00B0C", _lastTemperatureCelsius);
return Task.FromResult(_lastTemperatureCelsius); return Task.FromResult(_lastTemperatureCelsius);
} }

View file

@ -29,7 +29,7 @@ namespace NucuCar.Sensors
} }
var sensorIdentifier = Sensor.GetIdentifier(); var sensorIdentifier = Sensor.GetIdentifier();
Logger?.LogInformation($"Starting sensor worker for {sensorIdentifier}"); Logger?.LogInformation("Starting sensor worker for {SensorId}", sensorIdentifier);
try try
{ {
TelemetryPublisher?.RegisterTelemeter(Sensor); TelemetryPublisher?.RegisterTelemeter(Sensor);
@ -41,7 +41,7 @@ namespace NucuCar.Sensors
/* If sensor is ok attempt to read. */ /* If sensor is ok attempt to read. */
if (sensorState == SensorStateEnum.Initialized) if (sensorState == SensorStateEnum.Initialized)
{ {
Logger?.LogTrace($"{sensorIdentifier} is taking a measurement!"); Logger?.LogTrace("{SensorId} is taking a measurement!", sensorIdentifier);
await Sensor.TakeMeasurementAsync(); await Sensor.TakeMeasurementAsync();
} }
/* Else attempt to re-initialize. */ /* Else attempt to re-initialize. */
@ -49,7 +49,8 @@ namespace NucuCar.Sensors
sensorState == SensorStateEnum.Error) sensorState == SensorStateEnum.Error)
{ {
Logger?.LogWarning( 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; _intializationDelay += 10000;
await Task.Delay(_intializationDelay, stoppingToken); await Task.Delay(_intializationDelay, stoppingToken);
Sensor.Initialize(); Sensor.Initialize();
@ -57,7 +58,7 @@ namespace NucuCar.Sensors
else if (sensorState == SensorStateEnum.Disabled) else if (sensorState == SensorStateEnum.Disabled)
{ {
// Break from while. // Break from while.
Logger?.LogInformation($"{sensorIdentifier} has been disabled!"); Logger?.LogInformation("{SensorIdentifier} has been disabled!", sensorIdentifier);
break; break;
} }
@ -68,12 +69,13 @@ namespace NucuCar.Sensors
} }
catch (TaskCanceledException) catch (TaskCanceledException)
{ {
Logger?.LogInformation("The SensorWorker task was canceled."); Logger?.LogInformation("The SensorWorker task was canceled");
} }
catch (Exception e) catch (Exception e)
{ {
Logger?.LogError($"Unhandled exception in SensorWorker {sensorIdentifier}. {e.GetType()}: {e.Message}"); Logger?.LogError("Unhandled exception in SensorWorker {SensorId}. {Type}: {Message}",
Logger?.LogDebug(e.StackTrace); sensorIdentifier, e.GetType(), e.Message);
Logger?.LogDebug("{StackTrace}", e.StackTrace);
} }
} }
} }

View file

@ -3,7 +3,6 @@ using System.Collections.Generic;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using NucuCar.Telemetry.Publishers;
namespace NucuCar.Telemetry.Abstractions namespace NucuCar.Telemetry.Abstractions
{ {
@ -64,7 +63,7 @@ namespace NucuCar.Telemetry.Abstractions
public bool RegisterTelemeter(ITelemeter t) public bool RegisterTelemeter(ITelemeter t)
{ {
if (RegisteredTelemeters.Contains(t) || !t.IsTelemetryEnabled()) return false; if (RegisteredTelemeters.Contains(t) || !t.IsTelemetryEnabled()) return false;
Logger?.LogDebug($"Registering telemeter {t.GetIdentifier()}"); Logger?.LogDebug("Registering telemeter {Identifier}", t.GetIdentifier());
RegisteredTelemeters.Add(t); RegisteredTelemeters.Add(t);
return true; return true;
} }
@ -77,7 +76,7 @@ namespace NucuCar.Telemetry.Abstractions
public bool UnRegisterTelemeter(ITelemeter t) public bool UnRegisterTelemeter(ITelemeter t)
{ {
if (!RegisteredTelemeters.Contains(t)) return false; if (!RegisteredTelemeters.Contains(t)) return false;
Logger?.LogDebug($"UnRegistering telemeter {t.GetIdentifier()}"); Logger?.LogDebug("UnRegistering telemeter {Identifier}", t.GetIdentifier());
RegisteredTelemeters.Remove(t); RegisteredTelemeters.Remove(t);
return true; return true;
} }
@ -107,7 +106,7 @@ namespace NucuCar.Telemetry.Abstractions
var telemetryData = telemeter.GetTelemetryData(); var telemetryData = telemeter.GetTelemetryData();
if (telemetryData == null) if (telemetryData == null)
{ {
Logger?.LogWarning($"Warning! Data for {telemeter.GetIdentifier()} is null!"); Logger?.LogWarning("Warning! Data for {Identifier} is null!", telemeter.GetIdentifier());
continue; continue;
} }

View file

@ -40,7 +40,7 @@ namespace NucuCar.Telemetry.Publishers
var data = GetTelemetry(); var data = GetTelemetry();
var messageString = JsonConvert.SerializeObject(data); var messageString = JsonConvert.SerializeObject(data);
Logger?.LogDebug($"Telemetry message: {messageString}"); Logger?.LogDebug("Telemetry message: {Message}", messageString);
var message = new Message(Encoding.UTF8.GetBytes(messageString)); var message = new Message(Encoding.UTF8.GetBytes(messageString));
await PublishToCloudAsync(message, cancellationToken); await PublishToCloudAsync(message, cancellationToken);
@ -70,7 +70,7 @@ namespace NucuCar.Telemetry.Publishers
catch (OperationCanceledException) catch (OperationCanceledException)
{ {
retry += 1; retry += 1;
Logger?.LogWarning($"Telemetry not sent! Retry {retry}."); Logger?.LogWarning("Telemetry not sent! Retry attempt #{Retry}", retry);
} }
} }
} }

View file

@ -17,8 +17,7 @@ namespace NucuCar.Telemetry.Publishers
{ {
var data = GetTelemetry(); var data = GetTelemetry();
var messageString = JsonConvert.SerializeObject(data); var messageString = JsonConvert.SerializeObject(data);
Logger?.LogDebug($"Telemetry message: {messageString}"); Logger?.LogDebug("Telemetry message: {Message}", messageString);
Logger?.LogInformation(messageString);
return Task.CompletedTask; return Task.CompletedTask;
} }

View file

@ -38,8 +38,10 @@ namespace NucuCar.Telemetry.Publishers
var bufferSize = connectionStringParams.GetValueOrDefault("BufferSize", "4096"); var bufferSize = connectionStringParams.GetValueOrDefault("BufferSize", "4096");
_separator = connectionStringParams.GetValueOrDefault("Separator", ","); _separator = connectionStringParams.GetValueOrDefault("Separator", ",");
_fileStream = new FileStream(NormalizeFilename(fileName, fileExtension), FileMode.Append, FileAccess.Write, _fileStream = new FileStream(
FileShare.Read, int.Parse(bufferSize), true); NormalizeFilename(fileName, fileExtension), FileMode.Append, FileAccess.Write, FileShare.Read,
// ReSharper disable once AssignNullToNotNullAttribute
int.Parse(bufferSize), true);
Logger?.LogDebug("Initialized the TelemetryPublisherDisk!"); Logger?.LogDebug("Initialized the TelemetryPublisherDisk!");
} }
@ -47,7 +49,7 @@ namespace NucuCar.Telemetry.Publishers
{ {
var data = GetTelemetry(); var data = GetTelemetry();
var messageString = JsonConvert.SerializeObject(data); var messageString = JsonConvert.SerializeObject(data);
Logger?.LogDebug($"Telemetry message: {messageString}"); Logger?.LogDebug("Telemetry message: {Message}", messageString);
var encodedText = Encoding.UTF8.GetBytes($"{messageString}{_separator}"); var encodedText = Encoding.UTF8.GetBytes($"{messageString}{_separator}");
try try
@ -58,7 +60,7 @@ namespace NucuCar.Telemetry.Publishers
} }
catch (ObjectDisposedException e) catch (ObjectDisposedException e)
{ {
Logger.LogCritical(e.Message); Logger.LogCritical("{Message}", e.Message);
} }
} }

View file

@ -45,16 +45,16 @@ namespace NucuCar.Telemetry.Publishers
if (!options.TryGetValue("ProjectId", out var firestoreProjectId)) if (!options.TryGetValue("ProjectId", out var firestoreProjectId))
{ {
Logger?.LogCritical( Logger?.LogCritical(
$"Can't start {nameof(TelemetryPublisherFirestore)}! Malformed connection string! " + "Can't start {Name}! Malformed connection string! Missing ProjectId!",
$"Missing ProjectId!"); nameof(TelemetryPublisherFirestore));
throw new ArgumentException("Malformed connection string!"); throw new ArgumentException("Malformed connection string!");
} }
if (!options.TryGetValue("CollectionName", out var firestoreCollection)) if (!options.TryGetValue("CollectionName", out var firestoreCollection))
{ {
Logger?.LogCritical( Logger?.LogCritical(
$"Can't start {nameof(TelemetryPublisherFirestore)}! Malformed connection string! " + "Can't start {Name}! Malformed connection string! Missing CollectionName!",
$"Missing CollectionName!"); nameof(TelemetryPublisherFirestore));
throw new ArgumentException("Malformed connection string!"); throw new ArgumentException("Malformed connection string!");
} }
@ -67,14 +67,15 @@ namespace NucuCar.Telemetry.Publishers
var requestUrl = $"https://firestore.googleapis.com/v1/projects/{firestoreProjectId}/" + var requestUrl = $"https://firestore.googleapis.com/v1/projects/{firestoreProjectId}/" +
$"databases/(default)/documents/{firestoreCollection}/"; $"databases/(default)/documents/{firestoreCollection}/";
HttpClient = new MinimalHttpClient(requestUrl) {Timeout = timeout, Logger = Logger}; HttpClient = new MinimalHttpClient(requestUrl) {Timeout = timeout, Logger = Logger};
Logger?.LogInformation($"Initialized {nameof(TelemetryPublisherFirestore)}"); Logger?.LogInformation("Initialized {Name}", nameof(TelemetryPublisherFirestore));
Logger?.LogInformation($"ProjectId: {firestoreProjectId}; CollectionName: {firestoreCollection}."); Logger?.LogInformation("ProjectId: {FirestoreProjectId}; CollectionName: {FirestoreCollection}",
firestoreProjectId, firestoreCollection);
} }
private async Task SetupAuthorization() private async Task SetupAuthorization()
{ {
HttpClient.ClearAuthorizationHeader(); HttpClient.ClearAuthorizationHeader();
// https://cloud.google.com/identity-platform/docs/use-rest-api#section-sign-in-email-password // 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 requestUrl = $"https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key={_webApiKey}";
var data = new Dictionary<string, object>() var data = new Dictionary<string, object>()
@ -83,7 +84,7 @@ namespace NucuCar.Telemetry.Publishers
["password"] = _webPassword, ["password"] = _webPassword,
["returnSecureToken"] = true ["returnSecureToken"] = true
}; };
var response = await HttpClient.PostAsync(requestUrl, data); var response = await HttpClient.PostAsync(requestUrl, data);
if (response?.StatusCode == HttpStatusCode.OK) if (response?.StatusCode == HttpStatusCode.OK)
@ -98,11 +99,11 @@ namespace NucuCar.Telemetry.Publishers
} }
else else
{ {
Logger?.LogError($"Firestore authentication request failed! {response?.StatusCode}!"); Logger?.LogError("Firestore authentication request failed! {StatusCode}!", response?.StatusCode);
if (response != null) if (response != null)
{ {
var contentBody = await response.Content.ReadAsStringAsync(); 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. // ArgumentException occurs during json serialization errors.
catch (ArgumentException e) 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.Forbidden:
case HttpStatusCode.Unauthorized: 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(); await SetupAuthorization();
responseMessage = await HttpClient.PostAsync("", data); responseMessage = await HttpClient.PostAsync("", data);
if (responseMessage != null && responseMessage.IsSuccessStatusCode) if (responseMessage != null && responseMessage.IsSuccessStatusCode)
@ -163,13 +165,13 @@ namespace NucuCar.Telemetry.Publishers
} }
else else
{ {
Logger?.LogError($"Failed to publish telemetry data! {responseMessage?.StatusCode}"); Logger?.LogError("Failed to publish telemetry data! {StatusCode}", responseMessage?.StatusCode);
} }
break; break;
} }
default: default:
Logger?.LogError($"Failed to publish telemetry data! {responseMessage?.StatusCode}"); Logger?.LogError("Failed to publish telemetry data! {StatusCode}", responseMessage?.StatusCode);
break; break;
} }
} }

View file

@ -53,12 +53,12 @@ namespace NucuCar.Telemetry
} }
catch (TaskCanceledException) catch (TaskCanceledException)
{ {
_logger?.LogInformation("The TelemetryWorker task was canceled."); _logger?.LogInformation("The TelemetryWorker task was canceled");
} }
catch (Exception e) catch (Exception e)
{ {
_logger?.LogError($"Unhandled exception in TelemetryWorker. {e.Message}"); _logger?.LogError("Unhandled exception in TelemetryWorker. {Message}",e.Message);
_logger?.LogDebug(e.StackTrace); _logger?.LogDebug("{StackTrace}", e.StackTrace);
} }
} }
} }