forked from Ken98045/On-Guard
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MQTTPublish.cs
252 lines (212 loc) · 7.4 KB
/
MQTTPublish.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
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SAAI.Properties;
using MQTTnet.Client;
using MQTTnet.Client.Connecting;
using MQTTnet.Client.Disconnecting;
using MQTTnet.Client.Publishing;
using MQTTnet.Client.Options;
using MQTTnet.Client.Receiving;
using MQTTnet.Client.Subscribing;
using MQTTnet.Client.Unsubscribing;
using MQTTnet;
using System.Threading;
using System.IO;
namespace SAAI
{
public class MQTTPublish : IDisposable
{
static MqttClient s_client;
static ManualResetEvent s_ready = new ManualResetEvent(false);
private bool disposedValue;
static private int _retryDelay = 0;
static MQTTPublish()
{
#pragma warning disable CS4014
CreateClient();
#pragma warning restore CS4014
}
public static async Task CreateClient()
{
var factory = new MqttFactory();
s_client = (MqttClient)factory.CreateMqttClient();
await Connect();
}
public static async Task Publish(string camera, AreaOfInterest area, Frame frame)
{
string baseTopic = Settings.Default.MQTTMotionTopic;
baseTopic = baseTopic.Replace("{Camera}", camera);
baseTopic = baseTopic.Replace("{Area}", area.AOIName);
baseTopic = baseTopic.Replace("{Motion}", "on");
foreach (InterestingObject io in frame.Interesting)
{
string topic = baseTopic;
topic = topic.Replace("{Object}", io.FoundObject.Label);
string payload = Settings.Default.MQTTMotionPayload;
payload = payload.Replace("{File}", frame.Item.PendingFile);
payload = payload.Replace("{Confidence}", ((int) (io.FoundObject.Confidence * 100.0)).ToString());
payload = payload.Replace("{Image}", LoadImage(frame.Item.PendingFile));
payload = payload.Replace("{Object}", io.FoundObject.Label);
payload = payload.Replace("{Motion}", "on");
await Publish(topic, payload).ConfigureAwait(false);
}
}
public static async Task Publish(string topic, string payload)
{
s_ready.WaitOne(10000); // wait for the first connection attempt to complete (one way or the other) since the connection process is async
int connectTryCount = 0;
while (connectTryCount < 2 && !s_client.IsConnected)
{
Dbg.Write("MQTTPublish - Client NotConnected");
await Connect().ConfigureAwait(false);
connectTryCount++;
Task.Delay(1000 * 2);
}
if (s_client.IsConnected == false)
{
Dbg.Write("MQTTPublish - Client NotConnected");
}
else
{
var message = new MqttApplicationMessageBuilder()
.WithTopic(topic)
.WithPayload(payload)
.WithExactlyOnceQoS()
.WithRetainFlag()
.Build();
await s_client.PublishAsync(message).ConfigureAwait(false);
}
}
public static async Task Connect()
{
string clientId = "OnGuard";
string mqttURI = Settings.Default.MQTTServerAddress;
string mqttUser = Settings.Default.MQTTUser;
string mqttPassword = Settings.Default.MQTTPassword;
int mqttPort = Settings.Default.MQTTPort;
bool mqttSecure = Settings.Default.MQTTUseSecureLink;
var messageBuilder = new MqttClientOptionsBuilder()
.WithClientId(clientId)
.WithCredentials(mqttUser, mqttPassword)
.WithTcpServer(mqttURI, mqttPort)
.WithCleanSession();
var options = mqttSecure
? messageBuilder
.WithTls()
.Build()
: messageBuilder
.Build();
_ = s_client.UseDisconnectedHandler(async e =>
{
Dbg.Write("MQTTPublish - Server Disconnected");
if (_retryDelay > 0)
{
await Task.Delay(TimeSpan.FromSeconds(5)).ConfigureAwait(false);
}
_retryDelay = 5;
try
{
MqttClientAuthenticateResult disconnectRetryResult = await s_client.ConnectAsync(options).ConfigureAwait(false);
if (disconnectRetryResult.ResultCode != MqttClientConnectResultCode.Success)
{
HandleError(disconnectRetryResult);
}
else
{
Dbg.Write("MQTTPublish - Connected succeeded after retry");
s_ready.Set();
}
}
catch (Exception ex)
{
Dbg.Write("MQTTPublish - Reconnection Failed: " + ex.Message);
}
});
if (s_client.IsConnected == false)
{
try
{
MqttClientAuthenticateResult result = await s_client.ConnectAsync(options, CancellationToken.None).ConfigureAwait(false);
s_ready.Set();
if (result.ResultCode == MqttClientConnectResultCode.Success)
{
Dbg.Write("MQTTPublish - Connected to server!");
}
else
{
HandleError(result); // Here we let it go setup the disconnect handler -- things may improve in the future
}
}
catch (Exception ex)
{
Dbg.Write("MQTTPublish - Connection to server failed: " + ex.Message);
s_ready.Set(); // Well, it isn't "ready", but there is no sense waiting for a connection that will never come
return;
}
}
}
static void HandleError(MqttClientAuthenticateResult result)
{
switch (result.ResultCode)
{
case MqttClientConnectResultCode.BadUserNameOrPassword:
Dbg.Write("MQTTPublish - Connect - Invalid User Name or Password!");
DisposeInstance();
break;
case MqttClientConnectResultCode.BadAuthenticationMethod:
Dbg.Write("MQTTPublish - Connect - Bad authentication method - secure connection type invaid? " + result.ResultCode.ToString());
DisposeInstance();
break;
case MqttClientConnectResultCode.NotAuthorized:
Dbg.Write("MQTTPublish - Connect - User Not Authorized: " + result.ResultCode.ToString());
DisposeInstance();
break;
case MqttClientConnectResultCode.ServerUnavailable:
Dbg.Write("MQTTPublish - Connect - The server is unavailable");
break;
default:
Dbg.Write("MQTTPublish - Connect Error - Error Code: " + result.ResultCode.ToString());
break;
}
}
static string LoadImage(string path)
{
string result = string.Empty;
if (File.Exists(path))
{
byte[] image = File.ReadAllBytes(path);
result = Convert.ToBase64String(image);
}
return result;
}
protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
s_client.Dispose();
}
disposedValue = true;
}
}
private static void DisposeInstance()
{
if (null != s_client)
{
Dbg.Write("MQTTPublish - Disposing - Cannot Continue");
s_client.Dispose();
s_client = null;
}
}
public void Dispose()
{
// Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
Dispose(disposing: true);
GC.SuppressFinalize(this);
}
}
}