Skip to content

Commit

Permalink
add debug logging
Browse files Browse the repository at this point in the history
  • Loading branch information
zivillian committed May 30, 2024
1 parent 2749164 commit d9f6fa9
Show file tree
Hide file tree
Showing 6 changed files with 74 additions and 23 deletions.
23 changes: 22 additions & 1 deletion ora2mqtt/BaseCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,27 @@
using libgwmapi;
using System.Runtime.InteropServices;
using System.Security.Cryptography.X509Certificates;
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 +51,16 @@ protected GwmApiClient ConfigureApiClient(Ora2MqttOptions options)
}
}

return new GwmApiClient(new HttpClient(), new HttpClient(httpHandler))
var httpLogger = LoggerFactory.CreateLogger<HttpClient>();
var h5Client = new HttpClient(new LoggingHttpMessageHandler(httpLogger)
{
InnerHandler = new HttpClientHandler()
});
var appClient = new HttpClient(new LoggingHttpMessageHandler(httpLogger)
{
InnerHandler = httpHandler
});
return new GwmApiClient(h5Client, appClient)
{
Country = options.Country
};
Expand Down
16 changes: 10 additions & 6 deletions ora2mqtt/ConfigureCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,20 @@
using Sharprompt;
using Sharprompt.Fluent;
using YamlDotNet.Serialization;
using System.Runtime.InteropServices;
using System.Security.Cryptography.X509Certificates;
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 @@ -76,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 @@ -94,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 +164,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 @@ -174,7 +178,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 @@ -90,7 +95,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

0 comments on commit d9f6fa9

Please sign in to comment.