-
Notifications
You must be signed in to change notification settings - Fork 37
/
Program.cs
588 lines (500 loc) · 20.1 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
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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
/* ========================================================================
* Copyright (c) 2005-2024 The OPC Foundation, Inc. All rights reserved.
*
* OPC Foundation MIT License 1.00
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* The complete license agreement can be found here:
* http://opcfoundation.org/License/MIT/1.00/
* ======================================================================*/
using System.Security.Authentication;
using System.Text;
using System.Text.Json.Nodes;
using MQTTnet;
using MQTTnet.Client;
using Opc.Ua;
using UaMqttCommon;
await new Subscriber().Connect();
internal class Subscriber
{
const string BrokerUrl = "broker.hivemq.com";
const string TopicPrefix = "opcua";
private ServiceMessageContext m_context;
private MqttFactory m_factory;
private IMqttClient m_client;
private readonly Dictionary<string, Writer> m_writers = new();
private readonly Dictionary<string, Group> m_groups = new();
private class Group
{
public string PublisherId { get; set; }
public string GroupName { get; set; }
public bool HasNetworkMessageHeader { get; set; }
public bool HasDataSetMessageHeader { get; set; }
public bool HasMultipleDataSetMessages { get; set; }
public string DataTopic { get; set; }
public List<Writer> Writers { get; set; } = new();
}
private class Writer
{
public string PublisherId { get; set; }
public string WriterName { get; set; }
public int? DataSetWriterId { get; set; }
public WriterGroupDataType WriterGroup { get; set; }
public DataSetWriterDataType DataSetWriter { get; set; }
public DataSetMetaDataType DataSetMetaData { get; set; }
public Dictionary<string, string> EngineeringUnits { get; set; } = new();
public string MetaDataTopic { get; set; }
}
public async Task Connect()
{
m_context = new ServiceMessageContext();
m_factory = new MqttFactory();
using (m_client = m_factory.CreateMqttClient())
{
var options = new MqttClientOptionsBuilder().WithTcpServer(BrokerUrl)
.WithTlsOptions(
o =>
{
o.WithCertificateValidationHandler(e =>
{
Console.WriteLine($"Broker Certificate: '{e.Certificate.Subject}' {e.SslPolicyErrors}");
return true;
});
// The default value is determined by the OS. Set manually to force version.
o.WithSslProtocols(SslProtocols.Tls12);
})
.Build();
var response = await m_client.ConnectAsync(options, CancellationToken.None);
if (response.ResultCode != MqttClientConnectResultCode.Success)
{
Console.WriteLine($"Connect Failed: {response.ResultCode} {response.ResultCode} {response.ReasonString}");
}
else
{
Console.WriteLine("Subscriber Connected!");
}
m_client.ApplicationMessageReceivedAsync += async delegate (MqttApplicationMessageReceivedEventArgs args)
{
string topic = args.ApplicationMessage.Topic;
Console.WriteLine($"Received on Topic: {topic}");
if (topic.StartsWith($"{TopicPrefix}/json/{MessageTypes.Status}"))
{
await HandleStatus(args.ApplicationMessage);
}
else if (topic.StartsWith($"{TopicPrefix}/json/{MessageTypes.Connection}"))
{
await HandleConnection(args.ApplicationMessage);
}
else if (topic.StartsWith($"{TopicPrefix}/json/{MessageTypes.DataSetMetaData}"))
{
await HandleDataSetMetaData(args.ApplicationMessage);
}
else
{
await HandleData(args.ApplicationMessage);
}
};
await Subscribe(new Topic()
{
TopicPrefix = TopicPrefix,
MessageType = MessageTypes.Status,
PublisherId = "#"
}.Build());
Console.WriteLine("Press enter to exit.");
Console.ReadLine();
var disconnectOptions = m_factory.CreateClientDisconnectOptionsBuilder().Build();
await m_client.DisconnectAsync(disconnectOptions, CancellationToken.None);
Console.WriteLine("Subscriber Disconnected!");
}
}
private async Task Subscribe(string topic)
{
if (m_client == null || m_factory == null) throw new InvalidOperationException();
var options = m_factory.CreateSubscribeOptionsBuilder()
.WithTopicFilter(f => { f.WithTopic(topic); })
.Build();
var response = await m_client.SubscribeAsync(options, CancellationToken.None);
if (!String.IsNullOrEmpty(response?.ReasonString))
{
Console.WriteLine($"Subscribe Failed:'{response?.ReasonString}'.");
}
else
{
Console.WriteLine($"Subscribed: '{topic}'.");
}
}
private async Task Unsubscribe(string topic)
{
if (m_client == null || m_factory == null) throw new InvalidOperationException();
var options = m_factory.CreateUnsubscribeOptionsBuilder()
.WithTopicFilter(topic)
.Build();
var response = await m_client.UnsubscribeAsync(options, CancellationToken.None);
if (!String.IsNullOrEmpty(response?.ReasonString))
{
Console.WriteLine($"Unsubscribe Failed: '{response?.ReasonString}'.");
}
else
{
Console.WriteLine($"Unsubscribed: '{topic}'.");
}
}
private void WriteFieldValue(string name, DataSetField field, Writer writer)
{
StringBuilder sb = new();
if (field?.SourceTimestamp != null)
{
sb.Append($"[{field?.SourceTimestamp:HH:mm:ss}] ");
}
if (StatusCode.IsNotGood(field.StatusCode ?? 0))
{
sb.Append($"{name}=[{field?.StatusCode}] ");
}
if (field?.Value is JsonObject @object)
{
if (@object.ContainsKey("Body"))
{
sb.Append($"{name}={@object["Body"]}");
}
else
{
sb.Append($"{name}={@object}");
}
}
else
{
sb.Append($"{name}={field?.Value}");
}
if (writer != null)
{
lock (m_writers)
{
if (writer.EngineeringUnits.TryGetValue(name, out var unit))
{
sb.Append($" {unit}");
}
}
}
Console.WriteLine(sb.ToString());
}
private void HandleDataSetMessage(Topic topic, JsonDataSetMessage dm)
{
var publisherId = $"{dm?.PublisherId}";
Console.WriteLine(new string('=', 60));
if (!dm.ExcludeHeader)
{
Console.WriteLine($"PublisherId: {publisherId}");
Console.WriteLine($"DataSetWriterId: {dm?.DataSetWriterId}");
Console.WriteLine($"MessageType: {dm?.MessageType}");
Console.WriteLine($"SequenceNumber: {dm?.SequenceNumber}");
Console.WriteLine($"MinorVersion: {dm?.MinorVersion}");
Console.WriteLine($"Timestamp: {dm?.Timestamp:HH:mm:ss.fff}");
Console.WriteLine(new string('-', 60));
}
if (dm.Payload != null)
{
Writer writer = null;
// find the writer using information in the header.
if (!dm.ExcludeHeader)
{
var writerId = $"{publisherId}.{dm?.DataSetWriterId}";
lock (m_writers)
{
if (!m_writers.TryGetValue(writerId, out writer))
{
Console.WriteLine($"[Writer for Data message not found: {writerId}]");
}
}
}
// find the writer using information in the topic.
else
{
var groupId = $"{topic?.PublisherId}.{topic?.GroupName}";
lock (m_writers)
{
if (m_groups.TryGetValue(groupId, out var group))
{
writer = group.Writers.Where(x => x.WriterName == topic?.WriterName).FirstOrDefault();
}
}
if (writer == null)
{
Console.WriteLine($"[Writer for Data message not found: {topic?.WriterName}]");
}
}
foreach (var item in dm.Payload)
{
var field = DataSetField.Decode(m_context, item.Value.ToJsonString());
WriteFieldValue(item.Key, field, writer);
}
}
Console.WriteLine(new string('=', 60));
}
private Task HandleData(MqttApplicationMessage message)
{
byte[] payload = message.PayloadSegment.Array;
if (payload != null)
{
var json = Encoding.UTF8.GetString(payload);
try
{
var nm = JsonNetworkMessage.Decode(m_context, json);
if (nm?.Messages != null)
{
var topic = Topic.Parse(message.Topic);
foreach (var dm in nm.Messages)
{
HandleDataSetMessage(topic, dm);
}
}
}
catch (Exception e)
{
Console.WriteLine($"Parsing Failed: '{e.Message}' [{json}]");
}
}
return Task.CompletedTask;
}
private async Task HandleStatus(MqttApplicationMessage message)
{
byte[] payload = message.PayloadSegment.Array;
if (payload != null)
{
var json = Encoding.UTF8.GetString(payload);
try
{
var status = JsonStatusMessage.Decode(m_context, json);
Console.WriteLine($"{status?.PublisherId}: Status={((status?.Status != null) ? status.Status.Value : "")}");
var connectionTopic = new Topic()
{
TopicPrefix = TopicPrefix,
MessageType = MessageTypes.Connection,
PublisherId = status?.PublisherId
}.Build();
if (status?.Status == PubSubState.Operational)
{
await Subscribe(connectionTopic);
}
else
{
await Unsubscribe(connectionTopic);
// unsubscribe from all data topics for this publisher.
List<string> topics = new();
lock (m_writers)
{
foreach (var group in m_groups.Values)
{
if (group.PublisherId == status?.PublisherId)
{
if (group.DataTopic != null)
{
topics.Add(group.DataTopic);
}
foreach (var writer in group.Writers)
{
if (writer.MetaDataTopic != null)
{
topics.Add(writer.MetaDataTopic);
}
}
}
}
}
foreach (var topic in topics)
{
await Unsubscribe(topic);
}
}
}
catch (Exception e)
{
Console.WriteLine($"Parsing Failed: '{e.Message}' [{json}]");
}
}
}
private Task HandleDataSetMetaData(MqttApplicationMessage message)
{
byte[] payload = message.PayloadSegment.Array;
if (payload != null)
{
var json = Encoding.UTF8.GetString(payload);
try
{
var metadata = JsonDataSetMetaDataMessage.Decode(m_context, json);
var writerId = $"{metadata?.PublisherId}.{metadata?.DataSetWriterId}";
var source = metadata?.MetaData?.Fields;
Console.WriteLine($"DataSetMetaData Message: '{writerId}'");
if (source != null)
{
lock (m_writers)
{
if (!m_writers.TryGetValue(writerId, out var writer))
{
writer = new Writer()
{
PublisherId = metadata?.PublisherId,
DataSetMetaData = metadata?.MetaData
};
m_writers[writerId] = writer;
}
Dictionary<string, string> fields = writer.EngineeringUnits;
foreach (var field in source)
{
if (field.Name == null || field.Properties == null)
{
continue;
}
var value = field.Properties
.Where(x => x.Key?.Name == BrowseNames.EngineeringUnits)
.Select(x => x.Value)
.FirstOrDefault();
if (value != Variant.Null)
{
var eu = ExtensionObject.ToEncodeable((ExtensionObject)value.Value) as EUInformation;
if (eu != null)
{
fields[field.Name] = eu.DisplayName.Text;
}
}
}
writer.EngineeringUnits = fields;
}
}
}
catch (Exception e)
{
Console.WriteLine($"Parsing Failed: '{e.Message}' [{json}]");
}
}
return Task.CompletedTask;
}
public async Task HandleConnection(MqttApplicationMessage message)
{
byte[] payload = message.PayloadSegment.Array;
if (payload == null)
{
return;
}
JsonPubSubConnectionMessage connection;
var json = Encoding.UTF8.GetString(payload);
try
{
connection = JsonPubSubConnectionMessage.Decode(m_context, json);
}
catch (Exception e)
{
Console.WriteLine($"Parsing Failed: '{e.Message}' [{json}]");
return;
}
if (connection?.Connection?.WriterGroups != null)
{
foreach (var ii in connection.Connection.WriterGroups)
{
var groupId = $"{connection?.PublisherId}.{ii?.Name}";
Group group = null;
lock (m_writers)
{
if (!m_groups.TryGetValue(groupId, out group))
{
group = new Group()
{
PublisherId = connection?.PublisherId,
GroupName = ii?.Name
};
m_groups[groupId] = group;
}
}
group.HasNetworkMessageHeader = false;
group.HasDataSetMessageHeader = false;
group.HasMultipleDataSetMessages = false;
group.DataTopic = null;
if (ii?.MessageSettings?.Body is JsonWriterGroupMessageDataType wgm)
{
var mask = wgm.NetworkMessageContentMask;
group.HasNetworkMessageHeader = (mask & 0x01) != 0;
group.HasDataSetMessageHeader = (mask & 0x02) != 0;
group.HasMultipleDataSetMessages = (mask & 0x04) == 0;
}
if (ii?.TransportSettings?.Body is BrokerWriterGroupTransportDataType wgt)
{
group.DataTopic = wgt.QueueName;
}
if (group.DataTopic == null)
{
group.DataTopic = new Topic()
{
TopicPrefix = TopicPrefix,
MessageType = MessageTypes.Data,
PublisherId = connection?.PublisherId,
GroupName = ii?.Name,
WriterName = "#"
}.Build();
}
// this quickstart is only interested in data messages with multiple messages.
if (!group.HasMultipleDataSetMessages && !group.HasNetworkMessageHeader)
{
await Subscribe(group.DataTopic);
}
if (ii?.DataSetWriters != null)
{
foreach (var jj in ii.DataSetWriters)
{
string metadataTopic = null;
if (jj?.TransportSettings?.Body is BrokerDataSetWriterTransportDataType dwt)
{
metadataTopic = dwt.MetaDataQueueName;
}
if (metadataTopic == null)
{
metadataTopic = new Topic()
{
TopicPrefix = TopicPrefix,
MessageType = MessageTypes.DataSetMetaData,
PublisherId = connection?.PublisherId,
GroupName = ii?.Name,
WriterName = jj?.Name
}.Build();
}
lock (m_writers)
{
var writerId = $"{connection?.PublisherId}.{jj?.DataSetWriterId}";
if (!m_writers.TryGetValue(writerId, out var writer))
{
writer = new Writer()
{
PublisherId = connection?.PublisherId,
DataSetWriterId = jj?.DataSetWriterId,
};
m_writers[writerId] = writer;
group.Writers.Add(writer);
}
writer.MetaDataTopic = metadataTopic;
writer.WriterGroup = ii;
writer.DataSetWriter = jj;
}
await Subscribe(metadataTopic);
}
}
}
}
}
}