-
Notifications
You must be signed in to change notification settings - Fork 75
/
MqttClient.cs
1337 lines (1109 loc) · 35.6 KB
/
MqttClient.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
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.IO;
using System.Security.Authentication;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Waher.Content;
using Waher.Events;
using Waher.Networking.Sniffers;
#if WINDOWS_UWP
using Windows.Networking.Sockets;
using Windows.Security.Cryptography.Certificates;
#else
using System.Security.Cryptography.X509Certificates;
#endif
namespace Waher.Networking.MQTT
{
/// <summary>
/// Connection error event handler.
/// </summary>
/// <param name="Sender">Sender of event.</param>
/// <param name="Exception">Information about error received.</param>
public delegate Task MqttExceptionEventHandler(object Sender, Exception Exception);
/// <summary>
/// Event handler for state change events.
/// </summary>
/// <param name="Sender">Sender of event.</param>
/// <param name="NewState">New state reported.</param>
public delegate Task StateChangedEventHandler(object Sender, MqttState NewState);
/// <summary>
/// Event handler used for events raised when data has been successfully acknowledged.
/// </summary>
/// <param name="Sender">Sender of event.</param>
/// <param name="PacketIdentifier">Packet identifier of data successfully published.</param>
//#pragma warning disable
public delegate Task PacketAcknowledgedEventHandler(object Sender, ushort PacketIdentifier);
//#pragma warning restore
/// <summary>
/// Event handler for events raised when content has been received.
/// </summary>
/// <param name="Sender">Sender of event.</param>
/// <param name="Content">Content received.</param>
public delegate Task ContentReceivedEventHandler(object Sender, MqttContent Content);
/// <summary>
/// Manages an MQTT connection. Implements MQTT v3.1.1, as defined in
/// http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html
/// </summary>
public class MqttClient : Sniffable, IDisposable, IHostReference
{
private const int KeepAliveTimeSeconds = 30;
#if !WINDOWS_UWP
private readonly X509Certificate clientCertificate = null;
#endif
private readonly SortedDictionary<DateTime, OutputRecord> packetByTimeout = new SortedDictionary<DateTime, OutputRecord>();
private readonly SortedDictionary<int, DateTime> timeoutByPacketIdentifier = new SortedDictionary<int, DateTime>();
private readonly Random rnd = new Random();
private readonly object synchObj = new object();
private readonly Dictionary<ushort, MqttContent> contentCache = new Dictionary<ushort, MqttContent>();
private readonly string clientId = Guid.NewGuid().ToString().Substring(0, 23);
private BinaryTcpClient client = null;
private readonly byte[] willData = null;
private Timer secondTimer = null;
private DateTime nextPing = DateTime.MinValue;
private readonly MqttQualityOfService willQoS = MqttQualityOfService.AtMostOnce;
private readonly string host;
private readonly string userName;
private readonly string password;
private readonly string willTopic = null;
private readonly int port;
private int keepAliveSeconds;
private MqttState state;
private readonly bool tls;
private bool trustServer = false;
private readonly bool will = false;
private readonly bool willRetain = false;
#if !WINDOWS_UWP
/// <summary>
/// Manages an MQTT connection. Implements MQTT v3.1.1, as defined in
/// http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html
/// </summary>
/// <param name="Host">Host name or IP address of MQTT server.</param>
/// <param name="Port">Port to connect to.</param>
/// <param name="ClientCertificate">Client certificate.</param>
/// <param name="Sniffers">Sniffers to use.</param>
public MqttClient(string Host, int Port, X509Certificate ClientCertificate, params ISniffer[] Sniffers)
: this(Host, Port, ClientCertificate, null, MqttQualityOfService.AtMostOnce, false, null, Sniffers)
{
}
#endif
/// <summary>
/// Manages an MQTT connection. Implements MQTT v3.1.1, as defined in
/// http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html
/// </summary>
/// <param name="Host">Host name or IP address of MQTT server.</param>
/// <param name="Port">Port to connect to.</param>
/// <param name="Tls">If TLS is used to encrypt communication.</param>
/// <param name="UserName">User Name</param>
/// <param name="Password">Password</param>
/// <param name="Sniffers">Sniffers to use.</param>
public MqttClient(string Host, int Port, bool Tls, string UserName, string Password, params ISniffer[] Sniffers)
: this(Host, Port, Tls, UserName, Password, null, MqttQualityOfService.AtMostOnce, false, null, Sniffers)
{
}
#if !WINDOWS_UWP
/// <summary>
/// Manages an MQTT connection. Implements MQTT v3.1.1, as defined in
/// http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html
/// </summary>
/// <param name="Host">Host name or IP address of MQTT server.</param>
/// <param name="Port">Port to connect to.</param>
/// <param name="ClientCertificate">Client certificate.</param>
/// <param name="WillTopic">Topic to publish the last will and testament, in case the connection drops unexpectedly.</param>
/// <param name="WillQoS">Quality of Service of last will and testament, in case the connection drops unexpectedly.</param>
/// <param name="WillRetain">If last will and testament should be retained, in case the connection drops unexpectedly.</param>
/// <param name="WillData">Data of last will and testament, in case the connection drops unexpectedly.</param>
/// <param name="Sniffers">Sniffers to use.</param>
public MqttClient(string Host, int Port, X509Certificate ClientCertificate, string WillTopic,
MqttQualityOfService WillQoS, bool WillRetain, byte[] WillData, params ISniffer[] Sniffers)
: base(Sniffers)
{
this.host = Host;
this.port = Port;
this.tls = true;
this.userName = string.Empty;
this.password = string.Empty;
this.clientCertificate = ClientCertificate;
this.state = MqttState.Offline;
this.will = !string.IsNullOrEmpty(WillTopic) && !(WillData is null);
this.willTopic = WillTopic;
this.willQoS = WillQoS;
this.willRetain = WillRetain;
this.willData = WillData;
if (this.will && this.willData.Length > 65535)
throw new ArgumentException("Will data too large.", nameof(WillData));
Task.Run(() => this.BeginConnect());
}
#endif
/// <summary>
/// Manages an MQTT connection. Implements MQTT v3.1.1, as defined in
/// http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html
/// </summary>
/// <param name="Host">Host name or IP address of MQTT server.</param>
/// <param name="Port">Port to connect to.</param>
/// <param name="Tls">If TLS is used to encrypt communication.</param>
/// <param name="UserName">User Name</param>
/// <param name="Password">Password</param>
/// <param name="WillTopic">Topic to publish the last will and testament, in case the connection drops unexpectedly.</param>
/// <param name="WillQoS">Quality of Service of last will and testament, in case the connection drops unexpectedly.</param>
/// <param name="WillRetain">If last will and testament should be retained, in case the connection drops unexpectedly.</param>
/// <param name="WillData">Data of last will and testament, in case the connection drops unexpectedly.</param>
/// <param name="Sniffers">Sniffers to use.</param>
public MqttClient(string Host, int Port, bool Tls, string UserName, string Password, string WillTopic,
MqttQualityOfService WillQoS, bool WillRetain, byte[] WillData, params ISniffer[] Sniffers)
: base(Sniffers)
{
this.host = Host;
this.port = Port;
this.tls = Tls;
this.userName = UserName;
this.password = Password;
#if !WINDOWS_UWP
this.clientCertificate = null;
#endif
this.state = MqttState.Offline;
this.will = !string.IsNullOrEmpty(WillTopic) && !(WillData is null);
this.willTopic = WillTopic;
this.willQoS = WillQoS;
this.willRetain = WillRetain;
this.willData = WillData;
if (this.will && this.willData.Length > 65535)
throw new ArgumentException("Will data too large.", nameof(WillData));
Task.Run(() => this.BeginConnect());
}
private class OutputRecord
{
public byte[] Packet;
public int PacketIdentifier;
public EventHandler Callback;
}
private async Task BeginConnect()
{
try
{
this.Information("Connecting to " + this.Host + ":" + this.Port.ToString());
this.DisposeClient();
this.State = MqttState.Connecting;
this.client = new BinaryTcpClient();
await this.client.ConnectAsync(this.Host, this.Port, this.tls);
if (this.tls)
{
this.State = MqttState.StartingEncryption;
#if WINDOWS_UWP
await this.client.UpgradeToTlsAsClient(SocketProtectionLevel.Tls12, this.trustServer);
#else
await this.client.UpgradeToTlsAsClient(this.clientCertificate, SslProtocols.Tls12, this.trustServer);
#endif
this.client.Continue();
}
this.client.OnSent += this.Client_OnSent;
this.client.OnReceived += this.Client_OnReceived;
this.client.OnDisconnected += this.Client_OnDisconnected;
this.client.OnError += this.ConnectionError;
await this.CONNECT(KeepAliveTimeSeconds);
}
catch (Exception ex)
{
await this.ConnectionError(this, ex);
}
}
/// <summary>
/// Reconnects a client after an error or if it's offline. Reconnecting, instead of creating a completely new connection,
/// saves time.
/// </summary>
public async Task Reconnect()
{
try
{
this.secondTimer?.Dispose();
this.secondTimer = null;
if (this.state == MqttState.Connected)
await this.DISCONNECT();
this.DisposeClient();
}
catch (Exception)
{
// Ignore
}
finally
{
this.secondTimer = null;
this.client = null;
}
this.state = MqttState.Offline;
await this.BeginConnect();
}
private async Task ConnectionError(object Sender, Exception ex)
{
MqttExceptionEventHandler h = this.OnConnectionError;
if (!(h is null))
{
try
{
await h(this, ex);
}
catch (Exception ex2)
{
this.Exception(ex2);
Log.Exception(ex2);
}
}
await this.Error(ex);
this.State = MqttState.Error;
}
private async Task CONNECT(int KeepAliveSeconds)
{
this.State = MqttState.Authenticating;
this.keepAliveSeconds = KeepAliveSeconds;
this.nextPing = DateTime.Now.AddMilliseconds(KeepAliveSeconds * 500);
this.secondTimer = new Timer(this.SecondTimer_Elapsed, null, 1000, 1000);
BinaryOutput Payload = new BinaryOutput();
Payload.WriteString("MQTT");
Payload.WriteByte(4); // v3.1.1
byte b = 2; // Clean session.
if (this.will)
{
b |= 4;
b |= (byte)(((int)this.willQoS) << 3);
if (this.willRetain)
b |= 32;
}
if (!string.IsNullOrEmpty(this.userName))
{
b |= 128;
if (!string.IsNullOrEmpty(this.password))
b |= 64;
}
Payload.WriteByte(b);
Payload.WriteByte((byte)(KeepAliveSeconds >> 8));
Payload.WriteByte((byte)KeepAliveSeconds);
Payload.WriteString(this.clientId);
if (this.will)
{
Payload.WriteString(this.willTopic);
int l = this.willData.Length;
Payload.WriteByte((byte)(l >> 8));
Payload.WriteByte((byte)l);
Payload.WriteBytes(this.willData);
}
if (!string.IsNullOrEmpty(this.userName))
{
Payload.WriteString(this.userName);
if (!string.IsNullOrEmpty(this.password))
Payload.WriteString(this.password);
}
byte[] PayloadData = Payload.GetPacket();
BinaryOutput Packet = new BinaryOutput();
Packet.WriteByte((byte)MqttControlPacketType.CONNECT << 4);
Packet.WriteUInt((uint)PayloadData.Length);
Packet.WriteBytes(PayloadData);
byte[] PacketData = Packet.GetPacket();
if (this.HasSniffers)
this.Information("CONNECT");
await this.Write(PacketData, 0, null);
this.inputState = 0;
}
private async Task Write(byte[] Packet, int PacketIdentifier, EventHandler Callback)
{
if (PacketIdentifier != 0 && ((Packet[0] >> 1) & 3) > 0)
{
DateTime Timeout = DateTime.Now.AddSeconds(2);
lock (this.synchObj)
{
while (this.packetByTimeout.ContainsKey(Timeout))
Timeout = Timeout.AddTicks(this.rnd.Next(1, 10));
this.packetByTimeout[Timeout] = new OutputRecord()
{
Packet = Packet,
PacketIdentifier = PacketIdentifier,
Callback = Callback
};
this.timeoutByPacketIdentifier[PacketIdentifier] = Timeout;
}
}
await this.client.SendAsync(Packet, Callback);
this.nextPing = DateTime.Now.AddMilliseconds(this.keepAliveSeconds * 500);
}
private void Client_OnDisconnected(object sender, EventArgs e)
{
if (this.state != MqttState.Error)
this.State = MqttState.Offline;
}
private Task<bool> Client_OnSent(object Sender, byte[] Buffer, int Offset, int Count)
{
if (this.HasSniffers)
this.TransmitBinary(BinaryTcpClient.ToArray(Buffer, Offset, Count));
return Task.FromResult(true);
}
private async Task<bool> Client_OnReceived(object Sender, byte[] Buffer, int Offset, int Count)
{
if (this.HasSniffers)
this.ReceiveBinary(BinaryTcpClient.ToArray(Buffer, Offset, Count));
byte b;
bool Result = true;
while (Count-- > 0)
{
b = Buffer[Offset++];
switch (this.inputState)
{
case 0:
this.inputPacket = new MemoryStream();
this.inputPacket.WriteByte(b);
this.inputPacketType = (MqttControlPacketType)(b >> 4);
this.inputRemainingLength = 0;
this.inputOffset = 0;
this.inputState++;
break;
case 1:
this.inputRemainingLength |= ((b & 127) << this.inputOffset);
this.inputOffset += 7;
this.inputPacket.WriteByte(b);
if ((b & 128) == 0)
{
switch (this.inputPacketType)
{
case MqttControlPacketType.CONNECT:
case MqttControlPacketType.CONNACK:
case MqttControlPacketType.PINGREQ:
case MqttControlPacketType.PINGRESP:
case MqttControlPacketType.DISCONNECT:
case MqttControlPacketType.PUBLISH:
default:
if (this.inputRemainingLength == 0)
{
this.inputState = 0;
if (!await this.ProcessInputPacket())
Result = false;
}
else
this.inputState += 3;
break;
case MqttControlPacketType.PUBACK:
case MqttControlPacketType.PUBREC:
case MqttControlPacketType.PUBREL:
case MqttControlPacketType.PUBCOMP:
case MqttControlPacketType.SUBSCRIBE:
case MqttControlPacketType.SUBACK:
case MqttControlPacketType.UNSUBSCRIBE:
case MqttControlPacketType.UNSUBACK:
this.inputState++;
break;
}
}
break;
case 2:
this.inputPacket.WriteByte(b);
this.inputState++;
this.inputRemainingLength--;
break;
case 3:
this.inputPacket.WriteByte(b);
this.inputRemainingLength--;
if (this.inputRemainingLength == 0)
{
this.inputState = 0;
if (!await this.ProcessInputPacket())
Result = false;
}
else
this.inputState++;
break;
case 4:
this.inputPacket.WriteByte(b);
this.inputRemainingLength--;
if (this.inputRemainingLength == 0)
{
this.inputState = 0;
if (!await this.ProcessInputPacket())
Result = false;
}
break;
}
}
return Result;
}
private void PacketDelivered(int PacketIdentifier)
{
lock (this.synchObj)
{
if (this.timeoutByPacketIdentifier.TryGetValue(PacketIdentifier, out DateTime TP))
{
this.timeoutByPacketIdentifier.Remove(PacketIdentifier);
this.packetByTimeout.Remove(TP);
}
}
}
private async void SecondTimer_Elapsed(object State)
{
DateTime Now = DateTime.Now;
try
{
if (Now >= this.nextPing)
{
await this.PING();
this.nextPing = Now.AddMilliseconds(this.keepAliveSeconds * 500);
}
LinkedList<KeyValuePair<DateTime, OutputRecord>> Resend = null;
lock (this.synchObj)
{
foreach (KeyValuePair<DateTime, OutputRecord> P in this.packetByTimeout)
{
if (Now < P.Key)
break;
if (Resend is null)
Resend = new LinkedList<KeyValuePair<DateTime, OutputRecord>>();
Resend.AddLast(P);
}
if (!(Resend is null))
{
foreach (KeyValuePair<DateTime, OutputRecord> P in Resend)
{
this.packetByTimeout.Remove(P.Key);
this.timeoutByPacketIdentifier.Remove(P.Value.PacketIdentifier);
}
}
}
if (!(Resend is null))
{
foreach (KeyValuePair<DateTime, OutputRecord> P in Resend)
await this.Write(P.Value.Packet, P.Value.PacketIdentifier, P.Value.Callback);
}
}
catch (Exception ex)
{
Log.Exception(ex);
}
}
private async Task<bool> ProcessInputPacket()
{
try
{
BinaryInput Packet = new BinaryInput(this.inputPacket);
MqttHeader Header = MqttHeader.Parse(Packet);
switch (Header.ControlPacketType)
{
case MqttControlPacketType.CONNECT:
default:
if (this.HasSniffers)
this.Information("CONNECT");
throw new Exception("Received command from server that is not handled: " + Header.ControlPacketType.ToString());
case MqttControlPacketType.CONNACK:
if (this.HasSniffers)
this.Information("CONNACK");
bool SessionPresent = (Packet.ReadByte() & 1) != 0;
byte ReturnCode = Packet.ReadByte();
try
{
switch (ReturnCode)
{
case 0:
this.State = MqttState.Connected;
this.nextPing = DateTime.Now.AddMilliseconds(this.keepAliveSeconds * 500);
break;
case 1:
throw new IOException("Connection Refused, unacceptable protocol version.");
case 2:
throw new IOException("Connection Refused, identifier rejected.");
case 3:
throw new IOException("Connection Refused, Server unavailable.");
case 4:
throw new IOException("Connection Refused, bad user name or password.");
case 5:
throw new IOException("Connection Refused, not authorized.");
default:
throw new IOException("Unrecognized error code returned: " + ReturnCode.ToString());
}
}
catch (Exception ex)
{
await this.ConnectionError(this, ex);
this.DisposeClient();
return false;
}
break;
case MqttControlPacketType.PINGREQ:
if (this.HasSniffers)
this.Information("PINGREQ");
await this.PINGRESP();
break;
case MqttControlPacketType.PINGRESP:
if (this.HasSniffers)
this.Information("PINGRESP");
EventHandlerAsync h = this.OnPingResponse;
if (!(h is null))
{
try
{
await h(this, EventArgs.Empty);
}
catch (Exception ex)
{
this.Exception(ex);
Log.Exception(ex);
}
}
break;
case MqttControlPacketType.PUBLISH:
string Topic = Packet.ReadString();
if (this.HasSniffers)
this.Information("PUBLISH(" + Header.QualityOfService.ToString() + ":" + Topic + ")");
if (Header.QualityOfService > MqttQualityOfService.AtMostOnce)
Header.PacketIdentifier = Packet.ReadUInt16();
else
Header.PacketIdentifier = 0;
int c = Packet.BytesLeft;
byte[] Data = Packet.ReadBytes(c);
MqttContent Content = new MqttContent(Header, Topic, Data);
switch (Header.QualityOfService)
{
case MqttQualityOfService.AtMostOnce:
await this.ContentReceived(Content);
break;
case MqttQualityOfService.AtLeastOnce:
await this.PUBACK(Header.PacketIdentifier);
await this.ContentReceived(Content);
break;
case MqttQualityOfService.ExactlyOnce:
lock (this.synchObj)
{
this.contentCache[Header.PacketIdentifier] = Content;
}
await this.PUBREC(Header.PacketIdentifier);
break;
}
break;
case MqttControlPacketType.PUBACK:
if (this.HasSniffers)
this.Information("PUBACK");
this.PacketDelivered(Header.PacketIdentifier);
PacketAcknowledgedEventHandler h2 = this.OnPublished;
if (!(h2 is null))
{
try
{
await h2(this, Header.PacketIdentifier);
}
catch (Exception ex)
{
this.Exception(ex);
}
}
break;
case MqttControlPacketType.PUBREC:
if (this.HasSniffers)
this.Information("PUBREC");
this.PacketDelivered(Header.PacketIdentifier);
await this.PUBREL(Header.PacketIdentifier);
break;
case MqttControlPacketType.PUBREL:
if (this.HasSniffers)
this.Information("PUBREL");
lock (this.synchObj)
{
if (this.contentCache.TryGetValue(Header.PacketIdentifier, out Content))
this.contentCache.Remove(Header.PacketIdentifier);
else
Content = null;
}
await this.PUBCOMP(Header.PacketIdentifier);
if (!(Content is null))
await this.ContentReceived(Content);
break;
case MqttControlPacketType.PUBCOMP:
if (this.HasSniffers)
this.Information("PUBCOMP");
this.PacketDelivered(Header.PacketIdentifier);
h2 = this.OnPublished;
if (!(h2 is null))
{
try
{
await h2(this, Header.PacketIdentifier);
}
catch (Exception ex)
{
this.Exception(ex);
}
}
break;
case MqttControlPacketType.SUBACK:
if (this.HasSniffers)
this.Information("SUBACK");
this.PacketDelivered(Header.PacketIdentifier);
h2 = this.OnSubscribed;
if (!(h2 is null))
{
try
{
await h2(this, Header.PacketIdentifier);
}
catch (Exception ex)
{
this.Exception(ex);
}
}
break;
case MqttControlPacketType.UNSUBACK:
if (this.HasSniffers)
this.Information("UNSUBACK");
this.PacketDelivered(Header.PacketIdentifier);
h2 = this.OnUnsubscribed;
if (!(h2 is null))
{
try
{
await h2(this, Header.PacketIdentifier);
}
catch (Exception ex)
{
this.Exception(ex);
}
}
break;
}
}
catch (Exception ex)
{
await this.Error(ex);
}
return true;
}
private async Task Error(Exception ex)
{
MqttExceptionEventHandler h = this.OnError;
if (!(h is null))
{
try
{
await h(this, ex);
}
catch (Exception ex2)
{
this.Exception(ex2);
Log.Exception(ex2);
}
}
}
private int inputState = 0;
private MemoryStream inputPacket = null;
private MqttControlPacketType inputPacketType;
private int inputRemainingLength;
private int inputOffset;
/// <summary>
/// Sends a PING message to the server. This is automatically done to keep the connection alive. Only call this method
/// if you want to send additional PING messages, apart from the ones sent to keep the connection alive.
/// </summary>
public async Task PING()
{
BinaryOutput Packet = new BinaryOutput();
Packet.WriteByte((byte)MqttControlPacketType.PINGREQ << 4);
Packet.WriteUInt(0);
byte[] PacketData = Packet.GetPacket();
if (this.HasSniffers)
this.Information("PING");
await this.Write(PacketData, 0, null);
EventHandlerAsync h = this.OnPing;
if (!(h is null))
{
try
{
await h(this, EventArgs.Empty);
}
catch (Exception ex)
{
this.Exception(ex);
Log.Exception(ex);
}
}
}
private Task PINGRESP()
{
BinaryOutput Packet = new BinaryOutput();
Packet.WriteByte((byte)MqttControlPacketType.PINGRESP << 4);
Packet.WriteUInt(0);
byte[] PacketData = Packet.GetPacket();
if (this.HasSniffers)
this.Information("PINGRESP");
return this.Write(PacketData, 0, null);
}
/// <summary>
/// Event raised when a connection to a broker could not be made.
/// </summary>
public event MqttExceptionEventHandler OnConnectionError = null;
/// <summary>
/// Event raised when an error was encountered.
/// </summary>
public event MqttExceptionEventHandler OnError = null;
/// <summary>
/// Event raised whenever a ping message is sent, i.e. when connection is idle.
/// </summary>
public event EventHandlerAsync OnPing = null;
/// <summary>
/// Event raised whenever a ping response is received, i.e. when connection is kept active, while idle.
/// </summary>
public event EventHandlerAsync OnPingResponse = null;
/// <summary>
/// Host or IP address of MQTT server.
/// </summary>
public string Host => this.host;
/// <summary>
/// Port number to connect to.
/// </summary>
public int Port => this.port;
/// <summary>
/// If encryption is to be used or not.
/// </summary>
public bool Tls => this.tls;
/// <summary>
/// If server should be trusted, regardless if the operating system could validate its certificate or not.
/// </summary>
public bool TrustServer
{
get => this.trustServer;
set => this.trustServer = value;
}
/// <summary>
/// Client ID
/// </summary>
public string ClientId => this.clientId;
/// <summary>
/// Certificate used by the server.
/// </summary>
#if WINDOWS_UWP
public Certificate ServerCertificate
#else
public X509Certificate ServerCertificate
#endif
{
get { return this.client?.RemoteCertificate; }
}
/// <summary>
/// If the server certificate is valid.
/// </summary>
public bool ServerCertificateValid => this.client?.RemoteCertificateValid ?? false;
/// <summary>
/// Current state of connection.
/// </summary>
public MqttState State
{
get => this.state;
internal set
{
if (this.state != value)
{
this.state = value;
this.Information("Switching state to " + value.ToString());
this.RaiseOnStateChanged(value);
}
}
}
private async void RaiseOnStateChanged(MqttState State)
{
StateChangedEventHandler h = this.OnStateChanged;
if (!(h is null))
{
try
{
await h(this, State);
}
catch (Exception ex)
{
this.Exception(ex);
}
}
}
/// <summary>
/// Event raised whenever the internal state of the connection changes.
/// </summary>
public event StateChangedEventHandler OnStateChanged = null;
private ushort packetIdentifier = 0;
/// <summary>
/// Publishes information on a topic.
/// </summary>
/// <param name="Topic">Topic name</param>
/// <param name="QoS">Quality of service</param>
/// <param name="Retain">If topic should retain information.</param>
/// <param name="Data">Binary data to send.</param>
/// <returns>Packet identifier assigned to data.</returns>
public Task<ushort> PUBLISH(string Topic, MqttQualityOfService QoS, bool Retain, byte[] Data)
{
return this.PUBLISH(Topic, QoS, Retain, false, Data);
}
/// <summary>
/// Publishes information on a topic.
/// </summary>
/// <param name="Topic">Topic name</param>
/// <param name="QoS">Quality of service</param>
/// <param name="Retain">If topic should retain information.</param>
/// <param name="Data">Binary data to send.</param>
/// <returns>Packet identifier assigned to data.</returns>
public Task<ushort> PUBLISH(string Topic, MqttQualityOfService QoS, bool Retain, BinaryOutput Data)
{
return this.PUBLISH(Topic, QoS, Retain, false, Data.GetPacket());
}
private async Task<ushort> PUBLISH(string Topic, MqttQualityOfService QoS, bool Retain, bool Duplicate, byte[] Data)
{
BinaryOutput Payload = new BinaryOutput();
ushort PacketIdentifier;
Payload.WriteString(Topic);
if (QoS > MqttQualityOfService.AtMostOnce)
{