-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProgram.cs
151 lines (137 loc) · 5.5 KB
/
Program.cs
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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
using Microsoft.Extensions.Configuration;
using MQTTnet;
using MQTTnet.Client.Connecting;
using MQTTnet.Client.Disconnecting;
using MQTTnet.Client.Options;
using MQTTnet.Client.Receiving;
using MQTTnet.Extensions.ManagedClient;
using MQTTnet.Formatter;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
namespace Mqtt2Sql
{
public static class Program
{
private static MqttFactory _F;
private static IManagedMqttClient _C;
private static Database _Db;
private static bool _Retained;
private static MqttClientTlsOptions MqttClientTlsOptions = new MqttClientTlsOptions
{
UseTls = false,
IgnoreCertificateChainErrors = true,
IgnoreCertificateRevocationErrors = true,
AllowUntrustedCertificates = true
};
private static MqttClientOptions GetOptions(string clientName)
{
return new MqttClientOptions
{
ClientId = clientName,
ProtocolVersion = MqttProtocolVersion.V311,
ChannelOptions = new MqttClientTcpOptions
{
Server = "192.168.1.31",
Port = 1883,
TlsOptions = MqttClientTlsOptions,
},
CleanSession = true, // Don't store up messages while we're offline.
KeepAlivePeriod = TimeSpan.FromSeconds(5),
};
}
public static void Main(string[] args)
{
bool go = true;
while (go)
{
try
{
_F = new MqttFactory();
_Db = new Database();
IConfiguration cfg = new ConfigurationBuilder()
.SetBasePath(Directory.GetParent(AppContext.BaseDirectory).FullName)
.AddJsonFile("appsettings.json", false)
.Build();
string mattServerAddress = cfg["MattServerAddress"];
string mqttClientName = cfg["MqttClientName"];
List<string> topics = cfg.GetSection("Topics").GetChildren().Select(z => z.Value).ToList();
// Receiver.
_C = _F.CreateManagedMqttClient();
//_C.UseApplicationMessageReceivedHandler(HandleReceivedApplicationMessage);
_C.ConnectedHandler = new MqttClientConnectedHandlerDelegate(OnConnected);
_C.DisconnectedHandler = new MqttClientDisconnectedHandlerDelegate(OnDisconnected);
//_C.ApplicationMessageProcessedHandler = new ApplicationMessageProcessedHandlerDelegate(MessageProcessedHandler);
_C.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(SubscriberMessageReceivedHandler);
_Retained = true; // When we connect we'll get the retained message which we'll therefore give a bollocks timestamp to.
_C.StartAsync(new ManagedMqttClientOptions { ClientOptions = GetOptions("ClientPublisher") }).Wait();
_C.SubscribeAsync(topics.Select(z => new MqttTopicFilter { Topic = z })).Wait();
while (!_C.IsConnected)
{
Console.WriteLine("Waiting for connections.");
Thread.Sleep(1000);
}
Console.WriteLine("Entering main loop; press any key to stop and quit.");
while (go)
{
Thread.Sleep(13000);
if (Console.KeyAvailable)
{
go = false;
break;
}
}
Console.WriteLine("Stopping.");
}
catch (Exception e)
{
Console.WriteLine("Bummer: " + e.Message);
}
finally
{
try
{
_Db.SaveChanges();
_C.StopAsync().Wait();
}
catch (Exception f)
{
Console.WriteLine("Error stopping: " + f.Message);
}
_Db.Dispose();
_C.Dispose();
}
}
}
private static void SubscriberMessageReceivedHandler(MqttApplicationMessageReceivedEventArgs args)
{
MqttMessage m = new MqttMessage()
{
Topic = args.ApplicationMessage.Topic,
Timestamp = DateTime.UtcNow,
Payload = args.ApplicationMessage.ConvertPayloadToString()
};
if (_Retained)
{
_Retained = false;
}
else
{
_Db.Messages.Add(m);
_Db.SaveChanges();
}
Console.WriteLine($"Timestamp: {m.Timestamp:HH:mm:ss} | Topic: {m.Topic} | Payload: {m.Payload} | QoS: {args.ApplicationMessage.QualityOfServiceLevel}");
}
private static void OnConnected(MqttClientConnectedEventArgs args)
{
Console.WriteLine("Connected");
}
private static void OnDisconnected(MqttClientDisconnectedEventArgs args)
{
_Retained = true;
Console.WriteLine("Disconnected");
}
}
}