Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add logging & estonia country code #18

Merged
merged 3 commits into from
Aug 10, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 16 additions & 3 deletions libgwmapi/GwmApiClient.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using System.Net.Http.Json;
using System.Text.Json;
using System.Text.Json.Serialization;
using Microsoft.Extensions.Logging;

namespace libgwmapi;

Expand All @@ -10,14 +11,16 @@ public partial class GwmApiClient
public static readonly string AppHttpClientName = "eu-app-gateway";
private readonly HttpClient _h5Client;
private readonly HttpClient _appClient;
private readonly ILogger<GwmApiClient> _logger;

public GwmApiClient(IHttpClientFactory factory)
: this(factory.CreateClient(H5HttpClientName), factory.CreateClient(AppHttpClientName))
public GwmApiClient(IHttpClientFactory factory, ILoggerFactory loggerFactory)
: this(factory.CreateClient(H5HttpClientName), factory.CreateClient(AppHttpClientName), loggerFactory)
{
}

public GwmApiClient(HttpClient h5Client, HttpClient appClient)
public GwmApiClient(HttpClient h5Client, HttpClient appClient, ILoggerFactory loggerFactory)
{
_logger = loggerFactory.CreateLogger<GwmApiClient>();
_h5Client = h5Client;
_h5Client.DefaultRequestHeaders.Add("rs", "2");
_h5Client.DefaultRequestHeaders.Add("terminal", "GW_APP_ORA");
Expand Down Expand Up @@ -107,13 +110,23 @@ private async Task<T> GetAppAsync<T>(string url, CancellationToken cancellationT

private async Task CheckResponseAsync(HttpResponseMessage response, CancellationToken cancellationToken)
{
if (_logger.IsEnabled(LogLevel.Trace))
{
await response.Content.LoadIntoBufferAsync();
_logger.LogTrace(await response.Content.ReadAsStringAsync(cancellationToken));
}
response.EnsureSuccessStatusCode();
var result = await response.Content.ReadFromJsonAsync<GwmResponse>(cancellationToken: cancellationToken);
CheckResponse(result);
}

private async Task<T> GetResponseAsync<T>(HttpResponseMessage response, CancellationToken cancellationToken)
{
if (_logger.IsEnabled(LogLevel.Trace))
{
await response.Content.LoadIntoBufferAsync();
_logger.LogTrace(await response.Content.ReadAsStringAsync(cancellationToken));
}
response.EnsureSuccessStatusCode();
var result = await response.Content.ReadFromJsonAsync<GwmResponse<T>>(cancellationToken: cancellationToken);
CheckResponse(result);
Expand Down
28 changes: 27 additions & 1 deletion ora2mqtt/BaseCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,28 @@
using libgwmapi;
using System.Runtime.InteropServices;
using System.Security.Cryptography.X509Certificates;
using Microsoft.Extensions.Http;
using Microsoft.Extensions.Http.Logging;
using Microsoft.Extensions.Logging;
using YamlDotNet.Serialization;

namespace ora2mqtt;

public abstract class BaseCommand
{
[Option('d', "debug", Default = false, HelpText = "enable debug logging")]
public bool Debug { get; set; }

[Option('c', "config", Default = "ora2mqtt.yml", HelpText = "path to yaml config file")]
public string ConfigFile { get; set; }

protected ILoggerFactory LoggerFactory { get; private set; }

protected void Setup()
{
LoggerFactory = Microsoft.Extensions.Logging.LoggerFactory.Create(x => x.SetMinimumLevel(Debug ? LogLevel.Trace : LogLevel.Error).AddConsole());
}

protected GwmApiClient ConfigureApiClient(Ora2MqttOptions options)
{
var certHandler = new CertificateHandler();
Expand Down Expand Up @@ -39,7 +52,20 @@ protected GwmApiClient ConfigureApiClient(Ora2MqttOptions options)
}
}

return new GwmApiClient(new HttpClient(), new HttpClient(httpHandler))
var httpLogger = LoggerFactory.CreateLogger<HttpClient>();
var httpOptions = new HttpClientFactoryOptions
{
ShouldRedactHeaderValue = x => "accessToken".Equals(x, StringComparison.InvariantCultureIgnoreCase)
};
var h5Client = new HttpClient(new LoggingHttpMessageHandler(httpLogger, httpOptions)
{
InnerHandler = new HttpClientHandler()
});
var appClient = new HttpClient(new LoggingHttpMessageHandler(httpLogger)
{
InnerHandler = httpHandler
});
return new GwmApiClient(h5Client, appClient, LoggerFactory)
{
Country = options.Country
};
Expand Down
16 changes: 11 additions & 5 deletions ora2mqtt/ConfigureCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,20 @@
using Sharprompt;
using Sharprompt.Fluent;
using YamlDotNet.Serialization;
using ora2mqtt.Logging;
using Microsoft.Extensions.Logging;

namespace ora2mqtt
{
[Verb("configure", HelpText = "run config file wizard")]
public class ConfigureCommand:BaseCommand
{
private ILogger<ConfigureCommand> _logger;

public async Task<int> Run(CancellationToken cancellationToken)
{
Setup();
_logger = LoggerFactory.CreateLogger<ConfigureCommand>();
Ora2MqttOptions config;
if (!File.Exists(ConfigFile))
{
Expand Down Expand Up @@ -57,7 +63,7 @@ private void SelectCountry(Ora2MqttOptions options)
{
options.Country = Prompt.Select<string>(o => o
.WithMessage("Please choose your country")
.WithItems(new[] { "DE", "GB" })
.WithItems(new[] { "DE", "GB", "EE" })
);
}
}
Expand All @@ -74,7 +80,7 @@ private async Task LoginAsync(GwmApiClient client, Ora2MqttOptions options, Canc
}
catch (GwmApiException e)
{
await Console.Error.WriteLineAsync($"Access token expired ({e.Message}). Trying to refresh token...");
_logger.LogError($"Access token expired ({e.Message}). Trying to refresh token...");
}
var refresh = new RefreshTokenRequest
{
Expand All @@ -92,7 +98,7 @@ private async Task LoginAsync(GwmApiClient client, Ora2MqttOptions options, Canc
}
catch (GwmApiException e)
{
await Console.Error.WriteLineAsync($"Token refresh failed: {e.Message}");
_logger.LogError($"Token refresh failed: {e.Message}");
}
}
var request = new LoginAccountRequest
Expand Down Expand Up @@ -160,7 +166,7 @@ private async Task<bool> TestMqttAsync(Ora2MqttOptions oraOptions, CancellationT

try
{
var factory = new MqttFactory();
var factory = new MqttFactory(new MqttLogger(LoggerFactory));
using var client = factory.CreateMqttClient();
var builder = new MqttClientOptionsBuilder()
.WithTcpServer(options.Host)
Expand All @@ -175,7 +181,7 @@ private async Task<bool> TestMqttAsync(Ora2MqttOptions oraOptions, CancellationT
}
catch (MqttCommunicationException ex)
{
await Console.Error.WriteLineAsync($"Mqtt connection failed: {ex.Message}");
_logger.LogError($"Mqtt connection failed: {ex.Message}");
return false;
}
return true;
Expand Down
30 changes: 30 additions & 0 deletions ora2mqtt/Logging/MqttLogger.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
using Microsoft.Extensions.Logging;
using MQTTnet.Diagnostics;

namespace ora2mqtt.Logging
{
internal class MqttLogger: IMqttNetLogger
{
private readonly ILogger<MqttLogger> _logger;

public MqttLogger(ILoggerFactory factory)
{
_logger = factory.CreateLogger<MqttLogger>();
}

public void Publish(MqttNetLogLevel logLevel, string source, string message, object[] parameters, Exception exception)
{
var level = logLevel switch
{
MqttNetLogLevel.Verbose => LogLevel.Debug,
MqttNetLogLevel.Info => LogLevel.Information,
MqttNetLogLevel.Warning => LogLevel.Warning,
MqttNetLogLevel.Error => LogLevel.Error,
_ => throw new ArgumentOutOfRangeException(nameof(logLevel))
};
_logger.Log(level, exception, message, parameters);
}

public bool IsEnabled => true;
}
}
14 changes: 2 additions & 12 deletions ora2mqtt/Program.cs
Original file line number Diff line number Diff line change
@@ -1,18 +1,8 @@
using System.Runtime.InteropServices;
using System.Security.Cryptography.X509Certificates;
using CommandLine;
using libgwmapi;
using libgwmapi.DTO.UserAuth;
using MQTTnet;
using MQTTnet.Client;
using MQTTnet.Exceptions;
using CommandLine;
using ora2mqtt;
using Sharprompt;
using Sharprompt.Fluent;
using YamlDotNet.Serialization;

using var cts = new CancellationTokenSource();
Console.CancelKeyPress += (s, e) =>
Console.CancelKeyPress += (_, e) =>
{
cts.Cancel();
e.Cancel = true;
Expand Down
13 changes: 9 additions & 4 deletions ora2mqtt/RunCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,22 +4,27 @@
using MQTTnet.Client;
using MQTTnet;
using YamlDotNet.Serialization;
using MQTTnet.Server;
using libgwmapi.DTO.UserAuth;
using Microsoft.Extensions.Logging;
using ora2mqtt.Logging;

namespace ora2mqtt;

[Verb("run", true, HelpText = "default")]
public class RunCommand:BaseCommand
{
private ILogger _logger;

[Option('i', "interval", Default = 10, HelpText = "GWM API polling interval")]
public int Intervall { get; set; }

public async Task<int> Run(CancellationToken cancellationToken)
{
Setup();
_logger = LoggerFactory.CreateLogger<RunCommand>();
if (!File.Exists(ConfigFile))
{
await Console.Error.WriteLineAsync($"config file ({ConfigFile}) missing");
_logger.LogError($"config file ({ConfigFile}) missing");
return 1;
}
Ora2MqttOptions config;
Expand Down Expand Up @@ -52,7 +57,7 @@ public async Task<int> Run(CancellationToken cancellationToken)

private async Task<IMqttClient> ConnectMqttAsync(Ora2MqttMqttOptions options,CancellationToken cancellationToken)
{
var factory = new MqttFactory();
var factory = new MqttFactory(new MqttLogger(LoggerFactory));
var client = factory.CreateMqttClient();
var builder = new MqttClientOptionsBuilder()
.WithTcpServer(options.Host)
Expand Down Expand Up @@ -91,7 +96,7 @@ private async Task RefreshTokenAsync(GwmApiClient client, Ora2MqttOptions option
}
catch (GwmApiException e)
{
await Console.Error.WriteLineAsync($"Access token expired ({e.Message}). Trying to refresh token...");
_logger.LogError($"Access token expired ({e.Message}). Trying to refresh token...");
}

var refresh = new RefreshTokenRequest
Expand Down
1 change: 1 addition & 0 deletions ora2mqtt/ora2mqtt.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

<ItemGroup>
<PackageReference Include="CommandLineParser" Version="2.9.1" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="6.0.0" />
<PackageReference Include="MQTTnet" Version="4.3.1.873" />
<PackageReference Include="Sharprompt" Version="2.4.5" />
<PackageReference Include="YamlDotNet" Version="13.7.1" />
Expand Down
Loading