-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMQTT.c
1470 lines (1226 loc) · 39.4 KB
/
MQTT.c
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
/*********************************************************************
*
* MQTT Internet Of Things (MQTT) Client
* Module for Microchip TCP/IP Stack
* -Provides ability to receive Emails
* -Reference: RFC 2821
*
*********************************************************************
* FileName: MQTT.c
* Dependencies: TCP, ARP, DNS, Tick
* Processor: PIC18, PIC24F, PIC24H, dsPIC30F, dsPIC33F, PIC32
* Compiler: Microchip C32 v1.05 or higher
* Microchip C30 v3.12 or higher
* Microchip C18 v3.30 or higher
* HI-TECH PICC-18 PRO 9.63PL2 or higher
* Company: Microchip Technology, Inc.
*
* Software License Agreement
*
* Copyright (C) 2002-2009 Microchip Technology Inc. All rights reserved.
* Copyright (C) 2013,2014 Cyberdyne. All rights reserved.
*
* Microchip licenses to you the right to use, modify, copy, and
* distribute:
* (i) the Software when embedded on a Microchip microcontroller or
* digital signal controller product ("Device") which is
* integrated into Licensee's product; or
* (ii) ONLY the Software driver source files ENC28J60.c, ENC28J60.h,
* ENCX24J600.c and ENCX24J600.h ported to a non-Microchip device
* used in conjunction with a Microchip ethernet controller for
* the sole purpose of interfacing with the ethernet controller.
*
* You should refer to the license agreement accompanying this
* Software for additional information regarding your rights and
* obligations.
* https://developer.ibm.com/iot/recipes/improvise/
* https://internetofthings.ibmcloud.com/dashboard/#/organizations/mkxk7/devices
* https://developer.ibm.com/iot/recipes/improvise-registered-devices/
*
* Author Date Comment
*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* Howard Schlunder 3/03/06 Original
* Howard Schlunder 11/2/06 Vastly improved for release
* Dario Greggio 30/9/14 client MQTT (IoT), inizio
* - A simple client for MQTT. Original Code - Nicholas O'Leary http://knolleary.net
* - Adapted for Spark Core by Chris Howard - chris@kitard.com (Based on PubSubClient 1.9.1)
* D. Guz 20/01/15 Fix, cleanup, testing
********************************************************************/
#define __MQTT_C
#include "TCPIPConfig.h"
#define MAKEWORD(a, b) ((word) (((BYTE) (a)) | ((WORD) ((BYTE) (b))) << 8))
#define MAKELONG(a, b) ((unsigned long) (((WORD) (a)) | ((DWORD) ((WORD) (b))) << 16))
#define HIBYTE(w) ((BYTE) (*((char *)&w+1))) // molto meglio :) ma NON su 24 o 32!
#define HIWORD(l) ((WORD) (((DWORD) (l) >> 16) & 0xFFFF))
#define LOBYTE(w) ((BYTE) (w))
#define LOWORD(l) ((WORD) (l))
//#define LOBYTE(var) (((unsigned char*)&var)[0])
//#define HIBYTE(var) (((unsigned char*)&var)[1])
#if defined(STACK_USE_MQTT_CLIENT)
#include "TCPIP Stack/TCPIP.h"
#include "TCPIP Stack/TCP.h"
#include "MQTT.h"
#include "generictypedefs.h"
// Should come from TCP.h but too many dependencies in that file
#define INVALID_SOCKET (0xFE) // The socket is invalid or could not be opened
#define UNKNOWN_SOCKET (0xFF) // The socket is not known
typedef BYTE TCP_SOCKET;
/****************************************************************************
Section:
MQTT Client Configuration Parameters
***************************************************************************/
#define MQTT_PORT 1883 // Default port to use when unspecified
#define MQTT_PORT_SECURE 8883 // Default port to use when unspecified
#define MQTT_SERVER_REPLY_TIMEOUT (TICK_SECOND*8) // How long to wait before assuming the connection has been dropped (default 8 seconds)
/****************************************************************************
Section:
MQTT Client Public Variables
***************************************************************************/
// The global set of MQTT_POINTERS.
// Set these parameters after calling MQTTBeginUsage successfully.
MQTT_POINTERS MQTTClient;
/****************************************************************************
Section:
MQTT Client Internal Variables
***************************************************************************/
static IP_ADDR MQTTServer; // IP address of the remote MQTT server
static TCP_SOCKET MySocket = INVALID_SOCKET; // Socket currently in use by the MQTT client
WORD MQTTResponseCode;
BYTE MQTTBuffer[MQTT_MAX_PACKET_SIZE];
static BYTE rxBF[200];
static WORD bytesRecieved = 0;
static WORD lastInActivity=0,lastOutActivity=0;
static WORD LastPingTick = 0;
// Message state machine for the MQTT Client
static enum {
/*
MQTT_HOME = 0, // Idle start state for MQTT client
MQTT_BEGIN, // Preparing to make connection
MQTT_NAME_RESOLVE, // Resolving the MQTT server address
MQTT_OBTAIN_SOCKET, // Obtaining a socket for the MQTT connection
MQTT_SOCKET_OBTAINED, // MQTT connection successful
//MQTT_CLOSE, // MQTT socket is closed
MQTT_CONNECT, // connection
MQTT_CONNECT_ACK, // connected
MQTT_PUBLISH, // Publish
MQTT_PUBLISH_ACK, // Publish command accepted (if QOS)
MQTT_PUBACK, // PublishACK
MQTT_SUBSCRIBE, // Subscribe
MQTT_SUBSCRIBE_ACK, // Subscribe command accepted (if QOS)
MQTT_UNSUBSCRIBE, // Subscribe
MQTT_UNSUBSCRIBE_ACK, // Subscribe command accepted (if QOS)
MQTT_PING, // Ping
MQTT_PING_ACK, // Pingback
MQTT_LOOP, // Idle Loop for receiving messages
MQTT_IDLE=MQTT_LOOP, // Idle Loop for receiving messages
MQTT_DISCONNECT_INIT, // Sending Disconnect
MQTT_DISCONNECT, // Disconnect accepted, and...
MQTT_QUIT // ...connection closing
} MQTTState;
*/
MQTT_HOME = 0,
MQTT_BEGIN,
MQTT_NAME_RESOLVE,
MQTT_OBTAIN_SOCKET,
MQTT_SOCKET_OBTAINED,
MQTT_CONNECT,
MQTT_CONNECT_ACK,
MQTT_PING,
MQTT_PING_ACK,
MQTT_PUBLISH,
MQTT_PUBLISH_ACK,
MQTT_SUBSCRIBE,
MQTT_SUBSCRIBE_ACK,
MQTT_PUBACK,
MQTT_UNSUBSCRIBE,
MQTT_UNSUBSCRIBE_ACK,
MQTT_DISCONNECT_INIT,
MQTT_DISCONNECT,
MQTT_CLOSE,
MQTT_QUIT,
MQTT_IDLE
} MQTTState;
// Internal flags used by the MQTT Client
static union {
BYTE Val;
struct {
unsigned char MQTTInUse:1;
unsigned char ReceivedSuccessfully:1;
unsigned char ConnectedOnce:1;
unsigned char PingOutstanding:1;
unsigned char filler:5;
} bits;
} MQTTFlags = {0x00};
/****************************************************************************
Section:
MQTT Client Internal Function Prototypes
***************************************************************************/
/****************************************************************************
Section:
MQTT Function Implementations
***************************************************************************/
/*****************************************************************************
Function:
BOOL MQTTBeginUsage(void)
Summary:
Requests control of the MQTT client module.
Description:
Call this function before calling any other MQTT Client APIs. This
function obtains a lock on the MQTT Client, which can only be used by
one stack application at a time. Once the application is finished
with the MQTT client, it must call MQTTEndUsage to release control
of the module to any other waiting applications.
This function initializes all the MQTT state machines and variables
back to their default state.
Precondition:
None
Parameters:
None
Return Values:
TRUE - The application has successfully obtained control of the module
FALSE - The MQTT module is in use by another application. Call
MQTTBeginUsage again later, after returning to the main program loop
***************************************************************************/
BOOL MQTTBeginUsage(void) {
if(MQTTFlags.bits.MQTTInUse)
return FALSE;
MQTTFlags.Val = 0x00;
MQTTFlags.bits.MQTTInUse = TRUE;
MQTTState = MQTT_BEGIN;
memset((void*)&MQTTClient, 0x00, sizeof(MQTTClient));
MQTTClient.Ver = MQTTPROTOCOLVERSION;
MQTTClient.KeepAlive = MQTT_KEEPALIVE_LONG;
MQTTClient.MsgId=1;
return TRUE;
}
/*****************************************************************************
Function:
WORD MQTTEndUsage(void)
Summary:
Releases control of the MQTT client module.
Description:
Call this function to release control of the MQTT client module once
an application is finished using it. This function releases the lock
obtained by MQTTBeginUsage, and frees the MQTT client to be used by
another application.
Precondition:
MQTTBeginUsage returned TRUE on a previous call.
Parameters:
None
Return Values:
MQTT_SUCCESS - A message was successfully sent
MQTT_RESOLVE_ERROR - The MQTT server could not be resolved
MQTT_CONNECT_ERROR - The connection to the MQTT server failed or was prematurely terminated
1-199 and 300-399 - The last MQTT server response code BOH!
***************************************************************************/
WORD MQTTEndUsage(void) {
if(!MQTTFlags.bits.MQTTInUse)
return 0xFFFF;
// Release the DNS module, if in use
if(MQTTState == MQTT_NAME_RESOLVE)
DNSEndUsage();
if(MQTTClient.bConnected)
MQTTDisconnect();
// Release the TCP socket, if in use
if(MySocket != INVALID_SOCKET) {
TCPDisconnect(MySocket);
MySocket = INVALID_SOCKET;
}
// Release the MQTT module
MQTTFlags.bits.MQTTInUse = FALSE;
MQTTState = MQTT_HOME;
if(MQTTFlags.bits.ReceivedSuccessfully) {
return MQTT_SUCCESS;
}
else {
// return MQTTResponseCode;
}
}
/*****************************************************************************
Function:
void MQTTTask(void)
Summary:
Performs any pending MQTT client tasks
Description:
This function handles periodic tasks associated with the MQTT client,
such as processing initial connections and command sequences.
Precondition:
None
Parameters:
None
Returns:
None
Remarks:
This function acts as a task (similar to one in an RTOS). It
performs its task in a co-operative manner, and the main application
must call this function repeatedly to ensure that all open or new
connections are served in a timely fashion.
***************************************************************************/
void MQTTTask(void) {
WORD i;
WORD t;
static DWORD Timer;
static WORD nextMsgId;
BYTE d[7] = {0x00,0x04,'M','Q','T','T', MQTTPROTOCOLVERSION};
// Leave room in the buffer for header and variable length field
WORD length;
BYTE llen;
unsigned int j;
BYTE v;
WORD len;
BYTE header;
BYTE type;
WORD msgId;
BYTE *payload;
WORD tl;
char topic[25];
switch(MQTTState) {
case MQTT_HOME:
// MQTTBeginUsage() is the only function which will kick
// the state machine into the next state
break;
case MQTT_BEGIN:
// Obtain ownership of the DNS resolution module
if(!DNSBeginUsage())
break;
// Obtain the IP address associated with the MQTT mail server
if(MQTTClient.Server.szRAM) {
#if defined(__18CXX)
if(MQTTClient.ROMPointers.Server)
DNSResolveROM(MQTTClient.Server.szROM, DNS_TYPE_A);
else
#endif
DNSResolve(MQTTClient.Server.szRAM, DNS_TYPE_A);
}
else {
MQTTState=MQTT_HOME; // can't do anything
break;
}
Timer = TickGet();
MQTTState++;
break;
case MQTT_NAME_RESOLVE:
// Wait for the DNS server to return the requested IP address
if(!DNSIsResolved(&MQTTServer)) {
// Timeout after 6 seconds of unsuccessful DNS resolution
if(TickGet() - Timer > 6*TICK_SECOND) {
MQTTResponseCode = MQTT_RESOLVE_ERROR;
MQTTState = MQTT_HOME;
DNSEndUsage();
}
break;
}
// Release the DNS module, we no longer need it
if(!DNSEndUsage()) {
// An invalid IP address was returned from the DNS
// server. Quit and fail permanantly if host is not valid.
MQTTResponseCode = MQTT_RESOLVE_ERROR;
MQTTState = MQTT_HOME;
break;
}
MQTTState++;
// No need to break here
case MQTT_OBTAIN_SOCKET:
// Connect a TCP socket to the remote MQTT server
MySocket = TCPOpen(MQTTServer.Val, TCP_OPEN_IP_ADDRESS, MQTTClient.ServerPort, TCP_PURPOSE_DEFAULT);
// Abort operation if no TCP sockets are available
// If this ever happens, add some more
// TCP_PURPOSE_DEFAULT sockets in TCPIPConfig.h
if(MySocket == INVALID_SOCKET)
break;
MQTTState++;
Timer = TickGet();
// No break; fall into MQTT_SOCKET_OBTAINED
case MQTT_SOCKET_OBTAINED:
if(!TCPIsConnected(MySocket)) {
// Don't stick around in the wrong state if the
// server was connected, but then disconnected us.
// Also time out if we can't establish the connection to the MQTT server
if(MQTTFlags.bits.ConnectedOnce || ((LONG)(TickGet()-Timer) > (LONG)(MQTT_SERVER_REPLY_TIMEOUT))) {
MQTTResponseCode = MQTT_CONNECT_ERROR;
MQTTState = MQTT_CLOSE;
}
break;
}
MQTTFlags.bits.ConnectedOnce = TRUE;
case MQTT_CONNECT:
if(!MQTTConnected()) {
if(MQTTFlags.bits.ConnectedOnce) {
nextMsgId = 1;
length = 5;
for(j=0; j<9; j++)
MQTTBuffer[length++] = d[j];
if(MQTTClient.WillTopic.szRAM) {
MQTTClient.QOS=MQTTClient.WillQOS;
v = 0x06 | (MQTTClient.WillQOS<<3) | (MQTTClient.WillRetain<<5);
}
else
v = 0x02;
if(MQTTClient.Username.szRAM) {
v |= 0x80;
if(MQTTClient.Password.szRAM)
v = v | (0x80>>1);
}
MQTTBuffer[length++] = v;
MQTTBuffer[length++] = HIBYTE(MQTTClient.KeepAlive);
MQTTBuffer[length++] = LOBYTE(MQTTClient.KeepAlive);
#if defined(__18CXX)
if(MQTTClient.ROMPointers.ConnectId)
length = MQTTWriteROMString(MQTTClient.ConnectId.szROM,MQTTBuffer,length);
else
#endif
length = MQTTWriteString(MQTTClient.ConnectId.szRAM,MQTTBuffer,length);
if(MQTTClient.WillTopic.szRAM) {
#if defined(__18CXX)
if(MQTTClient.ROMPointers.WillTopic)
length = MQTTWriteString(MQTTClient.WillTopic.szROM,MQTTBuffer,length);
else
#endif
length = MQTTWriteString(MQTTClient.WillTopic.szRAM,MQTTBuffer,length);
#if defined(__18CXX)
if(MQTTClient.ROMPointers.WillMessage)
length = MQTTWriteROMString(MQTTClient.WillMessage.szROM,MQTTBuffer,length);
else
#endif
length = MQTTWriteString(MQTTClient.WillMessage.szRAM,MQTTBuffer,length);
}
if(MQTTClient.Username.szRAM) { // il check su union ? ok!
#if defined(__18CXX)
if(MQTTClient.ROMPointers.Username) {
length = MQTTWriteROMString(MQTTClient.Username.szROM,MQTTBuffer,length);
if(MQTTClient.Password.szRAM) {
if(MQTTClient.ROMPointers.Password) {
length = MQTTWriteROMString(MQTTClient.Password.szROM,MQTTBuffer,length);
}
else {
length = MQTTWriteString(MQTTClient.Password.szRAM,MQTTBuffer,length);
}
}
}
else {
#endif
length = MQTTWriteString(MQTTClient.Username.szRAM,MQTTBuffer,length);
if(MQTTClient.Password.szRAM) {
#if defined(__18CXX)
if(MQTTClient.ROMPointers.Password)
length = MQTTWriteROMString(MQTTClient.Password.szROM,MQTTBuffer,length);
else
#endif
length = MQTTWriteString(MQTTClient.Password.szRAM,MQTTBuffer,length);
}
#if defined(__18CXX)
}
#endif
}
MQTTWrite(MQTTCONNECT,MQTTBuffer,length-5);
MQTTState=MQTT_CONNECT_ACK;
MQTTResponseCode=MQTT_SUCCESS;
//if(MQTTWrite(MQTTCONNECT,MQTTBuffer,length-5)){ // si potrebbe spezzare in 2 per non rifare tutto il "prepare" qua sopra...
// TCPPutArray(MySocket, MQTTBuffer, length-5);
// TCPFlush(MySocket);
// MQTTState++;
// lastOutActivity = TickGet(); // gi? in write
//MQTTResponseCode=MQTT_SUCCESS;
// }
}
MQTTStop();
//lastInActivity =TickGet();
}
break;
case MQTT_CONNECT_ACK:
lastInActivity =TickGet();
/*
if(TCPIsConnected(MySocket)) {
int rec = TCPIsGetReady(MySocket);
if ( rec <= 0 )
{
return;
}
int length = TCPGetArray(MySocket, &rxBF[bytesRecieved], rec);
bytesRecieved += length;
*/
while(!MQTTAvailable()) {
t = TickGet();
// theApp.PumpMessage();
if(t-lastInActivity > TICK_SECOND*10) {
MQTTStop();
//MQTTState=MQTT_IDLE;
break;
}
}
//BYTE llen[4];
len= MQTTReadPacket();
// char myBuf[128];
// wsprintf(myBuf,"Connect: len=%u, %02X,%02X,%02X,%02X",len,buffer[0],buffer[1],buffer[2],buffer[3]);
// AfxMessageBox(myBuf);
if(len >= 2) { //len bytesRecieved
switch(rxBF[1]) { //MQTTBuffer
case 0:
lastInActivity = TickGet();
MQTTFlags.bits.PingOutstanding = FALSE;
MQTTClient.bConnected=TRUE;
break;
case 1: // unacceptable protocol version
MQTTClient.bConnected=FALSE; //
MQTTResponseCode=MQTT_BAD_PROTOCOL;
break;
case 2: // identifier rejected
MQTTClient.bConnected=FALSE; //
MQTTResponseCode=MQTT_IDENT_REJECTED;
break;
case 3: // server unavailable
MQTTClient.bConnected=FALSE; //
MQTTResponseCode=MQTT_SERVER_UNAVAILABLE;
break;
case 4: // bad user o password
MQTTClient.bConnected=FALSE; //
MQTTResponseCode=MQTT_BAD_USER_PASW;
break;
case 5: // unauthorized
#ifdef _DEBUG
AfxMessageBox("unauthorized");
#endif
MQTTClient.bConnected=FALSE; //
MQTTResponseCode=MQTT_UNAUTHORIZED;
break;
}
MQTTState=MQTT_IDLE; //go to idle now
}
/*
}
else{
MQTTState=MQTT_HOME;
}
* */
break;
case MQTT_PING:
MQTTBuffer[0]=MQTTPINGREQ;
MQTTBuffer[1]=0;
if(TCPIsPutReady(MySocket) >= 2) {
MQTTPutArray(MQTTBuffer,2);
lastOutActivity = TickGet();
MQTTState=MQTT_IDLE; //
}
break;
case MQTT_PING_ACK: // Pingback,
MQTTBuffer[0]=MQTTPINGRESP;
MQTTBuffer[1]=0;
if(TCPIsPutReady(MySocket)>=2) {
MQTTPutArray(MQTTBuffer,2);
lastOutActivity = TickGet();
MQTTState=MQTT_IDLE; //
}
break;
case MQTT_PUBLISH:
//publish
if(MQTTConnected()) {
// Leave room in the buffer for header and variable length field
length = 5;
#if defined(__18CXX)
if(MQTTClient.ROMPointers.Topic)
length = MQTTWriteString(MQTTClient.Topic.szROM, MQTTBuffer,length);
else
#endif
length = MQTTWriteString(MQTTClient.Topic.szRAM, MQTTBuffer,length);
for(i=0;i<MQTTClient.Plength;i++)
MQTTBuffer[length++] = MQTTClient.Payload.szRAM[i]; // idem ROM/RAM ..
header = MQTTPUBLISH | (MQTTClient.QOS ? (MQTTClient.QOS==2 ? MQTTQOS2 : MQTTQOS1) : MQTTQOS0);
if(MQTTClient.Retained)
header |= 1;
//if(MQTTWrite(header,MQTTBuffer,length-5)) // si potrebbe spezzare in 2 per non rifare tutto il "prepare" qua sopra...
MQTTWrite(header,MQTTBuffer,length-5);
MQTTState++;
MQTTResponseCode=MQTT_SUCCESS;
}
else
MQTTResponseCode=MQTT_OPERATION_FAILED;
break;
case MQTT_PUBLISH_ACK: // Publish command accepted (if QOS)
if(MQTTClient.QOS>0) { // FINIRE...
//BYTE llen;
len = MQTTReadPacket(); //&llen
/*
int rec = TCPIsGetReady(MySocket);
if ( rec <= 0 )
{
break;
}
int length = TCPGetArray(MySocket, rxBF, rec);
*/
// char myBuf[128];
// wsprintf(myBuf,"publish: len=%u, %02X,%02X,%02X,%02X",len,buffer[0],buffer[1],buffer[2],buffer[3]);
// AfxMessageBox(myBuf);
if(len >= 2) { // finire!
MQTTState=MQTT_IDLE;
}
}
else
MQTTState=MQTT_IDLE;
break;
case MQTT_SUBSCRIBE:
// subscribe(const char *topic, BYTE qos
// mmm no m_QOS=qos;
// ma cmq usiamo lo stesso, per praticit?...
if(/*MQTTClient.QOS < 0 || boh */ MQTTClient.QOS > 1)
break;
if(MQTTConnected()) {
// Leave room in the buffer for header and variable length field
length = 5;
nextMsgId++;
if(nextMsgId == 0)
nextMsgId = 1;
MQTTBuffer[length++] = HIBYTE(nextMsgId);
MQTTBuffer[length++] = LOBYTE(nextMsgId);
#if defined(__18CXX)
if(MQTTClient.ROMPointers.Topic)
length = MQTTWriteString(MQTTClient.Topic.szROM, MQTTBuffer,length);
else
#endif
length = MQTTWriteString(MQTTClient.Topic.szRAM, MQTTBuffer,length);
MQTTBuffer[length++] = MQTTClient.QOS;
if(MQTTWrite(MQTTSUBSCRIBE | (MQTTClient.QOS ? (MQTTClient.QOS==2 ? MQTTQOS2 : MQTTQOS1) : MQTTQOS0),MQTTBuffer,length-5)) // si potrebbe spezzare in 2 per non rifare tutto il "prepare" qua sopra...
MQTTState++;
MQTTResponseCode=MQTT_SUCCESS;
}
else
MQTTResponseCode=MQTT_OPERATION_FAILED;
break;
case MQTT_SUBSCRIBE_ACK: // Subscribe command accepted (if QOS)
if(MQTTClient.QOS>0) { // FINIRE...
len= MQTTReadPacket(&llen);
// char myBuf[128];
// wsprintf(myBuf,"subscribe: len=%u, %02X,%02X,%02X,%02X",len,buffer[0],buffer[1],buffer[2],buffer[3]);
// AfxMessageBox(myBuf);
if(len==4) {
MQTTState=MQTT_IDLE;
}
}
else
MQTTState=MQTT_IDLE;
break;
case MQTT_PUBACK:
// puback(WORD msgId)
if(MQTTConnected()) {
// Leave room in the buffer for header and variable length field
length = 5;
MQTTBuffer[length++] = HIBYTE(MQTTClient.MsgId);
MQTTBuffer[length++] = LOBYTE(MQTTClient.MsgId);
if(MQTTWrite(MQTTPUBACK,MQTTBuffer,length-5))
MQTTState=MQTT_IDLE;
// per? in loop() faceva
// MQTTBuffer[0] = MQTTPUBACK;
// MQTTBuffer[1] = 2;
// MQTTBuffer[2] = HIBYTE(id);
// MQTTBuffer[3] = LOBYTE(id);
// MQTTPutArray(MQTTBuffer,4);
// lastOutActivity = t;
}
break;
case MQTT_UNSUBSCRIBE:
//unsubscribe(const char *topic)
if(MQTTConnected()) {
length = 5;
nextMsgId++;
if(nextMsgId == 0)
nextMsgId = 1;
MQTTBuffer[length++] = HIBYTE(nextMsgId);
MQTTBuffer[length++] = LOBYTE(nextMsgId);
#if defined(__18CXX)
if(MQTTClient.ROMPointers.Topic)
//WORD MQTTWriteString(const char *string, BYTE *buf, WORD pos) {
length = MQTTWriteString(MQTTClient.Topic.szROM, MQTTBuffer,length);
else
#endif
length = MQTTWriteString(MQTTClient.Topic.szRAM, MQTTBuffer,length);
if(MQTTWrite(MQTTUNSUBSCRIBE | MQTTQOS1,MQTTBuffer,length-5))
MQTTState++;
MQTTResponseCode=MQTT_SUCCESS;
}
else
MQTTResponseCode=MQTT_OPERATION_FAILED;
break;
case MQTT_UNSUBSCRIBE_ACK: // Subscribe command accepted (if QOS)
MQTTState=MQTT_IDLE;
break;
case MQTT_DISCONNECT_INIT:
MQTTState++;
break;
case MQTT_DISCONNECT:
//disconnect()
MQTTBuffer[0] = MQTTDISCONNECT;
MQTTBuffer[1] = 0;
if(TCPIsPutReady(MySocket) >= 2) {
MQTTPutArray(MQTTBuffer,2);
lastOutActivity = TickGet();
MQTTState=MQTT_CLOSE;
MQTTStop();
}
break;
case MQTT_CLOSE:
// Close the socket so it can be used by other modules
TCPDisconnect(MySocket);
MySocket = INVALID_SOCKET;
MQTTFlags.bits.ConnectedOnce = FALSE;
// Go back to doing nothing
MQTTState = MQTT_QUIT;
break;
case MQTT_QUIT:
if(MySocket != INVALID_SOCKET)
TCPClose(MySocket);
MQTTState = MQTT_HOME;
break;
case MQTT_IDLE:
if(MQTTConnected()) {
t = TickGet();
if(t - LastPingTick > MQTT_KEEPALIVE_REALTIME*TICK_SECOND) {
if( !MQTTFlags.bits.PingOutstanding) {
MQTTState=MQTT_PING;
MQTTFlags.bits.PingOutstanding = TRUE;
LastPingTick = TickGet();
}
}
if(MQTTAvailable()) {
len = MQTTReadPacket(&llen);
msgId = 0;
if(len > 0) {
lastInActivity = t;
type = MQTTBuffer[0] & 0xF0;
switch(type) {
case MQTTPUBLISH:
if(MQTTClient.m_Callback) {
tl = MAKEWORD(MQTTBuffer[llen+2],MQTTBuffer[llen+1]);
//char *topic=malloc(tl+1);
for(i=0; i<tl; i++)
topic[i] = MQTTBuffer[llen+3+i];
topic[tl] = 0;
// msgId only present for QOS>0
if((MQTTBuffer[0] & 0x06) == MQTTQOS1) {
msgId = MAKEWORD(MQTTBuffer[llen+3+tl+1],MQTTBuffer[llen+3+tl]);
payload = MQTTBuffer+llen+3+tl+2;
/////////MQTTClient.m_Callback(&topic[0],payload,len-llen-3-tl-2);
MQTTPubACK(msgId);
}
else {
payload = MQTTBuffer+llen+3+tl;
/////////MQTTClient.m_Callback(&topic[0],payload,len-llen-3-tl);
}
//free(topic);
}
break;
case MQTTPINGREQ:
MQTTState=MQTT_PING_ACK;
break;
case MQTTPINGRESP:
MQTTFlags.bits.PingOutstanding = FALSE;
break;
}
}
}
}
break;
}
}
/*****************************************************************************
Function:
BOOL MQTTIsBusy(void)
Summary:
Determines if the MQTT client is busy.
Description:
Call this function to determine if the MQTT client is busy performing
background tasks. This function should be called after any call to
MQTTReceiveMail, MQTTPutDone to determine if the stack has finished
performing its internal tasks. It should also be called prior to any
call to MQTTIsPutReady to verify that the MQTT client has not
prematurely disconnected. When this function returns FALSE, the next
call should be to MQTTEndUsage to release the module and obtain the
status code for the operation.
Precondition:
MQTTBeginUsage returned TRUE on a previous call.
Parameters:
None
Return Values:
TRUE - The MQTT Client is busy with internal tasks or sending an
on-the-fly message.
FALSE - The MQTT Client is terminated and is ready to be released.
***************************************************************************/
BOOL MQTTIsBusy(void) {
return MQTTState != MQTT_HOME;
}
BOOL MQTTIsIdle(void) {
return MQTTState != MQTT_IDLE;
}
/*****************************************************************************
Function:
WORD MQTTPutArray(BYTE* Data, WORD Len)
Description:
Writes a series of bytes to the MQTT client.
Precondition:
MQTTBeginUsage returned TRUE on a previous call.
Parameters:
Data - The data to be written
Len - How many bytes should be written
Returns:
The number of bytes written. If less than Len, then the TX FIFO became
full before all bytes could be written.
Remarks:
This function should only be called externally when the MQTT client is
generating an on-the-fly message. (That is, MQTTSendMail was called
with MQTTClient.Body set to NULL.)
Internal:
***************************************************************************/
WORD MQTTPutArray(BYTE* Data, WORD Len) {
WORD result = 0;
result = TCPPutArray(MySocket, Data, Len);
TCPFlush(MySocket);
/*
while(Len--) {
if(TCPPut(MySocket,*Data++)) {
result++;
}
else {
Data--;
break;
}
}
*/
return result;
}
/*****************************************************************************
Function:
WORD MQTTPutROMArray(ROM BYTE* Data, WORD Len)
Description:
Writes a series of bytes from ROM to the MQTT client.
Precondition:
MQTTBeginUsage returned TRUE on a previous call.
Parameters:
Data - The data to be written
Len - How many bytes should be written
Returns:
The number of bytes written. If less than Len, then the TX FIFO became
full before all bytes could be written.
Remarks:
This function should only be called externally when the MQTT client is
generating an on-the-fly message. (That is, MQTTSendMail was called
with MQTTClient.Body set to NULL.)
This function is aliased to MQTTPutArray on non-PIC18 platforms.
Internal:
MQTTPut must be used instead of TCPPutArray because "\r\n." must be
transparently replaced by "\r\n..".
***************************************************************************/
#if defined(__18CXX)
/*WORD MQTTPutROMArray(ROM BYTE* Data, WORD Len) {
WORD result = 0;
while(Len--) {
if(TCPPut(*Data++)) {
result++;
}
else {
Data--;
break;
}
}
return result;
}
#endif*/
/*****************************************************************************
Function:
WORD MQTTPutString(BYTE* Data)
Description:
Writes a string to the MQTT client.
Precondition:
MQTTBeginUsage returned TRUE on a previous call.
Parameters:
Data - The data to be written
Returns:
The number of bytes written. If less than the length of Data, then the
TX FIFO became full before all bytes could be written.
Remarks:
This function should only be called externally when the MQTT client is
generating an on-the-fly message. (That is, MQTTSendMail was called
with MQTTClient.Body set to NULL.)
Internal:
***************************************************************************/
WORD MQTTPutString(BYTE* Data) {
WORD result = 0;
while(*Data) {
if(TCPPut(MySocket,*Data++)) {
result++;