aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/Tango.Telemetry/Destinations/MqttTelemetryDestination.cs
blob: a37d149a10598a7424ba1cddc3061eaa998c4f87 (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
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 MqttTelemetryDestination : ExtendedObject, ITelemetryDestination
    {
        private IMqttClient _mqttClient;
        private IMqttClientOptions _mqttOptions;

        public bool Enable { get; set; } = true;
        public String Address { get; private set; }
        public int Port { get; private set; }
        public String Topic { get; set; }

        public IReadOnlyList<TelemetrySource> SupportedSources { get; private set; }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="topic">example machie/telemetry/serial number</param>
        /// <param name="address">Default localhost</param>
        /// <param name="port">Default 1883</param>
        public MqttTelemetryDestination(String topic, String address = "localhost", int port = 1883)
        {
            Topic = topic;
            Port = port;
            SupportedSources = new List<TelemetrySource>() { TelemetrySource.Streaming };
        }

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

                    String exeName = Assembly.GetEntryAssembly().GetName().FullName;
                    _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.TelemetryObject.TelemetryName()}")
                       .WithPayload(package.ToPayload())
                       .WithExactlyOnceQoS()
                       .WithRetainFlag(false)
                       .Build();

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


                await _mqttClient.PublishAsync(message);
            }
        }

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