forked from harlequin-tech/WiFlyHQ
-
Notifications
You must be signed in to change notification settings - Fork 0
/
WiFlyHQ.cpp
2831 lines (2465 loc) · 65.6 KB
/
WiFlyHQ.cpp
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
/*-
* Copyright (c) 2012 Darran Hunt (darran [at] hunt dot net dot nz)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* THE CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* @file WiFly RN-XV Library
*/
#include "WiFlyHQ.h"
/* For free memory check */
extern unsigned int __bss_end;
extern unsigned int __heap_start;
extern void *__brkval;
#undef DEBUG
#ifdef DEBUG
#define DPRINT(item) debug.print(item)
#define DPRINTLN(item) debug.println(item)
#else
#define DPRINT(item)
#define DPRINTLN(item)
#endif
#define WIFLY_STATUS_TCP_MASK 0x000F
#define WIFLY_STATUS_TCP_OFFSET 0
#define WIFLY_STATUS_ASSOC_MASK 0x0001
#define WIFLY_STATUS_ASSOC_OFFSET 4
#define WIFLY_STATUS_AUTHEN_MASK 0x0001
#define WIFLY_STATUS_AUTHEN_OFFSET 5
#define WIFLY_STATUS_DNS_SERVER_MASK 0x0001
#define WIFLY_STATUS_DNS_SERVER_OFFSET 6
#define WIFLY_STATUS_DNS_FOUND_MASK 0x0001
#define WIFLY_STATUS_DNS_FOUND_OFFSET 7
#define WIFLY_STATUS_CHAN_MASK 0x000F
#define WIFLY_STATUS_CHAN_OFFSET 9
#define WIFLY_TCP_IDLE 0
#define WIFLY_TCP_CONNECTED 1
#define WIFLY_TCP_NOIP 3
#define WIFLY_TCP_CONNECTING 4
/* WiFi data rates */
#define WIFLY_RATE_1MBPS 0
#define WIFLY_RATE_2MBPS 1
#define WIFLY_RATE_5_5MBPS 2 /* 5.5 MBps */
#define WIFLY_RATE_6MBPS 8
#define WIFLY_RATE_9MBPS 9
#define WIFLY_RATE_11MBPS 3
#define WIFLY_RATE_12MBPS 10
#define WIFLY_RATE_18MBPS 11
#define WIFLY_RATE_24MBPS 12 /* Default */
#define WIFLY_RATE_36MBPS 13
#define WIFLY_RATE_48MBPS 14
#define WIFLY_RATE_54MBPS 15
/* Work around a bug with PROGMEM and PSTR where the compiler always
* generates warnings.
*/
#undef PROGMEM
#define PROGMEM __attribute__(( section(".progmem.data") ))
#undef PSTR
#define PSTR(s) (__extension__({static prog_char __c[] PROGMEM = (s); &__c[0];}))
/* Request and response strings in PROGMEM */
const prog_char req_GetIP[] PROGMEM = "get ip\r";
const prog_char resp_IP[] PROGMEM = "IP=";
const prog_char resp_NM[] PROGMEM = "NM=";
const prog_char resp_GW[] PROGMEM = "GW=";
const prog_char resp_Host[] PROGMEM = "HOST=";
const prog_char resp_DHCP[] PROGMEM = "DHCP=";
const prog_char req_GetMAC[] PROGMEM = "get mac\r";
const prog_char resp_MAC[] PROGMEM = "Mac Addr=";
const prog_char req_GetWLAN[] PROGMEM = "get wlan\r";
const prog_char resp_SSID[] PROGMEM = "SSID=";
const prog_char resp_Chan[] PROGMEM = "Chan=";
const prog_char req_GetOpt[] PROGMEM = "get opt\r";
const prog_char resp_DeviceID[] PROGMEM = "DeviceId=";
const prog_char req_GetUart[] PROGMEM = "get u\r";
const prog_char resp_Baud[] PROGMEM = "Baudrate=";
const prog_char req_GetTime[] PROGMEM = "get time\r";
const prog_char resp_Zone[] PROGMEM = "Zone=";
const prog_char req_ShowTime[] PROGMEM = "show time\r";
const prog_char resp_Uptime[] PROGMEM = "UpTime=";
const prog_char resp_Time[] PROGMEM = "Time=";
const prog_char req_GetDNS[] PROGMEM = "get dns\r";
const prog_char resp_DNSAddr[] PROGMEM = "Address=";
const prog_char req_ShowTimeT[] PROGMEM = "show t t\r";
const prog_char resp_RTC[] PROGMEM = "RTC=";
const prog_char resp_Mode[] PROGMEM = "Mode=";
const prog_char req_GetComm[] PROGMEM = "get comm\r";
const prog_char resp_FlushTimeout[] PROGMEM = "FlushTimer=";
const prog_char resp_FlushChar[] PROGMEM = "MatchChar=";
const prog_char resp_FlushSize[] PROGMEM = "FlushSize=";
const prog_char req_GetRSSI[] PROGMEM = "show rssi\r";
const prog_char resp_RSSI[] PROGMEM = "RSSI=(-";
const prog_char resp_Flags[] PROGMEM = "FLAGS=0x";
const prog_char resp_Protocol[] PROGMEM = "PROTO=";
const prog_char req_GetAdhoc[] PROGMEM = "get adhoc\r";
const prog_char resp_Beacon[] PROGMEM = "Beacon=";
const prog_char resp_Probe[] PROGMEM = "Probe=";
const prog_char resp_Reboot[] PROGMEM = "Reboot=";
const prog_char resp_Join[] PROGMEM = "Join=";
const prog_char resp_Rate[] PROGMEM = "Rate=";
const prog_char resp_Power[] PROGMEM = "TxPower=";
/* Request and response for specific info */
static struct {
const prog_char *req;
const prog_char *resp;
} requests[] = {
{ req_GetIP, resp_IP }, /* 0 */
{ req_GetIP, resp_NM }, /* 1 */
{ req_GetIP, resp_GW }, /* 2 */
{ req_GetMAC, resp_MAC }, /* 3 */
{ req_GetWLAN, resp_SSID }, /* 4 */
{ req_GetOpt, resp_DeviceID }, /* 5 */
{ req_GetUart, resp_Baud }, /* 6 */
{ req_ShowTime, resp_Time }, /* 7 */
{ req_ShowTime, resp_Uptime }, /* 8 */
{ req_GetTime, resp_Zone }, /* 9 */
{ req_GetDNS, resp_DNSAddr }, /* 10 */
{ req_ShowTimeT, resp_RTC }, /* 11 */
{ req_GetIP, resp_DHCP }, /* 12 */
{ req_GetUart, resp_Mode }, /* 13 */
{ req_GetComm, resp_FlushTimeout }, /* 14 */
{ req_GetComm, resp_FlushChar }, /* 15 */
{ req_GetComm, resp_FlushSize }, /* 16 */
{ req_GetRSSI, resp_RSSI }, /* 17 */
{ req_GetIP, resp_Flags }, /* 18 */
{ req_GetIP, resp_Host }, /* 19 */
{ req_GetIP, resp_Protocol }, /* 20 */
{ req_GetAdhoc, resp_Beacon }, /* 21 */
{ req_GetAdhoc, resp_Probe }, /* 22 */
{ req_GetAdhoc, resp_Reboot }, /* 23 */
{ req_GetWLAN, resp_Join }, /* 24 */
{ req_GetWLAN, resp_Rate }, /* 25 */
{ req_GetWLAN, resp_Power }, /* 26 */
};
/* Request indices, must match table above */
typedef enum {
WIFLY_GET_IP = 0,
WIFLY_GET_NETMASK = 1,
WIFLY_GET_GATEWAY = 2,
WIFLY_GET_MAC = 3,
WIFLY_GET_SSID = 4,
WIFLY_GET_DEVICEID = 5,
WIFLY_GET_BAUD = 6,
WIFLY_GET_TIME = 7,
WIFLY_GET_UPTIME = 8,
WIFLY_GET_ZONE = 9,
WIFLY_GET_DNS = 10,
WIFLY_GET_RTC = 11,
WIFLY_GET_DHCP = 12,
WIFLY_GET_UART_MODE = 13,
WIFLY_GET_FLUSHTIMEOUT = 14,
WIFLY_GET_FLUSHCHAR = 15,
WIFLY_GET_FLUSHSIZE = 16,
WIFLY_GET_RSSI = 17,
WIFLY_GET_IP_FLAGS = 18,
WIFLY_GET_HOST = 19,
WIFLY_GET_PROTOCOL = 20,
WIFLY_GET_BEACON = 21,
WIFLY_GET_PROBE = 22,
WIFLY_GET_REBOOT = 23,
WIFLY_GET_JOIN = 24,
WIFLY_GET_RATE = 25,
WIFLY_GET_POWER = 26,
} e_wifly_requests;
/** Convert a unsigned int to a string */
static int simple_utoa(uint32_t val, uint8_t base, char *buf, int size)
{
char tmpbuf[16];
int ind=0;
uint32_t nval;
int fsize=0;
if (base == DEC) {
do {
nval = val / 10;
tmpbuf[ind++] = '0' + val - (nval * 10);
val = nval;
} while (val);
} else {
do {
nval = val & 0x0F;
tmpbuf[ind++] = nval + ((nval < 10) ? '0' : 'A');
val >>= 4;
} while (val);
tmpbuf[ind++] = 'x';
tmpbuf[ind++] = '0';
}
ind--;
do {
buf[fsize++] = tmpbuf[ind];
} while ((ind-- > 0) && (fsize < (size-1)));
buf[fsize] = '\0';
return fsize;
}
/** Simple hex string to uint32_t */
static uint32_t atoh(char *buf)
{
uint32_t res=0;
char ch;
bool gotX = false;
while ((ch=*buf++) != 0) {
if (ch >= '0' && ch <= '9') {
res = (res << 4) + ch - '0';
} else if (ch >= 'a' && ch <= 'f') {
res = (res << 4) + ch - 'a' + 10;
} else if (ch >= 'A' && ch <= 'F') {
res = (res << 4) + ch - 'A' + 10;
} else if ((ch == 'x') && !gotX) {
/* Ignore 0x at start */
gotX = true;
} else {
break;
}
}
return res;
}
/** Simple ASCII to unsigned int */
static uint32_t atou(const char *buf)
{
uint32_t res=0;
while (*buf) {
if ((*buf < '0') || (*buf > '9')) {
break;
}
res = res * 10 + *buf - '0';
buf++;
}
return res;
}
/**
* Convert an IPAdress to an ASCIIZ string
* @param addr - the IP Address to convert
* @param buf - the buffer to write the result to
* @param size - the size of the buffer
* @returns pointer to the result
*/
char *WiFly::iptoa(IPAddress addr, char *buf, int size)
{
uint8_t fsize=0;
uint8_t ind;
for (ind=0; ind<3; ind++) {
fsize += simple_utoa(addr[ind], 10, &buf[fsize], size-fsize);
if (fsize < (size-1)) {
buf[fsize++] = '.';
}
}
simple_utoa(addr[ind], 10, &buf[fsize], size-fsize);
return buf;
}
/**
* Convert a dotquad IP address string to an IPAddress.
* E.g. "192.168.1.100" -> { 192, 168, 1, 100 }.
* @param buf - the string to convert
* @returns the IPAddress form of the string
*/
IPAddress WiFly::atoip(char *buf)
{
IPAddress ip;
for (uint8_t ind=0; ind<3; ind++) {
ip[ind] = atou(buf);
while (*buf >= '0' && *buf <= '9') {
buf++;
}
if (*buf == '\0') break;
}
return ip;
}
WiFly::WiFly()
{
inCommandMode = false;
exitCommand = 0;
connected = false;
connecting = false;
dhcp = true;
restoreHost = true;
#ifdef DEBUG
debugOn = true;
#else
debugOn = false;
#endif
dbgBuf = NULL;
dbgInd = 0;
dbgMax = 0;
}
/**
* Get WiFly ready to handle commands, and determine
* some initial status.
*/
void WiFly::init()
{
int8_t dhcpMode=0;
lastPort = 0;
lastHost[0] = 0;
if (!setopt(PSTR("set u m 1"), (char *)NULL)) {
debug.println(F("Failed to turn off echo"));
}
if (!setopt(PSTR("set sys printlvl 0"), (char *)NULL)) {
debug.println(F("Failed to turn off sys print"));
}
if (!setopt(PSTR("set comm remote 0"), (char *)NULL)) {
debug.println(F("Failed to set comm remote"));
}
/* update connection status */
getConnection();
DPRINT(F("tcp status: ")); DPRINT(status.tcp); DPRINT("\n\r");
DPRINT(F("assoc status: ")); DPRINT(status.assoc); DPRINT("\n\r");
DPRINT(F("authen status: ")); DPRINT(status.authen); DPRINT("\n\r");
DPRINT(F("dns status: ")); DPRINT(status.dnsServer); DPRINT("\n\r");
DPRINT(F("dns found status: ")); DPRINT(status.dnsFound); DPRINT("\n\r");
DPRINT(F("channel status: ")); DPRINT(status.channel); DPRINT("\n\r");
dhcpMode = getDHCPMode();
dhcp = !((dhcpMode == WIFLY_DHCP_MODE_OFF) || (dhcpMode == WIFLY_DHCP_MODE_SERVER));
}
/**
* Start the WiFly device, set it up to handle commands, obtain
* some initial status (TCP connection status, WiFi association, etc).
* @param serialdev - the serial stream to use to talk to the WiFly.
* @param debugPrint - optional debug stream for errors and status.
* @retval true - WiFly ready for use
* @retval false - failed to initialise WiFly
*/
boolean WiFly::begin(Stream *serialdev, Stream *debugPrint)
{
debug.begin(debugPrint);
serial = serialdev;
if (!enterCommandMode()) {
debug.println(F("Failed to enter command mode"));
return false;
}
init();
if (!exitCommandMode()) {
debug.println(F("Failed to exit command mode"));
return false;
}
return true;
}
/**
* Return number of bytes of memory available.
* @returns number of bytes of free memory
*/
int WiFly::getFreeMemory()
{
int free;
if ((int)__brkval == 0)
free = ((int)&free) - ((int)&__bss_end);
else
free = ((int)&free) - ((int)__brkval);
return free;
}
/**
* Flush the incoming data from the WiFly.
* @param timeout - the number of milliseconds to wait for additional data to flush. Default is 500msecs.
*/
void WiFly::flushRx(int timeout)
{
char ch;
DPRINT(F("flush\n\r"));
while (readTimeout(&ch,timeout));
DPRINT(F("flushed\n\r"));
}
/**
* Write a byte to the WiFly.
* @param byte - the byte to write.
* @return the number of bytes written (1).
*/
size_t WiFly::write(uint8_t byte)
{
if (dbgInd < dbgMax) {
dbgBuf[dbgInd++] = byte;
}
return serial->write(byte);
}
/* Read-ahead for checking for TCP stream close
* A circular buffer is used to keep read-ahead bytes and
* feed them back to the user.
*/
static char peekBuf[8];
static uint8_t peekHead = 0; /* head of buffer; new characters stored here */
static uint8_t peekTail = 0; /* Tail of buffer; characters read from here */
static uint8_t peekCount = 0; /* Number of characters in peek buffer */
/**
* Return the next byte that a read() would return, but leave the
* byte in the receive buffer.
* @returns the next byte that would be read
* @retval -1 - no data in receive buffer
*/
int WiFly::peek()
{
if (peekCount == 0) {
return serial->peek();
} else {
return peekBuf[peekTail];
}
}
/** Check for a state change on the stream
* @param str progmem string to check stream input for
* @param peeked true if the caller peeked the first char of the string,
* false if the caller read the character already
* @retval true - the state change was matched
* @retval false - state change not matched
* @note A side effect of this function is that it will store
* the unmatched string in the read-ahead peek buffer since
* it has to read the characters from the WiFly to check for
* the match. The peek buffer is used to feed those characters
* to the user ahead of reading any more characters from the WiFly.
*/
boolean WiFly::checkStream(const prog_char *str, boolean peeked)
{
char next;
#ifdef DEBUG
debug.print(F("checkStream: "));
debug.println((const __FlashStringHelper *)str);
#endif
if (peekCount > 0) {
uint8_t ind=0;
if (peeked) {
str++;
ind = 1;
}
for (; ind<peekCount; ind++) {
uint8_t pind = peekTail + ind;
next = pgm_read_byte(str++);
if (next == '\0') {
/* Done - got a match */
peekCount = 0; // discard peeked bytes
peekTail = 0;
peekHead = 0;
return true;
}
if (pind > sizeof(peekBuf)) {
pind = 0;
}
if (peekBuf[pind] != next) {
/* Not a match */
return false;
}
/* peeked characters match */
}
/* string matched so far, keep reading */
} else if (!peeked) {
/* Already read and matched the first character before being called */
str++;
}
next = pgm_read_byte(str++);
while (readTimeout(&peekBuf[peekHead]),50) {
if (peekBuf[peekHead] != next) {
if (++peekHead > sizeof(peekBuf)) {
peekHead = 0;
}
peekCount++;
if (peekCount > sizeof(peekBuf)) {
debug.println(F("ERROR peek.1 buffer overlow"));
}
break;
}
if (++peekHead > sizeof(peekBuf)) {
peekHead = 0;
}
peekCount++;
if (peekCount > sizeof(peekBuf)) {
debug.println(F("ERROR peek.2 buffer overlow"));
}
next = pgm_read_byte(str++);
if (next == '\0') {
/* Done - got a match */
peekCount = 0; // discard peeked bytes
peekTail = 0;
peekHead = 0;
return true;
}
}
return false;
}
/** Check for stream close, if its closed
* we will quickly receive *CLOS* from the WiFly
* @param peeked - set to true if first character of *CLOS* was peeked, or false if it has been read.
* @retval true - stream closed
* @retval false - stream not closed
*/
boolean WiFly::checkClose(boolean peeked)
{
if (checkStream(PSTR("*CLOS*"), peeked)) {
connected = false;
DPRINTLN(F("Stream closed"));
return true;
}
return false;
}
/** Check for stream open.
* @param peeked - set to true if first character of *OPEN* was peeked, or false if it has been read.
* @retval true - stream opened
* @retval false - stream not opened
*/
boolean WiFly::checkOpen(boolean peeked)
{
if (checkStream(PSTR("*OPEN*"), peeked)) {
connected = true;
DPRINTLN(F("Stream opened"));
return true;
}
return false;
}
/** Read the next byte from the WiFly.
* @returns the byte read
* @retval -1 - nothing in the receive buffer to read
*/
int WiFly::read()
{
int data = -1;
/* Any data in peek buffer? */
if (peekCount) {
data = (uint8_t)peekBuf[peekTail++];
if (peekTail > sizeof(peekBuf)) {
peekTail = 0;
}
peekCount--;
} else {
data = serial->read();
/* TCP connected? Check for close */
if (connected && data == '*') {
if (checkClose(false)) {
return -1;
} else {
data = (uint8_t)peekBuf[peekTail++];
if (peekTail > sizeof(peekBuf)) {
peekTail = 0;
}
peekCount--;
}
}
}
return data;
}
/** Check to see if data is available to be read.
* @returns the number of bytes that are available to read.
* @retval 0 - no data available
* @retval -1 - active TCP connection was closed,
*/
int WiFly::available()
{
int count;
count = serial->available();
if (count > 0) {
if (debugOn) {
debug.print(F("available: peek = "));
debug.println((char)serial->peek());
}
/* Check for TCP stream closure */
if (serial->peek() == '*') {
if (connected) {
if (checkClose(true)) {
return -1;
} else {
return peekCount + serial->available();
}
} else {
checkOpen(true);
return peekCount + serial->available();
}
}
}
return count+peekCount;
}
void WiFly::flush()
{
serial->flush();
}
/** Hex dump a string */
void WiFly::dump(const char *str)
{
while (*str) {
debug.print(*str,HEX);
debug.print(' ');
str++;
}
debug.println();
}
/** Send a string to the WiFly */
void WiFly::send(const char *str)
{
DPRINT(F("send: ")); DPRINT(str); DPRINT("\n\r");
print(str);
//serial->print(str);
}
/** Send a character to the WiFly */
void WiFly::send(const char ch)
{
write(ch);
//serial->write(ch);
}
/** Send a string from PROGMEM to the WiFly */
void WiFly::send_P(const prog_char *str)
{
DPRINT(F("send_P: "));
DPRINTLN((const __FlashStringHelper *)str);
print((const __FlashStringHelper *)str);
}
/**
* Start a capture of all the characters recevied from the WiFly.
* @param size - the size of the capture buffer. This will be malloced.
*/
void WiFly::dbgBegin(int size)
{
if (dbgBuf != NULL) {
free(dbgBuf);
}
dbgBuf = (char *)malloc(size);
dbgInd = 0;
dbgMax = size;
}
/** Stop debug capture and free buffer */
void WiFly::dbgEnd()
{
if (dbgBuf != NULL) {
free(dbgBuf);
dbgBuf = NULL;
}
dbgInd = 0;
dbgMax = 0;
}
/** Do a hex and ASCII dump of the capture buffer, and free the buffer. */
void WiFly::dbgDump()
{
int ind;
if (dbgBuf == NULL) {
return;
}
if (dbgInd > 0) {
debug.println(F("debug dump"));
for (ind=0; ind<dbgInd; ind++) {
debug.print(ind);
debug.print(F(": "));
debug.print(dbgBuf[ind],HEX);
if (isprint(dbgBuf[ind])) {
debug.print(' ');
debug.print(dbgBuf[ind]);
}
debug.println();
}
}
free(dbgBuf);
dbgBuf = NULL;
dbgMax = 0;
}
/** Read the next character from the WiFly serial interface.
* Waits up to timeout milliseconds to receive the character.
* @param chp pointer to store the read character in
* @param timeout the number of milliseconds to wait for a character
* @retval true - character read
* @retval false - timeout reached, character not read
*/
boolean WiFly::readTimeout(char *chp, uint16_t timeout)
{
uint32_t start = millis();
char ch;
static int ind=0;
while (millis() - start < timeout) {
if (serial->available() > 0) {
ch = serial->read();
*chp = ch;
if (dbgInd < dbgMax) {
dbgBuf[dbgInd++] = ch;
}
if (debugOn) {
debug.print(ind++);
debug.print(F(": "));
debug.print(ch,HEX);
if (isprint(ch)) {
debug.print(' ');
debug.print(ch);
}
debug.println();
}
return true;
}
}
if (debugOn) {
debug.println(F("readTimeout - timed out"));
}
return false;
}
static char prompt[16];
static boolean gotPrompt = false;
/** Scan the input data for the WiFLy prompt. This is a string starting with a '<' and
* ending with a '>'. Store the prompt for future use.
*/
boolean WiFly::setPrompt()
{
char ch;
while (readTimeout(&ch,500)) {
if (ch == '<') {
uint8_t ind = 1;
prompt[0] = ch;
while (ind < (sizeof(prompt)-4)) {
if (readTimeout(&ch,500)) {
prompt[ind++] = ch;
if (ch == '>') {
if (readTimeout(&ch,500)) {
if (ch == ' ') {
prompt[ind++] = ch;
//prompt[ind++] = '\r';
//prompt[ind++] = '\n';
prompt[ind] = 0;
DPRINT(F("setPrompt: ")); DPRINT(prompt); DPRINT("\n\r");
gotPrompt = true;
gets(NULL,0);
return true;
} else {
/* wrong character */
return false;
}
} else {
/* timeout */
return false;
}
}
} else {
/* timeout */
return false;
}
}
return false;
}
}
return false;
}
/** See if the prompt is somewhere in the string */
boolean WiFly::checkPrompt(const char *str)
{
if (strstr(str, prompt) != NULL) {
return true;
} else {
return false;
}
}
/**
* Read characters from the WiFly and match them against the
* string. Ignore any leading characters that don't match. Keep
* reading, discarding the input, until the string is matched
* or until no characters are received for the timeout duration.
* @param str The string to match
* @param timeout fail if no data received for this period (in milliseconds).
* @retval true - a match was found
* @retval false - no match found, timeout reached
*/
boolean WiFly::match(const char *str, uint16_t timeout)
{
const char *match = str;
char ch;
#ifdef DEBUG
if (debugOn) {
debug.print(F("match: "));
debug.println(str);
}
#endif
if ((match == NULL) || (*match == '\0')) {
return true;
}
/* find first character */
while (readTimeout(&ch,timeout)) {
if (ch == *match) {
match++;
} else {
match = str;
if (ch == *match) {
match++;
}
}
if (*match == '\0') {
DPRINT(F("match: true\n\r"));
return true;
}
}
DPRINT(F("match: false\n\r"));
return false;
}
/**
* Read characters from the WiFly and match them against the
* progmem string. Ignore any leading characters that don't match. Keep
* reading, discarding the input, until the string is matched
* or until no characters are received for the timeout duration.
* @param str The string to match, in progmem.
* @param timeout fail if no data received for this period (in milliseconds).
* @retval true - a match was found
* @retval false - no match found, timeout reached
*/
boolean WiFly::match_P(const prog_char *str, uint16_t timeout)
{
const prog_char *match = str;
char ch, ch_P;
if (debugOn) {
debug.print(F("match_P: "));
debug.println((const __FlashStringHelper *)str);
}
ch_P = pgm_read_byte(match);
if (ch_P == '\0') {
/* Null string always matches */
return true;
}
while (readTimeout(&ch,timeout)) {
if (ch == ch_P) {
match++;
} else {
/* Restart match */
match = str;
if (ch == pgm_read_byte(match)) {
match++;
}
}
ch_P = pgm_read_byte(match);
if (ch_P == '\0') {
DPRINT(F("match_P: true\n\r"));
return true;
}
}
DPRINT(F("match_P: false\n\r"));
return false;
}
/**
* Read characters from the WiFly and match them against the set of
* progmem strings. Ignore any leading characters that don't match. Keep
* reading, discarding the input, until one of the strings is matched
* or until no characters are received for the timeout duration.<br>
* Example: res = multiMatch_P(500, 3, F("first="), F("second="), F("closed"));<br>
* Will return 0 if "first=" is matched, 1 if "second=" is matched, 2 if "closed" is
* matched, or -1 if nothing is matched and no data is received for 500 milliseconds.
* @param timeout - fail if no data received for this period (in milliseconds).
* @param count - the number of strings in the str array
* @param ... A list of count progmem strings to match
* @returns the index of the matching string
* @retval -1 - no match found, timeout reached
*/
int WiFly::multiMatch_P(uint16_t timeout, uint8_t count, ...)
{
const prog_char *str[20];
int ind;
va_list ap;
va_start(ap, count);
if (count > 20) {
count = 20;
}
for (ind=0; ind<count; ind++) {
str[ind] = va_arg(ap, const prog_char *);
}
va_end(ap);
return multiMatch_P(str, count, timeout);
}
/**
* Read characters from the WiFly and match them against the set of
* progmem strings. Ignore any leading characters that don't match. Keep
* reading, discarding the input, until one of the strings is matched
* or until no characters are received for the timeout duration.
* @param str - the array of progmem strings to match
* @param count - the number of strings in the str array
* @param timeout - fail if no data received for this period (in milliseconds).
* @returns the index of the matching string
* @retval -1 - no match found, timeout reached
*/
int8_t WiFly::multiMatch_P(const prog_char *str[], uint8_t count, uint16_t timeout)
{
struct {
bool active;
const prog_char *str;
} match[count];
char ch, ch_P;
uint8_t ind;
for (ind=0; ind<count; ind++) {
match[ind].active = false;
match[ind].str = str[ind];
if (debugOn) {
debug.print(F("multiMatch_P: "));
debug.print(ind);
debug.print(' ');
debug.println((const __FlashStringHelper *)str[ind]);
}
}
while (readTimeout(&ch,timeout)) {