aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/Tango.Telemetry/Destinations/TelemetryMqttDestination.cs
blob: 16b741a82660e673135de45572a7714d970353d4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
using MQTTnet.Client;
using MQTTnet.Client.Options;
using MQTTnet;
using System.Reflection;
using MQTTnet.Client.Connecting;
using Tango.Core;
using MQTTnet.Packets;

namespace Tango.Telemetry.Destinations
{
    public class TelemetryMqttDestination : ExtendedObject, ITelemetryDestination
    {
        private IMqttClient _mqttClient;
        private IMqttClientOptions _mqttOptions;
        private DateTime _nextRealAvailabilityCheck;

        public string Name { get; set; } = "MQTT";
        public String Address { get; private set; }
        public int Port { get; private set; }
        public String Topic { get; private set; }

        public IReadOnlyList<TelemetrySourceTypes> SupportedSourceTypes { get; private set; }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="topic">e.g machie/telemetry/serial number</param>
        /// <param name="address">Default localhost</param>
        /// <param name="port">Default 1883</param>
        public TelemetryMqttDestination(String topic, String address = "localhost", int port = 1883)
        {
            _nextRealAvailabilityCheck = DateTime.Now;
            Topic = topic;
            Address = address;
            Port = port;
            SupportedSourceTypes = new List<TelemetrySourceTypes>() { TelemetrySourceTypes.Streaming };
        }

        public async Task<bool> IsAvailable()
        {
            if (_mqttClient == null)
            {
                return await EnsureConnection();
            }
            else
            {
                if (DateTime.Now > _nextRealAvailabilityCheck)
                {
                    _nextRealAvailabilityCheck = DateTime.Now.AddMinutes(5);
                    return await EnsureConnection();
                }
                else
                {
                    return _mqttClient.IsConnected;
                } 
            }
        }

        private async Task<bool> EnsureConnection()
        {
            if (_mqttClient == null || !_mqttClient.IsConnected)
            {
                try
                {
                    var factory = new MqttFactory();
                    _mqttClient = factory.CreateMqttClient();

                    String exeName = Assembly.GetEntryAssembly().GetName().Name;
                    _mqttOptions = new MqttClientOptionsBuilder()
                        .WithClientId(exeName)
                        .WithTcpServer(Address, Port)
                        .WithCleanSession()
                        .Build();

                    var result = await _mqttClient.ConnectAsync(_mqttOptions);
                    if (result.ResultCode != MqttClientConnectResultCode.Success)
                    {
                        LogManager.Log(new Exception($"Error connecting to MQTT broker. {result.ResultCode}"));
                        return false;
                    }
                }
                catch (Exception ex)
                {
                    LogManager.Log(ex, "Error connecting to MQTT broker.");
                    return false;
                }
            }

            return true;
        }

        public async Task Publish(TelemetryPublishPackage package, List<KeyValuePair<String, String>> properties)
        {
            if (await EnsureConnection())
            {
                var message = new MqttApplicationMessageBuilder()
                       .WithTopic($"{Topic}/{package.PendingTelemetry.TelemetryObject.ToTelemetryName()}")
                       .WithPayload(package.ToPayload())
                       .WithExactlyOnceQoS()
                       .WithRetainFlag(false)
                       .Build();

                message.UserProperties = new List<MqttUserProperty>();

                foreach (var prop in properties)
                {
                    message.UserProperties.Add(new MqttUserProperty(prop.Key, prop.Value ?? String.Empty));
                }


                await _mqttClient.PublishAsync(message);
            }
        }

        public void Dispose()
        {
            _mqttClient?.Dispose();
        }

        public override string ToString()
        {
            return $"{Name} -> {Address}:{Port}";
        }
    }
}