-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAppBase.cs
More file actions
322 lines (294 loc) · 13.8 KB
/
Copy pathAppBase.cs
File metadata and controls
322 lines (294 loc) · 13.8 KB
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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using MQTTnet.Client;
using MQTTnet.Extensions.ManagedClient;
using TTNet.Data.Model;
namespace TTNet.Data;
/// <summary>
/// A The Things Network Application Data connection.
/// </summary>
public abstract class AppBase : DeviceHandler, IDisposable
{
/// <summary>
/// Client identifier.
/// </summary>
public string ClientID { get; private set; }
private readonly Dictionary<string, DeviceHandler> _deviceHandlers;
/// <summary>
/// Application identifier.
/// </summary>
public string AppID { get; private set; }
/// <summary>
/// Tenant identifier.
/// </summary>
public string? TenantID { get; private set; }
/// <summary>
/// Value indicating whether this <see cref="TTNet.Data.AppBase"/> is connected.
/// </summary>
public abstract bool IsConnected { get; }
/// <summary>
/// Get the <see cref="TTNet.Data.DeviceHandler"/> for a device ID.
/// </summary>
/// <param name="deviceId">The device ID.</param>
/// <returns>The <see cref="TTNet.Data.DeviceHandler"/>.</returns>
public DeviceHandler this[string deviceId]
{
get
{
DeviceHandler result;
if (_deviceHandlers.ContainsKey(deviceId))
{
result = _deviceHandlers[deviceId];
}
else
{
if (_mqttClient != null)
result = new DeviceHandler(_mqttClient, deviceId, AppID, TenantID);
else if (_managedMqttClient != null)
result = new DeviceHandler(_managedMqttClient, deviceId, AppID, TenantID);
else
throw new Exception();
_deviceHandlers.Add(deviceId, result);
}
return result;
}
}
/// <summary>
/// Occurs when connection is completed.
/// </summary>
public event EventHandler<MqttClientConnectedEventArgs>? Connected;
/// <summary>
/// Occurs when disconnected.
/// </summary>
public event EventHandler<MqttClientDisconnectedEventArgs>? Disconnected;
/// <summary>
/// Occurs when a exception is throwed.
/// </summary>
public event EventHandler<Exception>? ExceptionThrowed;
/// <summary>
/// Occurs when a message is processed in managed mode.
/// </summary>
public event EventHandler<Guid>? MessageProcessed;
/// <summary>
/// Occurs when a message is skipped in managed mode.
/// </summary>
public event EventHandler<Guid>? MessageSkipped;
/// <summary>
/// Initializes a new instance of the <see cref="TTNet.Data.AppBase"/> class.
/// </summary>
/// <param name="mqttClient">A <see cref="MQTTnet.Client.IMqttClient"/>.</param>
/// <param name="appId">App identifier.</param>
/// <param name="tenantId">Tenant identifier. Use null for The Things Stack Open Source deployment.</param>
protected AppBase(IMqttClient mqttClient, string appId, string? tenantId = "ttn") : base(mqttClient, "+", appId, tenantId)
{
AppID = appId;
TenantID = tenantId;
ClientID = Guid.NewGuid().ToString();
_deviceHandlers = [];
}
/// <summary>
/// Initializes a new instance of the <see cref="TTNet.Data.AppBase"/> class.
/// </summary>
/// <param name="mqttClient">A <see cref="MQTTnet.Extensions.ManagedClient.IManagedMqttClient"/>.</param>
/// <param name="appId">App identifier.</param>
/// <param name="tenantId">Tenant identifier. Use null for The Things Stack Open Source deployment.</param>
protected AppBase(IManagedMqttClient mqttClient, string appId, string? tenantId = "ttn") : base(mqttClient, "+", appId, tenantId)
{
AppID = appId;
TenantID = tenantId;
ClientID = Guid.NewGuid().ToString();
_deviceHandlers = [];
}
private protected MqttClientOptions GetMqttClientOptions(string server, int port, bool withTls, string username, string apiKey)
{
var o = new MqttClientOptionsBuilder()
.WithClientId(ClientID)
.WithTcpServer(server, port)
.WithCredentials(username, apiKey)
.WithCleanSession();
return withTls ? o.WithTlsOptions(o => o.WithSslProtocols(System.Security.Authentication.SslProtocols.None)).Build() : o.Build();
}
private protected async Task HandleApplicationMessageReceivedAsync(MqttApplicationMessageReceivedEventArgs e)
{
Message msg;
MessageReceivedEventArgs eventArgs;
string[] topic = e.ApplicationMessage.Topic.Split('/');
// Parse the message and raise the corresponding event
try
{
msg = JsonSerializer.Deserialize<Message>(e.ApplicationMessage.PayloadSegment, _serializerOptions) ??
throw new JsonException("JsonSerializer returned null");
eventArgs = new MessageReceivedEventArgs(msg, e.ApplicationMessage.Topic, topic);
switch (topic[4])
{
case "join":
_join?.Invoke(this, eventArgs);
if (_deviceHandlers.ContainsKey(topic[3]))
_deviceHandlers[topic[3]]._join?.Invoke(this, eventArgs);
break;
case "up":
_up?.Invoke(this, eventArgs);
if (_deviceHandlers.ContainsKey(topic[3]))
_deviceHandlers[topic[3]]._up?.Invoke(this, eventArgs);
break;
case "down":
switch (topic[5])
{
case "queued":
_downQueued?.Invoke(this, eventArgs);
if (_deviceHandlers.ContainsKey(topic[3]))
_deviceHandlers[topic[3]]._downQueued?.Invoke(this, eventArgs);
break;
case "sent":
_downSent?.Invoke(this, eventArgs);
if (_deviceHandlers.ContainsKey(topic[3]))
_deviceHandlers[topic[3]]._downSent?.Invoke(this, eventArgs);
break;
case "ack":
_downAck?.Invoke(this, eventArgs);
if (_deviceHandlers.ContainsKey(topic[3]))
_deviceHandlers[topic[3]]._downAck?.Invoke(this, eventArgs);
break;
case "nack":
_downNack?.Invoke(this, eventArgs);
if (_deviceHandlers.ContainsKey(topic[3]))
_deviceHandlers[topic[3]]._downNack?.Invoke(this, eventArgs);
break;
case "failed":
_downFailed?.Invoke(this, eventArgs);
if (_deviceHandlers.ContainsKey(topic[3]))
_deviceHandlers[topic[3]]._downFailed?.Invoke(this, eventArgs);
break;
}
break;
case "service":
if (topic[5] == "data")
{
_serviceData?.Invoke(this, eventArgs);
if (_deviceHandlers.ContainsKey(topic[3]))
_deviceHandlers[topic[3]]._serviceData?.Invoke(this, eventArgs);
}
break;
case "location":
if (topic[5] == "solved")
{
_locationSolved?.Invoke(this, eventArgs);
if (_deviceHandlers.ContainsKey(topic[3]))
_deviceHandlers[topic[3]]._locationSolved?.Invoke(this, eventArgs);
}
break;
}
}
catch (Exception ex)
{
if (ExceptionThrowed != null)
await ExceptionThrowed.InvokeAsync(this, ex);
}
}
private protected async Task HandleConnectedAsync(MqttClientConnectedEventArgs eventArgs)
{
// Subscribe to topics with handled events
if (eventArgs.ConnectResult.ResultCode == MqttClientConnectResultCode.Success)
{
await SubscribeAsync();
foreach (DeviceHandler d in _deviceHandlers.Values)
await d.SubscribeAsync();
}
if (Connected != null)
await Connected.InvokeAsync(this, eventArgs);
}
private protected Task HandleDisconnectedAsync(MqttClientDisconnectedEventArgs eventArgs) =>
Disconnected?.InvokeAsync(this, eventArgs) ?? Task.CompletedTask;
private protected Task HandleApplicationMessageProcessedAsync(ApplicationMessageProcessedEventArgs eventArgs) =>
MessageProcessed?.InvokeAsync(this, eventArgs.ApplicationMessage.Id) ?? Task.CompletedTask;
private protected Task HandleApplicationMessageSkippedAsync(ApplicationMessageSkippedEventArgs eventArgs) =>
MessageSkipped?.InvokeAsync(this, eventArgs.ApplicationMessage.Id) ?? Task.CompletedTask;
private protected Task HandleConnectingFailedAsync(ConnectingFailedEventArgs eventArgs) =>
ExceptionThrowed?.InvokeAsync(this, eventArgs.Exception) ?? Task.CompletedTask;
private protected Task HandleSynchronizingSubscriptionsFailedAsync(ManagedProcessFailedEventArgs eventArgs) =>
ExceptionThrowed?.InvokeAsync(this, eventArgs.Exception) ?? Task.CompletedTask;
/// <summary>
/// Unsupported. This must be called from a specific device.
/// </summary>
/// <exception cref="System.InvalidOperationException">Thrown always.</exception>
/// <returns>The publication result.</returns>
/// <param name="msg">Message.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <param name="schedule">Schedule.</param>
public override Task<MqttClientPublishResult> PublishAsync(Message msg, CancellationToken cancellationToken, Schedule schedule) =>
throw new InvalidOperationException();
/// <summary>
/// Unsupported. This must be called from a specific device.
/// </summary>
/// <exception cref="System.InvalidOperationException">Thrown always.</exception>
/// <returns>The publication result.</returns>
/// <param name="msg">Message.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <param name="schedule">Schedule.</param>
public override Task<MqttClientPublishResult> PublishAsync(Downlink msg, CancellationToken cancellationToken, Schedule schedule) =>
throw new InvalidOperationException();
/// <summary>
/// Unsupported. This must be called from a specific device.
/// </summary>
/// <exception cref="System.InvalidOperationException">Thrown always.</exception>
/// <returns>The publication result.</returns>
/// <param name="json">Message.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <param name="schedule">Schedule.</param>
public override Task<MqttClientPublishResult> PublishAsync(string json, CancellationToken cancellationToken, Schedule schedule) =>
throw new InvalidOperationException();
/// <summary>
/// Unsupported. This must be called from a specific device.
/// </summary>
/// <exception cref="System.InvalidOperationException">Thrown always.</exception>
/// <returns>The publication result.</returns>
/// <param name="json">Message stream.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <param name="schedule">Schedule.</param>
public override Task<MqttClientPublishResult> PublishAsync(Stream json, CancellationToken cancellationToken, Schedule schedule = Schedule.Push) =>
throw new InvalidOperationException();
/// <summary>
/// Unsupported. This must be called from a specific device.
/// </summary>
/// <exception cref="System.InvalidOperationException">Thrown always.</exception>
/// <returns>The publication ID.</returns>
/// <param name="msg">Message.</param>
/// <param name="schedule">Schedule.</param>
public override Task<Guid> PublishAsync(Message msg, Schedule schedule = Schedule.Push) =>
throw new InvalidOperationException();
/// <summary>
/// Unsupported. This must be called from a specific device.
/// </summary>
/// <exception cref="System.InvalidOperationException">Thrown always.</exception>
/// <returns>The publication ID.</returns>
/// <param name="msg">Message.</param>
/// <param name="schedule">Schedule.</param>
public override Task<Guid> PublishAsync(Downlink msg, Schedule schedule = Schedule.Push) =>
throw new InvalidOperationException();
/// <summary>
/// Unsupported. This must be called from a specific device.
/// </summary>
/// <exception cref="System.InvalidOperationException">Thrown always.</exception>
/// <returns>The publication ID.</returns>
/// <param name="json">Message.</param>
/// <param name="schedule">Schedule.</param>
public override Task<Guid> PublishAsync(string json, Schedule schedule = Schedule.Push) =>
throw new InvalidOperationException();
/// <summary>
/// Unsupported. This must be called from a specific device.
/// </summary>
/// <exception cref="System.InvalidOperationException">Thrown always.</exception>
/// <returns>The publication ID.</returns>
/// <param name="json">Message stream.</param>
/// <param name="schedule">Schedule.</param>
public override Task<Guid> PublishAsync(Stream json, Schedule schedule = Schedule.Push) =>
throw new InvalidOperationException();
/// <summary>
/// Dispose all resources used by this object
/// </summary>
public abstract void Dispose();
}