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 List<HttpRequestMessage> SendAsyncArgCalls;
public List<HttpResponseMessage> SendAsyncResponses;
public readonly List<HttpRequestMessage> SendAsyncArgCalls;
public readonly List<HttpResponseMessage> SendAsyncResponses;
private int _sendAsyncCallCounter;

View file

@ -1,6 +1,4 @@
using System;
namespace NucuCar.Sensors.Abstractions
namespace NucuCar.Sensors.Abstractions
{
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 bool Enabled { get; set; } = false;

View file

@ -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;
}
}

View file

@ -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);
}

View file

@ -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);
}
}
}

View file

@ -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;
}

View file

@ -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);
}
}
}

View file

@ -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;
}

View file

@ -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);
}
}

View file

@ -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<string, object>()
@ -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;
}
}

View file

@ -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);
}
}
}