-
Notifications
You must be signed in to change notification settings - Fork 5
/
uMQTTServer.pas
2472 lines (2303 loc) · 75.8 KB
/
uMQTTServer.pas
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
unit uMQTTServer;
{$mode delphi}{$H+}
interface
uses
Classes, SysUtils, GlobalTypes, Winsock2, uMQTT, Threads, Platform, SyncObjs;
const
MinVersion = 3;
stInit = 0;
stClosed = 1;
stConnecting = 2;
stConnected = 3;
stClosing = 4;
stError = 5;
stQuitting = 6;
type
TMQTTClient = class;
TMQTTThread = class;
TMQTTPacketStore = class;
TMQTTMessageStore = class;
TMQTTServer = class;
TTimerRec = record
Owner : TObject;
No : LongWord;
Handle : TTimerHandle;
end;
PTimerRec = ^TTimerRec;
TMQTTPacket = class
ID : Word;
Stamp : TDateTime;
Counter : cardinal;
Retries : integer;
Publishing : Boolean;
Msg : TMemoryStream;
procedure Assign (From : TMQTTPacket);
constructor Create;
destructor Destroy; override;
end;
TMQTTMessage = class
ID : Word;
Stamp : TDateTime;
LastUsed : TDateTime;
Qos : TMQTTQOSType;
Retained : boolean;
Counter : cardinal;
Retries : integer;
Topic : UTF8String;
Message : string;
procedure Assign (From : TMQTTMessage);
constructor Create;
destructor Destroy; override;
end;
TMQTTSession = class
ClientID : UTF8String;
Stamp : TDateTime;
InFlight : TMQTTPacketStore;
Releasables : TMQTTMessageStore;
constructor Create;
destructor Destroy; override;
end;
TMQTTSessionStore = class
List : TList;
Stamp : TDateTime;
function GetItem (Index: Integer): TMQTTSession;
procedure SetItem (Index: Integer; const Value: TMQTTSession);
property Items [Index: Integer]: TMQTTSession read GetItem write SetItem; default;
function Count : integer;
procedure Clear;
function GetSession (ClientID : UTF8String) : TMQTTSession;
procedure StoreSession (ClientID : UTF8String; aClient : TMQTTThread); overload;
procedure StoreSession (ClientID : UTF8String; aClient : TMQTTClient); overload;
procedure DeleteSession (ClientID : UTF8String);
procedure RestoreSession (ClientID : UTF8String; aClient : TMQTTThread); overload;
procedure RestoreSession (ClientID : UTF8String; aClient : TMQTTClient); overload;
constructor Create;
destructor Destroy; override;
end;
TMQTTPacketStore = class
List : TList;
Stamp : TDateTime;
function GetItem (Index: Integer): TMQTTPacket;
procedure SetItem (Index: Integer; const Value: TMQTTPacket);
property Items [Index: Integer]: TMQTTPacket read GetItem write SetItem; default;
function Count : integer;
procedure Clear;
procedure Assign (From : TMQTTPacketStore);
function AddPacket (anID : Word; aMsg : TMemoryStream; aRetry : cardinal; aCount : cardinal) : TMQTTPacket;
procedure DelPacket (anID : Word);
function GetPacket (anID : Word) : TMQTTPacket;
procedure Remove (aPacket : TMQTTPacket);
constructor Create;
destructor Destroy; override;
end;
TMQTTMessageStore = class
List : TList;
Stamp : TDateTime;
function GetItem (Index: Integer): TMQTTMessage;
procedure SetItem (Index: Integer; const Value: TMQTTMessage);
property Items [Index: Integer]: TMQTTMessage read GetItem write SetItem; default;
function Count : integer;
procedure Clear;
procedure Assign (From : TMQTTMessageStore);
function AddMsg (anID : Word; aTopic : UTF8String; aMessage : AnsiString; aQos : TMQTTQOSType; aRetry : cardinal; aCount : cardinal; aRetained : Boolean = false) : TMQTTMessage;
procedure DelMsg (anID : Word);
function GetMsg (anID : Word) : TMQTTMessage;
procedure Remove (aMsg : TMQTTMessage);
constructor Create;
destructor Destroy; override;
end;
TMQTTThread = class (TWinsock2TCPServerThread)
private
FOnMon : TMQTTMonEvent;
Owner : TMQTTServer;
FGraceful : boolean;
FBroker : Boolean; // non standard
FOnSubscriptionChange: TNotifyEvent;
procedure DoSend (Sender : TObject; anID : Word; aRetry : integer; aStream : TMemoryStream);
procedure RxSubscribe (Sender : TObject; anID : Word; Topics : TStringList);
procedure RxUnsubscribe (Sender : TObject; anID : Word; Topics : TStringList);
procedure RxPubAck (Sender : TObject; anID : Word);
procedure RxPubRec (Sender : TObject; anID : Word);
procedure RxPubRel (Sender : TObject; anID : Word);
procedure RxPubComp (Sender : TObject; anID : Word);
public
Subscriptions : TStringList;
Parser : TMQTTParser;
InFlight : TMQTTPacketStore;
Releasables : TMQTTMessageStore;
procedure DoSetWill (Sender : TObject; aTopic, aMessage : UTF8String; aQOS : TMQTTQOSType; aRetain : boolean);
constructor Create (aServer : TWinsock2TCPServer);
destructor Destroy; override;
property OnSubscriptionChange : TNotifyEvent read FOnSubscriptionChange write FOnSubscriptionChange;
property OnMon : TMQTTMonEvent read FOnMon write FOnMon;
end;
{ TMQTTClient }
TMQTTClient = class (TThread)
private
Timers : array [1 .. 3] of TTimerRec;
FUsername, FPassword : UTF8String;
FMessageID : Word;
FHost : string;
FPort : integer;
FState : integer;
FEnable, FOnline : Boolean;
FGraceful : Boolean;
FOnOnline: TNotifyEvent;
FOnOffline: TMQTTDisconnectEvent;
FOnEnableChange: TNotifyEvent;
FOnMsg: TMQTTMsgEvent;
FOnFailure: TMQTTFailureEvent;
FLocalBounce: Boolean;
FAutoSubscribe: Boolean;
FOnClientID : TMQTTClientIDEvent;
FBroker: Boolean; // non standard
FEvent : TEvent;
procedure DoSend (Sender : TObject; anID : Word; aRetry : integer; aStream : TMemoryStream);
procedure RxConnAck (Sender : TObject; aCode : byte);
procedure RxSubAck (Sender : TObject; anID : Word; Qoss : array of TMQTTQosType);
procedure RxPubAck (Sender : TObject; anID : Word);
procedure RxPubRec (Sender : TObject; anID : Word);
procedure RxPubRel (Sender : TObject; anID : Word);
procedure RxPubComp (Sender : TObject; anID : Word);
procedure RxPublish (Sender : TObject; anID : Word; aTopic : UTF8String; aMessage : string);
procedure RxUnsubAck (Sender : TObject; anID : Word);
function GetClientID: UTF8String;
procedure SetClientID (const Value: UTF8String);
function GetKeepAlive: Word;
procedure SetKeepAlive (const Value: Word);
function GetMaxRetries : integer;
procedure SetMaxRetries (const Value: integer);
function GetRetryTime : cardinal;
procedure SetRetryTime (const Value : cardinal);
function GetClean: Boolean;
procedure SetClean (const Value: Boolean);
function GetPassword: UTF8String;
function GetUsername: UTF8String;
procedure SetPassword (const Value: UTF8String);
procedure SetUsername (const Value: UTF8String);
protected
procedure SetState (NewState : integer);
procedure Execute; override;
public
Link : TWinsock2TCPClient;
Parser : TMQTTParser;
InFlight : TMQTTPacketStore;
Releasables : TMQTTMessageStore;
Subscriptions : TStringList;
procedure SetTimer (No, Interval : LongWord; Once : boolean);
procedure KillTimer (No : Longword);
function Enabled : boolean;
function Online : boolean;
function NextMessageID : Word;
procedure Subscribe (aTopic : UTF8String; aQos : TMQTTQOSType); overload;
procedure Subscribe (Topics : TStringList); overload;
procedure Unsubscribe (aTopic : UTF8String); overload;
procedure Unsubscribe (Topics : TStringList); overload;
procedure Ping;
procedure Publish (aTopic : UTF8String; aMessage : string; aQos : TMQTTQOSType; aRetain : Boolean = false);
procedure SetWill (aTopic, aMessage : UTF8String; aQos : TMQTTQOSType; aRetain : Boolean = false);
procedure Activate (Enable : Boolean);
constructor Create;
destructor Destroy; override;
published
property ClientID : UTF8String read GetClientID write SetClientID;
property KeepAlive : Word read GetKeepAlive write SetKeepAlive;
property MaxRetries : integer read GetMaxRetries write SetMaxRetries;
property RetryTime : cardinal read GetRetryTime write SetRetryTime;
property Clean : Boolean read GetClean write SetClean;
property Broker : Boolean read FBroker write FBroker; // no standard
property AutoSubscribe : Boolean read FAutoSubscribe write FAutoSubscribe;
property Username : UTF8String read GetUsername write SetUsername;
property Password : UTF8String read GetPassword write SetPassword;
property Host : string read FHost write FHost;
property Port : integer read FPort write FPort;
property LocalBounce : Boolean read FLocalBounce write FLocalBounce;
property OnClientID : TMQTTClientIDEvent read FOnClientID write FOnClientID;
property OnOnline : TNotifyEvent read FOnOnline write FOnOnline;
property OnOffline : TMQTTDisconnectEvent read FOnOffline write FOnOffline;
property OnEnableChange : TNotifyEvent read FOnEnableChange write FOnEnableChange;
property OnFailure : TMQTTFailureEvent read FOnFailure write FOnFailure;
property OnMsg : TMQTTMsgEvent read FOnMsg write FOnMsg;
end;
{ TMQTTServer }
TMQTTServer = class (TWinsock2TCPListener)
protected
procedure DoConnect (aThread : TWinsock2TCPServerThread); override;
procedure DoDisconnect (aThread : TWinsock2TCPServerThread); override;
function DoExecute (aThread : TWinsock2TCPServerThread) : Boolean; override;
private
FOnMon : TMQTTMonEvent;
FOnClientsChange: TMQTTIDEvent;
FOnCheckUser: TMQTTCheckUserEvent;
FPort : integer;
FEnable : boolean;
FOnBrokerOffline: TMQTTDisconnectEvent;
FOnBrokerOnline: TNotifyEvent;
FOnBrokerEnableChange: TNotifyEvent;
FOnObituary: TMQTTObituaryEvent;
FOnEnableChange: TNotifyEvent;
FLocalBounce: Boolean;
FOnSubscription: TMQTTSubscriptionEvent;
FOnFailure: TMQTTFailureEvent;
FMaxRetries: integer;
FRetryTime: cardinal;
FOnStoreSession: TMQTTSessionEvent;
FOnRestoreSession: TMQTTSessionEvent;
FOnDeleteSession: TMQTTSessionEvent;
// FOnRetain: TMQTTRetainEvent;
// FOnGetRetained: TMQTTRetainedEvent;
// broker events
procedure BkrOnline (Sender : TObject);
procedure BkrOffline (Sender : TObject; Graceful : boolean);
procedure BkrEnableChanged (Sender : TObject);
procedure BkrSubscriptionChange (Sender : TObject);
procedure BkrMsg (Sender : TObject; aTopic : UTF8String; aMessage : AnsiString; aQos : TMQTTQOSType; aRetained : boolean);
// socket events
procedure DoCreateThread (aServer : TWinsock2TCPServer; var aThread : TWinsock2TCPServerThread);
// procedure DoClientConnect (Sender: TObject; Client: TWSocketClient; Error: Word);
// procedure DoClientDisconnect (Sender: TObject; Client: TWSocketClient; Error: Word);
// procedure DoClientCreate (Sender: TObject; Client: TWSocketClient);
// parser events
procedure RxDisconnect (Sender : TObject);
procedure RxPing (Sender : TObject);
procedure RxPublish (Sender : TObject; anID : Word; aTopic : UTF8String; aMessage : AnsiString);
procedure RxHeader (Sender : TObject; MsgType: TMQTTMessageType; Dup: Boolean;
Qos: TMQTTQOSType; Retain: Boolean);
procedure RxConnect (Sender : TObject;
aProtocol : UTF8String;
aVersion : byte;
aClientID,
aUserName, aPassword : UTF8String;
aKeepAlive : Word; aClean : Boolean);
procedure RxBrokerConnect (Sender : TObject; // non standard
aProtocol : UTF8String;
aVersion : byte;
aClientID,
aUserName, aPassword : UTF8String;
aKeepAlive : Word; aClean : Boolean);
procedure SetMaxRetries (const Value: integer);
procedure SetRetryTime (const Value: cardinal);
public
FOnMonHdr : TMQTTHeaderEvent;
Timers : array [1 .. 3] of TTimerRec;
MessageID : Word;
Brokers : TList;
Sessions : TMQTTSessionStore;
Retained : TMQTTMessageStore;
procedure SetTimer (No, Interval : LongWord; Once : boolean);
procedure KillTimer (No : Longword);
function NextMessageID : Word;
procedure Activate (Enable : boolean);
procedure LoadBrokers (anIniFile : string);
procedure StoreBrokers (anIniFile : string);
function GetClient (aParser : TMQTTParser) : TMQTTThread; overload;
function GetClient (aClientID : UTF8String) : TMQTTThread; overload;
procedure PublishToAll (From : TObject; aTopic : UTF8String; aMessage : AnsiString; aQos : TMQTTQOSType; wasRetained : boolean = false);
function Enabled : boolean;
function AddBroker (aHost : string; aPort : integer) : TMQTTClient;
procedure SyncBrokerSubscriptions (aBroker : TMQTTClient);
constructor Create;
destructor Destroy; override;
published
property MaxRetries : integer read FMaxRetries write SetMaxRetries;
property RetryTime : cardinal read FRetryTime write SetRetryTime; // in secs
property Port : integer read FPort write FPort;
property LocalBounce : Boolean read FLocalBounce write FLocalBounce;
property OnFailure : TMQTTFailureEvent read FOnFailure write FOnFailure;
property OnStoreSession : TMQTTSessionEvent read FOnStoreSession write FOnStoreSession;
property OnRestoreSession : TMQTTSessionEvent read FOnRestoreSession write FOnRestoreSession;
property OnDeleteSession : TMQTTSessionEvent read FOnDeleteSession write FOnDeleteSession;
// property OnRetain : TMQTTRetainEvent read FOnRetain write FOnRetain;
// property OnGetRetained : TMQTTRetainedEvent read FOnGetRetained write FOnGetRetained;
property OnBrokerOnline : TNotifyEvent read FOnBrokerOnline write FOnBrokerOnline;
property OnBrokerOffline : TMQTTDisconnectEvent read FOnBrokerOffline write FOnBrokerOffline;
property OnBrokerEnableChange : TNotifyEvent read FOnBrokerEnableChange write FOnBrokerEnableChange;
property OnEnableChange : TNotifyEvent read FOnEnableChange write FOnEnableChange;
property OnSubscription : TMQTTSubscriptionEvent read FOnSubscription write FOnSubscription;
property OnClientsChange : TMQTTIDEvent read FOnClientsChange write FOnClientsChange;
property OnCheckUser : TMQTTCheckUserEvent read FOnCheckUser write FOnCheckUser;
property OnObituary : TMQTTObituaryEvent read FOnObituary write FOnObituary;
property OnMon : TMQTTMonEvent read FOnMon write FOnMon;
end;
function SubTopics (aTopic : UTF8String) : TStringList;
function IsSubscribed (aSubscription, aTopic : UTF8String) : boolean;
implementation
uses
IniFiles, uLog, GlobalConst;
function StateToStr (s : integer) : string;
begin
case s of
stInit : Result := 'Init';
stClosed : Result := 'Closed';
stConnecting : Result := 'Connecting';
stConnected : Result := 'Connected';
stClosing : Result := 'Closing';
stError : Result := 'Error';
stQuitting : Result := 'Quitting';
else Result := 'Unknown ' + IntToStr (s);
end;
end;
function SubTopics (aTopic : UTF8String) : TStringList;
var
i : integer;
begin
Result := TStringList.Create;
Result.Add ('');
for i := 1 to length (aTopic) do
begin
if aTopic[i] = '/' then
Result.Add ('')
else
Result[Result.Count - 1] := Result[Result.Count - 1] + Char (aTopic[i]);
end;
end;
function IsSubscribed (aSubscription, aTopic : UTF8String) : boolean;
var
s, t : TStringList;
i : integer;
MultiLevel : Boolean;
begin
s := SubTopics (aSubscription);
t := SubTopics (aTopic);
MultiLevel := (s[s.Count - 1] = '#'); // last field is #
if not MultiLevel then
Result := (s.Count = t.Count)
else
Result := (s.Count <= t.Count + 1);
if Result then
begin
for i := 0 to s.Count - 1 do
begin
if (i >= t.Count) then Result := MultiLevel
else if (i = s.Count - 1) and (s[i] = '#') then break
else if s[i] = '+' then continue // they match
else
Result := Result and (s[i] = t[i]);
if not Result then break;
end;
end;
s.Free;
t.Free;
end;
procedure SetDup (aStream : TMemoryStream; aState : boolean);
var
x : byte;
begin
if aStream.Size = 0 then exit;
aStream.Seek (0, soFromBeginning);
x := 0;
aStream.Read (x, 1);
x := (x and $F7) or (ord (aState) * $08);
aStream.Seek (0, soFromBeginning);
aStream.Write (x, 1);
end;
{ TMQTTThread }
constructor TMQTTThread.Create (aServer : TWinsock2TCPServer);
begin
inherited Create (aServer);
FBroker := false; // non standard
Parser := TMQTTParser.Create;
Parser.OnSend := DoSend;
Parser.OnSetWill := DoSetWill;
Parser.OnSubscribe := RxSubscribe;
Parser.OnUnsubscribe := RxUnsubscribe;
Parser.OnPubAck := RxPubAck;
Parser.OnPubRel := RxPubRel;
Parser.OnPubRec := RxPubRec;
Parser.OnPubComp := RxPubComp;
InFlight := TMQTTPacketStore.Create;
Releasables := TMQTTMessageStore.Create;
Subscriptions := TStringList.Create;
end;
destructor TMQTTThread.Destroy;
begin
InFlight.Clear;
InFlight.Free;
Releasables.Clear;
Releasables.Free;
Parser.Free;
Subscriptions.Free;
inherited;
end;
procedure TMQTTThread.DoSend (Sender: TObject; anID : Word; aRetry : integer; aStream: TMemoryStream);
var
x : byte;
begin
// if FState = stConnected then
// begin
x := 0;
aStream.Seek (0, soFromBeginning);
aStream.Read (x, 1);
if (TMQTTQOSType ((x and $06) shr 1) in [qtAT_LEAST_ONCE, qtEXACTLY_ONCE]) and
(TMQTTMessageType ((x and $f0) shr 4) in [{mtPUBREL,} mtPUBLISH, mtSUBSCRIBE, mtUNSUBSCRIBE]) and
(anID > 0) then
begin
InFlight.AddPacket (anID, aStream, aRetry, Parser.RetryTime); // start disabled
Log (Parser.ClientID + ' Message ' + IntToStr (anID) + ' created.');
end;
Server.WriteData (aStream.Memory, aStream.Size);
// end;
end;
procedure TMQTTThread.DoSetWill (Sender: TObject; aTopic, aMessage: UTF8String;
aQos : TMQTTQOSType; aRetain: boolean);
begin
Parser.WillTopic := aTopic;
Parser.WillMessage := aMessage;
Parser.WillQos := aQos;
Parser.WillRetain := aRetain;
end;
procedure TMQTTThread.RxPubAck (Sender: TObject; anID: Word);
begin
InFlight.DelPacket (anID);
Log (Parser.ClientID + ' ACK Message ' + IntToStr (anID) + ' disposed of.');
end;
procedure TMQTTThread.RxPubComp (Sender: TObject; anID: Word);
begin
InFlight.DelPacket (anID);
Log (Parser.ClientID + ' COMP Message ' + IntToStr (anID) + ' disposed of.');
end;
procedure TMQTTThread.RxPubRec (Sender: TObject; anID: Word);
var
aPacket : TMQTTPacket;
begin
aPacket := InFlight.GetPacket (anID);
if aPacket <> nil then
begin
aPacket.Counter := Parser.RetryTime;
if aPacket.Publishing then
begin
aPacket.Publishing := false;
Log (Parser.ClientID + ' REC Message ' + IntToStr (anID) + ' recorded.');
end
else
Log (Parser.ClientID + ' REC Message ' + IntToStr (anID) + ' already recorded.');
end
else
Log (Parser.ClientID + ' REC Message ' + IntToStr (anID) + ' not found.');
Parser.SendPubRel (anID);
end;
procedure TMQTTThread.RxPubRel (Sender: TObject; anID: Word);
var
aMsg : TMQTTMessage;
begin
aMsg := Releasables.GetMsg (anID);
if aMsg <> nil then
begin
Log (Parser.ClientID + ' REL Message ' + IntToStr (anID) + ' publishing @ ' + QOSNames[aMsg.Qos]);
Owner.PublishToAll (Self, aMsg.Topic, aMsg.Message, aMsg.Qos);
Releasables.Remove (aMsg);
aMsg.Free;
Log (Parser.ClientID + ' REL Message ' + IntToStr (anID) + ' removed from storage.');
end
else
Log (Parser.ClientID + ' REL Message ' + IntToStr (anID) + ' has been already removed from storage.');
Parser.SendPubComp (anID);
end;
procedure TMQTTThread.RxSubscribe (Sender: TObject; anID: Word; Topics: TStringList);
var
x : cardinal;
q : TMQTTQOSType;
i, j : integer;
found : boolean;
Qoss : array of TMQTTQOSType;
bMsg : TMQTTMessage;
aQos : TMQTTQOSType;
begin
SetLength (Qoss, Topics.Count);
for i := 0 to Topics.Count - 1 do
begin
found := false;
x := cardinal (Topics.Objects[i]) and $03;
q := TMQTTQOSType (x);
if Assigned (Owner.FOnSubscription) then
Owner.FOnSubscription (Self, UTF8String (Topics[i]), q);
for j := 0 to Subscriptions.Count - 1 do
if Subscriptions[j] = Topics[i] then
begin
found := true;
Subscriptions.Objects[j] := TObject (q);
break;
end;
if not found then
begin
Subscriptions.AddObject (Topics[i], TObject (q));
end;
Qoss[i] := q;
for j := 0 to Owner.Retained.Count - 1 do // set retained
begin
bMsg := Owner.Retained[j];
if IsSubscribed (UTF8String (Topics[i]), bMsg.Topic) then
begin
aQos := bMsg.Qos;
if q < aQos then aQos := q;
bMsg.LastUsed := Now;
Parser.SendPublish (Owner.NextMessageID, bMsg.Topic, bMsg.Message, aQos, false, true);
end;
end;
end;
if Parser.RxQos = qtAT_LEAST_ONCE then Parser.SendSubAck (anID, Qoss);
if Assigned (FOnSubscriptionChange) then FOnSubscriptionChange (Self);
end;
procedure TMQTTThread.RxUnsubscribe (Sender: TObject; anID: Word; Topics: TStringList);
var
i, j : integer;
changed : boolean;
begin
changed := false;
for i := 0 to Topics.Count - 1 do
begin
for j := Subscriptions.Count - 1 downto 0 do
begin
if Subscriptions[j] = Topics[i] then
begin
Subscriptions.Delete (j);
changed := true;
end;
end;
end;
if changed and Assigned (FOnSubscriptionChange) then
FOnSubscriptionChange (Self);
if Parser.RxQos = qtAT_LEAST_ONCE then Parser.SendUnSubAck (anID);
end;
{ TMQTTServer }
procedure TMQTTServer.Activate (Enable: boolean);
begin
if FEnable = Enable then exit;
if (Enable) then
begin
BoundPort := FPort;
try
Active := true;
FEnable := true;
except
FEnable := false;
end;
if FEnable then SetTimer (3, 100, true);
end
else
begin
FEnable := false;
Active := false;
KillTimer (1);
KillTimer (2);
KillTimer (3);
end;
if Assigned (FOnEnableChange) then FOnEnableChange (Self);
end;
function TMQTTServer.AddBroker (aHost: string; aPort: integer): TMQTTClient;
begin
Result := TMQTTClient.Create;
Result.Host := aHost;
Result.Port := aPort;
Result.Broker := true;
Result.LocalBounce := false;
Result.OnOnline := BkrOnline;
Result.OnOffline := BkrOffline;
Result.OnEnableChange := BkrEnableChanged;
Result.OnMsg := BkrMsg;
Brokers.Add (Result);
end;
procedure TMQTTServer.BkrEnableChanged (Sender: TObject);
begin
if Assigned (FOnBrokerEnableChange) then FOnBrokerEnableChange (Sender);
end;
procedure TMQTTServer.BkrOffline (Sender: TObject; Graceful: boolean);
begin
TMQTTClient (Sender).Subscriptions.Clear;
if Assigned (FOnBrokerOffline) then FOnBrokerOffline (Sender, Graceful);
end;
procedure TMQTTServer.BkrOnline (Sender: TObject);
begin
SyncBrokerSubscriptions (TMQTTClient (Sender));
if Assigned (FOnBrokerOnline) then FOnBrokerOnline (Sender);
end;
procedure TMQTTServer.BkrMsg (Sender: TObject; aTopic : UTF8String; aMessage : AnsiString; aQos : TMQTTQOSType; aRetained : boolean);
var
aBroker : TMQTTClient;
i : integer;
aMsg : TMQTTMessage;
begin
aBroker := TMQTTClient (Sender);
Log ('Received Retained Message from a Broker - Retained ' + ny[aRetained]);
if aRetained then
begin
Log ('Retaining "' + string (aTopic) + '" @ ' + QOSNames[aQos]);
for i := Retained.Count - 1 downto 0 do
begin
aMsg := Retained[i];
if aMsg.Topic = aTopic then
begin
Retained.Remove (aMsg);
aMsg.Free;
break;
end;
end;
Retained.AddMsg (0, aTopic, aMessage, aQos, 0, 0);
end
else
Log ('Received Message from a Broker - Publishing..');
PublishToAll (Sender, aTopic, aMessage, aBroker.Parser.RxQos, aRetained);
end;
procedure TMQTTServer.DoCreateThread (aServer: TWinsock2TCPServer;
var aThread: TWinsock2TCPServerThread);
begin
Log ('Thread Created');
aThread := TMQTTThread.Create (aServer);
with TMQTTThread (aThread) do
begin
Owner := Self;
Parser.OnPing := RxPing;
Parser.OnDisconnect := RxDisconnect;
Parser.OnPublish := RxPublish;
Parser.OnPubRec := RxPubRec;
Parser.OnConnect := RxConnect;
Parser.OnBrokerConnect := RxBrokerConnect; // non standard
Parser.OnHeader := RxHeader;
Parser.MaxRetries := FMaxRetries;
Parser.RetryTime := FRetryTime;
OnSubscriptionChange := BkrSubscriptionChange;
end;
end;
procedure TMQTTServer.DoConnect (aThread: TWinsock2TCPServerThread);
begin
inherited DoConnect (aThread);
Log ('Connect');
// if Assigned (
end;
procedure TMQTTServer.DoDisconnect (aThread: TWinsock2TCPServerThread);
var
aTopic, aMessage : UTF8String;
aQos : TMQTTQOSType;
aClient : TMQTTThread;
begin
aClient := TMQTTThread (aThread);
with aClient do
begin
Log ('Client Disconnected. Graceful ' + ny[FGraceful]);
if (InFlight.Count > 0) or (Releasables.Count > 0) then
begin
if Assigned (FOnStoreSession) then
FOnStoreSession (aClient, Parser.ClientID)
else
Sessions.StoreSession (Parser.ClientID, aClient);
end;
if not FGraceful then
begin
aTopic := Parser.WillTopic;
aMessage := Parser.WillMessage;
aQos := Parser.WillQos;
if Assigned (FOnObituary) then FOnObituary (aClient, aTopic, aMessage, aQos);
PublishToAll (nil, aTopic, aMessage, aQos);
end;
end;
if Assigned (FOnClientsChange) then FOnClientsChange (Self, Threads.Count - 1);
inherited DoDisconnect (aThread);
end;
function TMQTTServer.DoExecute (aThread: TWinsock2TCPServerThread): Boolean;
var
aClient : TMQTTThread;
d : boolean;
b : array [0..255] of byte;
c : integer;
closed : boolean;
begin
Result := inherited DoExecute (aThread);
aClient := TMQTTThread (aThread);
c := 256;
closed := false;
d := aThread.Server.ReadAvailable (@b[0], 255, c, closed);
if closed or not d then Result := false;
if (c = 0) or closed then exit;
aClient.Parser.Parse (@b[0], c);
end;
procedure TMQTTServer.BkrSubscriptionChange (Sender: TObject);
var
i : integer;
begin
Log ('Subscriptions changed...');
for i := 0 to Brokers.Count - 1 do
SyncBrokerSubscriptions (TMQTTClient (Brokers[i]));
end;
constructor TMQTTServer.Create;
var
i : integer;
begin
inherited;
for i := 1 to 3 do
begin
Timers[i].Handle := INVALID_HANDLE_VALUE;
Timers[i].No := i;
Timers[i].Owner := Self;
end;
MessageID := 1000;
FOnMonHdr := nil;
FPort := 1883;
FMaxRetries := DefMaxRetries;
FRetryTime := DefRetryTime;
Brokers := TList.Create;
Sessions := TMQTTSessionStore.Create;
Retained := TMQTTMessageStore.Create;
OnCreateThread := DoCreateThread;
end;
destructor TMQTTServer.Destroy;
var
i : integer;
begin
for i := 1 to 3 do KillTimer (i);
for i := 0 to Brokers.Count - 1 do TMQTTClient (Brokers[i]).Free;
Brokers.Free;
Retained.Free;
Sessions.Free;
Activate (false);
inherited;
end;
procedure TMQTTServer.RxPing (Sender: TObject);
begin
if not (Sender is TMQTTParser) then exit;
TMQTTParser (Sender).SendPingResp;
end;
procedure TMQTTServer.RxPublish (Sender: TObject; anID: Word; aTopic : UTF8String;
aMessage: AnsiString);
var
aParser : TMQTTParser;
aClient : TMQTTThread;
aMsg : TMQTTMessage;
i : integer;
begin
if not (Sender is TMQTTParser) then exit;
aParser := TMQTTParser (Sender);
aClient := GetClient (aParser);
if aClient = nil then exit;
if aParser.RxRetain then
begin
Log ('Retaining "' + string (aTopic) + '" @ ' + QOSNames[aParser.RxQos]);
for i := Retained.Count - 1 downto 0 do
begin
aMsg := Retained[i];
if aMsg.Topic = aTopic then
begin
Retained.Remove (aMsg);
aMsg.Free;
break;
end;
end;
Retained.AddMsg (0, aTopic, aMessage, aParser.RxQos, 0, 0);
end;
case aParser.RxQos of
qtAT_MOST_ONCE :
PublishToAll (aClient, aTopic, aMessage, aParser.RxQos, aParser.RxRetain);
qtAT_LEAST_ONCE :
begin
aParser.SendPubAck (anID);
PublishToAll (aClient, aTopic, aMessage, aParser.RxQos, aParser.RxRetain);
end;
qtEXACTLY_ONCE :
begin
aMsg := aClient.Releasables.GetMsg (anID);
if aMsg = nil then
begin
aClient.Releasables.AddMsg (anID, aTopic, aMessage, aParser.RxQos, 0, 0);
Log (aClient.Parser.ClientID + ' Message ' + IntToStr (anID) + ' stored and idle.');
end
else
Log (aClient.Parser.ClientID + ' Message ' + IntToStr (anID) + ' already stored.');
aParser.SendPubRec (anID);
end;
end;
end;
procedure TMQTTServer.LoadBrokers (anIniFile: string);
var
i : integer;
Sections : TStringList;
aBroker : TMQTTClient;
EnFlag : Boolean;
begin
for i := 0 to Brokers.Count - 1 do TMQTTClient (Brokers[i]).Free;
Brokers.Clear;
Sections := TStringList.Create;
with TIniFile.Create (anIniFile) do
begin
ReadSections (Sections);
for i := 0 to Sections.Count - 1 do
begin
if Copy (Sections[i], 1, 6) = 'BROKER' then
begin
aBroker := AddBroker ('', 0);
aBroker.Host := ReadString (Sections[i], 'Prim Host', '');
aBroker.Port := ReadInteger (Sections[i], 'Port', 1883);
EnFlag := ReadBool (Sections[i], 'Enabled', false);
if EnFlag then aBroker.Activate (true);
end;
end;
Free;
end;
Sections.Free;
end;
procedure TMQTTServer.SetMaxRetries (const Value: integer);
var
i : integer;
aClient : TMQTTThread;
begin
FMaxRetries := Value;
aClient := TMQTTThread (Threads.First);
while aClient <> nil do
begin
aClient.Parser.MaxRetries := Value;
aClient := TMQTTThread (aClient.Next);
end;
for i := 0 to Brokers.Count - 1 do
TMQTTClient (Brokers[i]).Parser.MaxRetries := Value;
end;
procedure TMQTTServer.SetRetryTime (const Value: cardinal);
var
i : integer;
aClient : TMQTTThread;
begin
FRetryTime := Value;
aClient := TMQTTThread (Threads.First);
while aClient <> nil do
begin
aClient.Parser.KeepAlive := Value;
aClient := TMQTTThread (aClient.Next);
end;
for i := 0 to Brokers.Count - 1 do
TMQTTClient (Brokers[i]).Parser.KeepAlive := Value;
end;
procedure ServerTimerTask (Data : Pointer);
var
j : integer;
bPacket : TMQTTPacket;
aClient : TMQTTThread;
aServer : TMQTTServer;
WillClose : Boolean;
begin
with PTimerRec (Data)^ do
begin
aServer := TMQTTServer (Owner);
log ('timer ' + No.ToString + ' triggered');
case No of
3 : begin
aClient := TMQTTThread (aServer.Threads.First);
while aClient <> nil do
begin
if not aClient.Parser.CheckKeepAlive then
begin
WillClose := true;
if Assigned (aServer.FOnFailure) then aServer.FOnFailure (aClient, frKEEPALIVE, WillClose);
if WillClose then aClient.Server.Disconnect;
end
else
begin
for j := aClient.InFlight.Count - 1 downto 0 do
begin
bPacket := aClient.InFlight[j];
if bPacket.Counter > 0 then
begin
bPacket.Counter := bPacket.Counter - 1;
if bPacket.Counter = 0 then
begin
bPacket.Retries := bPacket.Retries + 1;
if bPacket.Retries <= aClient.Parser.MaxRetries then
begin
if bPacket.Publishing then
begin
aClient.InFlight.List.Remove (bPacket);
Log ('Message ' + IntToStr (bPacket.ID) + ' disposed of..');
Log ('Re-issuing Message ' + inttostr (bPacket.ID) + ' Retry ' + inttostr (bPacket.Retries));
SetDup (bPacket.Msg, true);
aClient.DoSend (aClient.Parser, bPacket.ID, bPacket.Retries, bPacket.Msg);
bPacket.Free;
end
else
begin
Log ('Re-issuing PUBREL Message ' + inttostr (bPacket.ID) + ' Retry ' + inttostr (bPacket.Retries));
aClient.Parser.SendPubRel (bPacket.ID, true);
bPacket.Counter := aClient.Parser.RetryTime;
end;
end
else
begin
WillClose := true;
if Assigned (aServer.FOnFailure) then aServer.FOnFailure (aServer, frMAXRETRIES, WillClose);
if WillClose then aClient.Server.Disconnect;
end;
end;
end;
end;
end;
aClient := TMQTTThread (aClient.Next);
end;
end;
end;
end;
end;
procedure TMQTTServer.SetTimer (No, Interval: LongWord; Once : boolean);
var
Flags : Longword;
begin
if not (No in [1 .. 3]) then exit;
if Timers[No].Handle <> INVALID_HANDLE_VALUE then TimerDestroy (Timers[No].Handle);
if Once then Flags := TIMER_FLAG_NONE else Flags := TIMER_FLAG_RESCHEDULE;
Timers[No].Handle := TimerCreateEx (Interval, TIMER_STATE_ENABLED, Flags, ServerTimerTask, @Timers[No]);