-
Notifications
You must be signed in to change notification settings - Fork 49
/
PubNubDefs.h
1477 lines (1354 loc) · 43.3 KB
/
PubNubDefs.h
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
/* -*- c-file-style:"stroustrup"; indent-tabs-mode: nil -*- */
#ifndef PubNub_h
#define PubNub_h
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#if !defined(PubNub_BASE_CLIENT)
#if defined(ARDUINO_ARCH_ESP8266)
#include <ESP8266WiFi.h>
#define PubNub_BASE_CLIENT WiFiClient
#elif defined(ARDUINO_ARCH_ESP32)
#include <WiFi.h>
#define PubNub_BASE_CLIENT WiFiClient
#elif defined(ARDUINO_SAMD_ZERO) || \
defined(ARDUINO_SAMD_MKR1000) || \
defined(ARDUINO_SAMD_MKRFox1200)
#include <WiFi101.h>
#define PubNub_BASE_CLIENT WiFiClient
#elif defined(ARDUINO_STM32_FEATHER)
#include <adafruit_feather.h>
#define PubNub_BASE_CLIENT AdafruitTCP
#elif defined(ARDUINO_METRO_M4_AIRLIFT_LITE) || \
defined(ARDUINO_SAMD_MKRWIFI1010) || \
defined(ARDUINO_AVR_UNO_WIFI_REV2)
#include <WiFiNINA.h>
#define PubNub_BASE_CLIENT WiFiSSLClient
#elif defined(ARDUINO_SAMD_MKRGSM1400)
#include <MKRGSM.h>
#define PubNub_BASE_CLIENT GSMClient
#elif defined(ARDUINO_SAMD_MKRWAN1300)
#include <MKRWAN.h>
#define PubNub_BASE_CLIENT LoRaModem
#elif defined(ARDUINO_AVR_YUN)
#include <Process.h>
#define PubNub_BASE_CLIENT Process
#elif defined(ARDUINO_SAMD_MKRNB1500)
#include <MKRNB.h>
#define PubNub_BASE_CLIENT NBModem
#else
#include <Ethernet.h>
#define PubNub_BASE_CLIENT EthernetClient
#endif
#endif /* !defined(PubNub_BASE_CLIENT) */
#ifdef PUBNUB_DEBUG
#define DBGprint(x...) Serial.print(x)
#define DBGprintln(x...) Serial.println(x)
#else
#define DBGprint(x...)
#define DBGprintln(x...)
#endif
/* Under some board support libraries, like ESP8266,
the (de-facto) standard library functions are missing.
To use Pubnub library with those boards, you need to
define the following preprocessor macro-constant.
*/
#if defined(PUBNUB_DEFINE_STRSPN_AND_STRNCASECMP)
inline size_t strspn(const char* cs, const char* ct)
{
size_t n;
for (n = 0; *cs; cs++, n++) {
const char* p;
for (p = ct; *p && *p != *cs; ++p) {
continue;
}
if (*p == '\0') {
break;
}
}
return n;
}
#include <ctype.h>
inline int strncasecmp(const char* s1, const char* s2, size_t n)
{
size_t i;
for (i = 0; i < n; ++i) {
const int diff = tolower(s1[i]) - tolower(s2[i]);
if ((diff != 0) || (s1[i] == '\0')) {
return diff;
}
}
return 0;
}
#endif
/** This is a very thin Arduino #Client interface wrapper.
It's reason d'^etre is the fact that some clients,
namely the WiFiClient for ESP32, drops the available()
count to 0 on connection close. So, if you don't read
the incoming octets fast enough, you won't read them
at all (if you observe the result of available()).
*/
class PubNonSubClient : public PubNub_BASE_CLIENT {
public:
PubNonSubClient()
: PubNub_BASE_CLIENT()
, d_avail(0)
{
}
int available()
{
if (0 == d_avail) {
d_avail = PubNub_BASE_CLIENT::available();
}
return d_avail;
}
int read()
{
if (d_avail > 0) {
--d_avail;
}
return PubNub_BASE_CLIENT::read();
}
int read(uint8_t* buf, size_t size)
{
int len = PubNub_BASE_CLIENT::read(buf, size);
if (d_avail > len) {
if (len > 0) {
d_avail -= len;
}
}
else {
d_avail = 0;
}
return len;
}
private:
int d_avail;
};
/* This class is a thin #EthernetClient (in general, any class that
* implements the Arduino #Client "interface") wrapper whose
* goal is to automatically acquire time token information when
* reading subscribe call response.
*
* The user application sees only the JSON body, not the timetoken.
* As soon as the body ends, PubSubclient reads the rest of HTTP reply
* itself and disconnects. The stored timetoken is used in the next call
* to the PubNub::subscribe() method.
*/
class PubSubClient : public PubNub_BASE_CLIENT {
public:
PubSubClient()
: PubNub_BASE_CLIENT()
, d_avail(0)
, json_enabled(false)
{
strcpy(timetoken, "0");
}
int available()
{
if (0 == d_avail) {
d_avail = PubNub_BASE_CLIENT::available();
}
return d_avail;
}
/* Customized functions that make reading stop as soon as we
* have hit ',' outside of braces and string, which indicates
* end of JSON body. */
int read()
{
int c = PubNub_BASE_CLIENT::read();
if (c != -1) {
if (d_avail > 0) {
--d_avail;
}
}
if (!json_enabled || c == -1) {
return c;
}
this->_state_input(c, 0, 0);
return c;
}
int read(uint8_t* buf, size_t size)
{
int len = PubNub_BASE_CLIENT::read(buf, size);
if (d_avail > len) {
if (len > 0) {
d_avail -= len;
}
}
else {
d_avail = 0;
}
if (!json_enabled || len <= 0) {
return len;
}
for (int i = 0; i < len; i++) {
this->_state_input(buf[i], buf + i + 1, len - i - 1);
}
return len;
}
void stop()
{
if ((!available() && !connected()) || !json_enabled) {
PubNub_BASE_CLIENT::stop();
return;
}
/* We are still connected. Read the rest of the stream so that
* we catch the timetoken. */
while (wait_for_data(10)) {
read();
}
json_enabled = false;
}
/* Block until data is available. Returns false in case the
* connection goes down or timeout expires. */
bool wait_for_data(int timeout = 310)
{
unsigned long t_start = millis();
while ((0 == available()) && connected()) {
if (millis() - t_start > (unsigned long)timeout * 1000) {
DBGprintln("wait_for_data() timeout");
return false;
}
delay(10);
}
return available() > 0;
}
/* Enable the JSON state machine. */
void start_body()
{
json_enabled = true;
in_string = after_backslash = false;
braces_depth = 0;
}
char const* server_timetoken() const { return timetoken; }
private:
inline void _state_input(uint8_t ch, uint8_t* nextbuf, size_t nextsize);
inline void _grab_timetoken(uint8_t* nextbuf, size_t nextsize);
int d_avail;
/* JSON state machine context */
bool json_enabled : 1;
bool in_string : 1;
bool after_backslash : 1;
int braces_depth;
/* Time token acquired during the last subscribe request. */
char timetoken[22];
};
class PubNub {
public:
/**
* Init the Pubnub Client API
*
* This should be called after Ethernet.begin().
* Note that the string parameters are not copied; do not
* overwrite or free the memory where you stored the keys!
* (If you are passing string literals, don't worry about it.)
* Note that you should run only a single publish at once.
*
* @param string publish_key required key to send messages.
* @param string subscribe_key required key to receive messages.
* @param string origin optional setting for cloud origin.
* @return boolean whether begin() was successful.
*/
bool begin(const char* publish_key,
const char* subscribe_key,
const char* origin = "pubsub.pubnub.com")
{
d_publish_key = publish_key;
d_subscribe_key = subscribe_key;
d_origin = origin;
d_uuid = 0;
d_auth = 0;
d_last_http_status_code_class = http_scc_unknown;
set_port(http_port);
return true;
}
/**
* HTTP status code class. It is defined by the first digit of the
* HTTP status code.
*
* @see RFC 7231 Section 6
*/
enum http_status_code_class {
/** This is not defined in the RFC, we use it to indicate
"none/unknown" */
http_scc_unknown = 0,
/** The request was received, continuing process */
http_scc_informational = 1,
/** The request was successfully received, understood, and
accepted */
http_scc_success = 2,
/** Further action needs to be taken in order to complete the
request */
http_scc_redirection = 3,
/** The request contains bad syntax or cannot be fulfilled */
http_scc_client_error = 4,
/** The server failed to fulfill an apparently valid
request */
http_scc_server_error = 5
};
/**
* Possible TCP/IP ports to use when connecting to Pubnub.
*/
enum port_for_connection {
/** Connect via HTTP on its default port */
http_port,
/** Connect via TLS (formerly known as SSL) on its default port) */
tls_port
};
/**
* Set the UUID identification of PubNub client. This is useful
* e.g. for presence identification.
*
* Pass 0 to unset. The string is not copied over (just like
* in begin()). See the PubNubSubscriber example for simple code
* that generates a random UUID (although not 100% reliable).
*/
void set_uuid(const char* uuid) { d_uuid = uuid; }
/**
* Set the authorization key/token of PubNub client. This is useful
* e.g. for access rights validation (PAM).
*
* Pass 0 to unset. The string is not copied over (just like
* in begin()). */
void set_auth(const char* auth) { d_auth = auth; }
/**
* Set the TCP/IP port to use when connecting to Pubnub.
* Basically, only call this if your client supports SSL/TLS
* as you will need to set the `tls_port`.
*/
void set_port(port_for_connection port) {
switch (port) {
case http_port:
default:
d_port = 80;
break;
case tls_port:
d_port = 443;
break;
}
}
/**
* Publish/Send a message (assumed to be well-formed JSON) to a
* given channel.
*
* Note that the reply can be obtained using code like:
client = PubNub.publish("demo", "\"lala\"");
if (!client) {
Serial.println("Failed to publish, got no response from PubNub");
return;
}
if (PubNub.get_last_http_status_code_class() !=
PubNub::http_scc_success) { Serial.print("Got HTTP status code error from
PubNub, class: ");
Serial.print((int)PubNub.get_last_http_status_code_class(), DEC);
}
while (client->connected()) {
// More sophisticated code will want to add timeout handling here
while (client->connected() && !client->available()) ; // wait
char c = client->read();
Serial.print(c);
}
client->stop();
* You will get content right away, the header has been already
* skipped inside the function. If you do not care about
* the reply, just call client->stop(); immediately.
*
* It returns an object that is typically EthernetClient (but it
* can be a WiFiClient if you enabled the WiFi shield).
*
* @param string channel required channel name.
* @param string message required message string in JSON format.
* @param string timeout optional timeout in seconds.
* @return string Stream-ish object with reply message or 0 on error.
*/
inline PubNonSubClient* publish(const char* channel,
const char* message,
int timeout = 30);
/**
* Subscribe/Listen for a message on a given channel. The function
* will block and return when a message arrives. Typically, you
* will run this function from loop() function to keep listening
* for messages indefinitely.
*
* As a reply, you will get a JSON array with messages, e.g.:
* ["msg1",{msg2:"x"}]
* and so on. Empty reply [] is also normal and your code must be
* able to handle that. Note that the reply specifically does not
* include the time token present in the raw reply.
*
* @param string channel required channel name.
* @param string timeout optional timeout in seconds.
* @return string Stream-ish object with reply message or 0 on error.
*/
inline PubSubClient* subscribe(const char* channel, int timeout = 310);
/**
* History
*
* Receive list of the last N messages on the given channel.
*
* @param string channel required channel name.
* @param int limit optional number of messages to retrieve.
* @param string timeout optional timeout in seconds.
* @return string Stream-ish object with reply message or 0 on error. */
inline PubNonSubClient* history(const char* channel,
int limit = 10,
int timeout = 310);
/** Returns the HTTP status code class of the last PubNub
transaction. If the transaction failed without getting a
(HTTP) response, it will be "unknown".
*/
inline http_status_code_class get_last_http_status_code_class() const
{
return d_last_http_status_code_class;
}
#if defined(PUBNUB_UNIT_TEST)
inline PubNonSubClient& publishClient() { return publish_client; }
inline PubNonSubClient& historyClient() { return history_client; };
inline PubSubClient& subscribeClient() { return subscribe_client; }
#endif /* PUBNUB_UNIT_TEST */
private:
enum PubNub_BH {
PubNub_BH_OK,
PubNub_BH_ERROR,
PubNub_BH_TIMEOUT,
};
inline enum PubNub_BH _request_bh(PubNub_BASE_CLIENT& client,
unsigned long t_start,
int timeout,
char qparsep);
const char* d_publish_key;
const char* d_subscribe_key;
const char* d_origin;
const char* d_uuid;
const char* d_auth;
/// TCP/IP port to use.
unsigned d_port;
/// The HTTP status code class of the last PubNub transaction
http_status_code_class d_last_http_status_code_class;
PubNonSubClient publish_client, history_client;
PubSubClient subscribe_client;
};
#if defined(__AVR)
#include <avr/pgmspace.h>
#elif !defined(strncasecmp_P) || defined(PUBNUB_DEFINE_STRSPN_AND_STRNCASECMP)
#define strncasecmp_P(a, b, c) strncasecmp(a, b, c)
#endif
/* There are some special considerations when using the WiFi libary,
* compared to the Ethernet library:
*
* (i) The client object may return stale data from previous connection,
* so we should call .flush() after initiating a connection.
*
* (ii) It appears .stop() does not block on really terminating
* the connection, do that manually.
*
* (iii) Data may still be available while connected() returns false
* already; use available() test on a lot of places where we used
* connected() before.
*/
inline void PubSubClient::_state_input(uint8_t ch, uint8_t* nextbuf, size_t nextsize)
{
/* Process a single character on input, updating the JSON
* state machine. If we reached the last character of input
* (just before expected ","), we will eat the rest of the body,
* update timetoken and close the connection. */
if (in_string) {
if (after_backslash) {
/* Whatever this is... */
after_backslash = false;
return;
}
switch (ch) {
case '"':
in_string = false;
if (braces_depth == 0)
this->_grab_timetoken(nextbuf, nextsize);
return;
case '\\':
after_backslash = true;
return;
default:
return;
}
}
else {
switch (ch) {
case '"':
in_string = true;
return;
case '{':
case '[':
braces_depth++;
return;
case '}':
case ']':
braces_depth--;
if (braces_depth == 0)
this->_grab_timetoken(nextbuf, nextsize);
return;
default:
return;
}
}
return;
}
inline void PubSubClient::_grab_timetoken(uint8_t* nextbuf, size_t nextsize)
{
char new_timetoken[22] = { '\0' };
size_t new_timetoken_len = 0;
unsigned long t_start = millis();
const unsigned long timeout = /*3*/ 10000UL;
enum NTTState {
await_comma,
await_quote,
read_timetoken,
done
} state = await_comma;
/* Expected followup now is:
* ,"13511688131075270"]
*/
while (state != done) {
uint8_t ch;
if (millis() - t_start > timeout) {
DBGprintln("Timeout while reading timetoken");
return;
}
if (nextsize > 0) {
ch = *nextbuf++;
--nextsize;
}
else {
if (0 == available()) {
if (!connected()) {
DBGprintln("Lost connection while reading timetoken");
return;
}
delay(10);
}
// Some clients (actually, quite a few) implement
// character read via array read, like:
//
// int read() { uint8_t c; read(&c, 1); return c;}
///
// and have both reads virtual. So, if we call such a
// `read()`, it will call the virtual "array read", which
// is actually _our_ array read, which will then call
// _state_input(), in a sort of unwanted recursion.
//
// @todo: Of course, this does _not_ solve such problems
// in general, as some other client might do the opposite,
// implement array read via character read! Thus, this
// whole idea of inheriting Client classes is wrong (as
// inheritance often is) and needs to be refactored.
int len = PubNub_BASE_CLIENT::read(&ch, 1);
if (len != 1) {
continue;
}
if (d_avail > 0) {
--d_avail;
}
}
switch (state) {
case await_comma:
if (',' == ch) {
state = await_quote;
}
break;
case await_quote:
if ('"' == ch) {
state = read_timetoken;
}
break;
case read_timetoken:
if (ch == '"') {
state = done;
break;
}
new_timetoken[new_timetoken_len++] = ch;
if (new_timetoken_len >= sizeof(new_timetoken) - 1) {
/* TODO: handle this as a kind of error */
state = done;
break;
}
break;
default:
break;
}
}
if (new_timetoken_len > 0) {
memcpy(timetoken, new_timetoken, new_timetoken_len);
}
timetoken[new_timetoken_len] = 0;
}
inline bool await_disconnect(PubNub_BASE_CLIENT& client, unsigned long timeout) {
unsigned long t_start = millis();
while (client.connected()) {
if (millis() - t_start > timeout * 1000UL) {
return false;
}
delay(10);
}
return true;
}
inline PubNonSubClient* PubNub::publish(const char* channel,
const char* message,
int timeout)
{
PubNonSubClient& client = publish_client;
int have_param = 0;
unsigned long t_start = millis();
/* connect() timeout is about 30s, much lower than our usual
* timeout is. */
int rslt = client.connect(d_origin, d_port);
if (rslt != 1) {
DBGprint("Connection error ");
DBGprintln(rslt);
client.stop();
return 0;
}
d_last_http_status_code_class = http_scc_unknown;
client.flush();
client.print("GET /publish/");
client.print(d_publish_key);
client.print("/");
client.print(d_subscribe_key);
client.print("/0/");
client.print(channel);
client.print("/0/");
/* Inject message, URI-escaping it in the process.
* We are careful to save RAM by not using any copies
* of the string or explicit buffers. */
const char* pmessage = message;
while (pmessage[0]) {
/* RFC 3986 Unreserved characters plus few
* safe reserved ones. */
size_t okspan = strspn(
pmessage,
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~"
",=:;@[]");
if (okspan > 0) {
client.write((const uint8_t*)pmessage, okspan);
pmessage += okspan;
}
if (pmessage[0]) {
/* %-encode a non-ok character. */
char enc[3] = { '%' };
enc[1] = "0123456789ABCDEF"[pmessage[0] / 16];
enc[2] = "0123456789ABCDEF"[pmessage[0] % 16];
client.write((const uint8_t*)enc, 3);
pmessage++;
}
}
if (d_auth) {
client.print(have_param ? '&' : '?');
client.print("auth=");
client.print(d_auth);
have_param = 1;
}
enum PubNub::PubNub_BH ret =
this->_request_bh(client, t_start, timeout, have_param ? '&' : '?');
switch (ret) {
case PubNub_BH_OK:
return &client;
case PubNub_BH_ERROR:
DBGprintln("publish() BH_ERROR");
client.stop();
if (!await_disconnect(client, 10)) {
DBGprintln("publish() BH_ERROR: disconnect timeout");
}
return 0;
case PubNub_BH_TIMEOUT:
DBGprintln("publish() BH_TIMEOUT");
client.stop();
if (!await_disconnect(client, 10)) {
DBGprintln("publish() BH_TIMEOUT: disconnect timeout");
}
return 0;
}
return 0;
}
inline PubSubClient* PubNub::subscribe(const char* channel, int timeout)
{
PubSubClient& client = subscribe_client;
int have_param = 0;
unsigned long t_start = millis();
/* connect() timeout is about 30s, much lower than our usual
* timeout is. */
if (!client.connect(d_origin, d_port)) {
DBGprintln("Connection error");
client.stop();
return 0;
}
d_last_http_status_code_class = http_scc_unknown;
client.flush();
client.print("GET /subscribe/");
client.print(d_subscribe_key);
client.print("/");
client.print(channel);
client.print("/0/");
client.print(client.server_timetoken());
if (d_uuid) {
client.print("?uuid=");
client.print(d_uuid);
have_param = 1;
}
if (d_auth) {
client.print(have_param ? '&' : '?');
client.print("auth=");
client.print(d_auth);
have_param = 1;
}
enum PubNub::PubNub_BH ret =
this->_request_bh(client, t_start, timeout, have_param ? '&' : '?');
switch (ret) {
case PubNub_BH_OK:
/* Success and reached body. We need to eat '[' first,
* as our API contract is to return only the "message body"
* part of reply from subscribe. */
if (!client.wait_for_data()) {
DBGprintln("No data received!");
client.stop();
if (!await_disconnect(client, 10)) {
DBGprintln("subscribe() no data received: disconnect timeout");
}
return 0;
}
if (client.read() != '[') {
DBGprintln("Unexpected body in subscribe response");
client.stop();
if (!await_disconnect(client, 10)) {
DBGprintln("subscribe() unexpected body: disconnect timeout");
}
return 0;
}
/* Now return handle to the client for further perusal.
* PubSubClient class will make sure that the client does
* not see the time token but we stop right after the
* message body. */
client.start_body();
return &client;
case PubNub_BH_ERROR:
DBGprintln("subscribe() BH_ERROR");
client.stop();
if (!await_disconnect(client, 10)) {
DBGprintln("subscribe() BH_ERROR: disconnect timeout");
}
return 0;
case PubNub_BH_TIMEOUT:
DBGprintln("subscribe() BH_TIMEOUT");
client.stop();
DBGprintln("subscribe() BH_TIMEOUT stopped");
if (await_disconnect(client, 10)) {
DBGprintln("subscribe() BH_TIMEOUT: disconnected");
}
else {
DBGprintln("subscribe() BH_TIMEOUT: disconnect timeout");
}
return 0;
}
return 0;
}
inline PubNonSubClient* PubNub::history(const char* channel, int limit, int timeout)
{
PubNonSubClient& client = history_client;
unsigned long t_start = millis();
if (!client.connect(d_origin, d_port)) {
DBGprintln("Connection error");
client.stop();
return 0;
}
d_last_http_status_code_class = http_scc_unknown;
client.flush();
client.print("GET /history/");
client.print(d_subscribe_key);
client.print("/");
client.print(channel);
client.print("/0/");
client.print(limit, DEC);
enum PubNub::PubNub_BH ret = this->_request_bh(client, t_start, timeout, '?');
switch (ret) {
case PubNub_BH_OK:
return &client;
case PubNub_BH_ERROR:
DBGprintln("history() BH_ERROR");
client.stop();
if (!await_disconnect(client, 10)) {
DBGprintln("history() BH_ERROR: disconnect timeout");
}
return 0;
case PubNub_BH_TIMEOUT:
DBGprintln("history() BH_TIMEOUT");
client.stop();
if (!await_disconnect(client, 10)) {
DBGprintln("history() BH_TIMEOUT: disconnect timeout");
}
return 0;
}
return 0;
}
/** A helper that "cracks" the messages from an array of them.
It is, essentially, a simple, non-validating parser of
a JSON array, yielding individual elements of said array.
*/
class MessageCracker {
public:
enum State {
bracket_open,
ground_zero,
in_message,
in_quotes,
malformed,
done
};
MessageCracker()
: d_state(bracket_open)
{
}
void handle(char c, String& msg)
{
switch (d_state) {
case bracket_open:
if ('[' == c) {
d_state = ground_zero;
msg.remove(0);
}
break;
case ground_zero:
switch (c) {
case '{':
case '[':
d_bracket_level = 1;
d_state = in_message;
msg.concat(c);
break;
case '"':
d_bracket_level = 0;
d_state = in_quotes;
d_backslash = false;
msg.concat(c);
break;
case ',':
d_bracket_level = 0;
d_state = in_message;
break;
case ']':
d_state = done;
break;
default:
d_bracket_level = 0;
d_state = in_message;
msg.concat(c);
break;
}
break;
case in_quotes:
switch (c) {
case '"':
if (!d_backslash) {
d_state = (0 == d_bracket_level) ? ground_zero : in_message;
}
else {
d_backslash = false;
}
msg.concat(c);
break;
case '\\':
d_backslash = true;
msg.concat(c);
break;
default:
msg.concat(c);
break;
}
break;
case in_message:
switch (c) {
case '{':
case '[':
++d_bracket_level;
msg.concat(c);
break;
case '"':
d_state = in_quotes;
d_backslash = false;
msg.concat(c);
break;
case '}':
case ']':
if (0 == d_bracket_level) {
d_state = done;
}
else {
if (--d_bracket_level == 0) {
d_state = ground_zero;
}
msg.concat(c);
}
break;
default:
msg.concat(c);
break;
}
break;
case malformed:
case done:
default:
break;
}
}
State state() const { return d_state; }
bool msg_complete(String& msg) const
{
return (msg.length() > 0) && (ground_zero == state());
}
private:
/** Parser/cracker state */
State d_state;
/** Current bracket level - starts at 0 */
size_t d_bracket_level;
/** Are we inside quotes (string) */
bool d_in_quotes;
/** Was the last character a backslash? Valid only inside quotes */
bool d_backslash;
};