• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

net-daemon / netdaemon / 6594659689

19 Oct 2023 05:58PM UTC coverage: 80.941% (-0.3%) from 81.222%
6594659689

push

github

web-flow
Fix alot of warnings (#956)

811 of 1148 branches covered (0.0%)

Branch coverage included in aggregate %.

28 of 28 new or added lines in 15 files covered. (100.0%)

2939 of 3485 relevant lines covered (84.33%)

50.62 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

45.61
/src/Extensions/NetDaemon.Extensions.MqttEntityManager/AssuredMqttConnection.cs
1
using System.Globalization;
2
using System.Text;
3
using Microsoft.Extensions.Logging;
4
using Microsoft.Extensions.Options;
5
using MQTTnet.Client;
6
using MQTTnet.Extensions.ManagedClient;
7
using NetDaemon.Extensions.MqttEntityManager.Exceptions;
8
using NetDaemon.Extensions.MqttEntityManager.Helpers;
9

10
namespace NetDaemon.Extensions.MqttEntityManager;
11

12
/// <summary>
13
/// Wrapper to assure an MQTT connection
14
/// </summary>
15
internal class AssuredMqttConnection : IAssuredMqttConnection, IDisposable
16
{
17
    private readonly ILogger<AssuredMqttConnection> _logger;
18
    private readonly Task _connectionTask;
19
    private IManagedMqttClient? _mqttClient;
20
    private bool _disposed;
21

22
    /// <summary>
23
    /// Wrapper to assure an MQTT connection
24
    /// </summary>
25
    /// <param name="logger"></param>
26
    /// <param name="mqttFactory"></param>
27
    /// <param name="mqttConfig"></param>
28
    public AssuredMqttConnection(
26✔
29
        ILogger<AssuredMqttConnection> logger,
26✔
30
        IMqttFactoryWrapper mqttFactory,
26✔
31
        IOptions<MqttConfiguration> mqttConfig)
26✔
32
    {
33
        _logger = logger;
26✔
34

35
        _logger.LogTrace("MQTT initiating connection");
26✔
36
        _connectionTask = Task.Run(() => ConnectAsync(mqttConfig.Value, mqttFactory));
52✔
37
    }
26✔
38

39
    /// <summary>
40
    /// Ensures that the MQTT client is available
41
    /// </summary>
42
    /// <returns></returns>
43
    /// <exception cref="MqttConnectionException">Timed out while waiting for connection</exception>
44
    public async Task<IManagedMqttClient> GetClientAsync()
45
    {
46
        await _connectionTask;
26✔
47

48
        return _mqttClient ?? throw new MqttConnectionException("Unable to create MQTT connection");
26!
49
    }
26✔
50

51
    private async Task ConnectAsync(MqttConfiguration mqttConfig, IMqttFactoryWrapper mqttFactory)
52
    {
53
        _logger.LogTrace("Connecting to MQTT broker at {Host}:{Port}/{UserName}",
26✔
54
            mqttConfig.Host, mqttConfig.Port, mqttConfig.UserName);
26✔
55

56
        var clientOptions = new ManagedMqttClientOptionsBuilder()
26✔
57
            .WithAutoReconnectDelay(TimeSpan.FromSeconds(5))
26✔
58
            .WithClientOptions(new MqttClientOptionsBuilder()
26✔
59
                .WithTcpServer(mqttConfig.Host, mqttConfig.Port)
26✔
60
                .WithCredentials(mqttConfig.UserName, mqttConfig.Password))
26✔
61
            .Build();
26✔
62

63
        _mqttClient = mqttFactory.CreateManagedMqttClient();
26✔
64

65
        _mqttClient.ConnectedAsync += MqttClientOnConnectedAsync;
26✔
66
        _mqttClient.DisconnectedAsync += MqttClientOnDisconnectedAsync;
26✔
67

68
        await _mqttClient.StartAsync(clientOptions);
26✔
69

70
        _logger.LogTrace("MQTT client is ready");
26✔
71
    }
26✔
72

73
    private Task MqttClientOnDisconnectedAsync(MqttClientDisconnectedEventArgs arg)
74
    {
75
        _logger.LogDebug("MQTT disconnected: {Reason}", BuildErrorResponse(arg));
×
76
        return Task.CompletedTask;
×
77
    }
78

79
    private Task MqttClientOnConnectedAsync(MqttClientConnectedEventArgs arg)
80
    {
81
        _logger.LogDebug("MQTT connected: {ResultCode}", arg.ConnectResult.ResultCode);
×
82
        return Task.CompletedTask;
×
83
    }
84

85
    private static string BuildErrorResponse(MqttClientDisconnectedEventArgs arg)
86
    {
87
        var sb = new StringBuilder();
×
88

89
        sb.AppendLine(CultureInfo.InvariantCulture, $"{arg.Exception?.Message} ({arg.Reason})");     // Note: arg.ReasonString is always null
×
90
        var ex = arg.Exception?.InnerException;
×
91
        while (ex != null)
×
92
        {
93
            sb.AppendLine(ex.Message);
×
94
            ex = ex.InnerException;
×
95
        }
96

97
        return sb.ToString();
×
98
    }
99

100
    public void Dispose()
101
    {
102
        if (_disposed)
×
103
            return;
×
104

105
        _disposed = true;
×
106
        _logger.LogTrace("MQTT disconnecting");
×
107
        _connectionTask?.Dispose();
×
108
        _mqttClient?.Dispose();
×
109
    }
×
110
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc