forked from SuperTango/arduino-wifly-serial
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWiFlySerial.cpp
1809 lines (1476 loc) · 55 KB
/
WiFlySerial.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
/*
Arduino WiFly Device Driver
Driver for Roving Network's WiFly GSX (c) (tm) b/g WiFi device
using a simple Tx/Rx serial connection.
4-wires needed: Power, Gnd, Rx, Tx
Provides moderately-generic WiFi device interface.
Compatible with Arduino 1.0
Version 1.09
- WiFlyGSX is a relatively intelligent peer.
- WiFlyGSX may have awoken in a valid configured state while Arduino asleep;
initialization and configuration to be polite and obtain state
- WiFlyGSX hardware CTS/RTS not enabled yet
- Can listen on multiple ports.
- most settings assumed volatile; fetched from WiFly where reasonable.
Expected pattern of use:
begin
issue commands, such as set SSID, passphrase etc
exit command mode / enter data mode
listen for web activity
Open a TCP connection to a peer
send / receive data
close connection
SoftwareSerial is exposed as serial i/o
Credits:
SoftwareSerial Mikal Hart http://arduiniana.org/
Time Michael Margolis http://www.arduino.cc/playground/uploads/Code/Time.zip
WiFly Roving Networks www.rovingnetworks.com
and to Massimo and the Arduino team.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
Copyright GPL 2.1 Tom Waldock 2011, 2012
*/
#include "WiFlySerial.h"
// Strings stored in Program space
const char s_WIFLYDEVICE_LIBRARY_VERSION[] PROGMEM = "WiFlySerial v1.09" ;
const char s_WIFLYDEVICE_JOIN[] PROGMEM = "join " ;
const char s_WIFLYDEVICE_OPEN[] PROGMEM = "open " ;
const char s_WIFLYDEVICE_CLOSE[] PROGMEM = "close" ;
const char s_WIFLYDEVICE_ASSOCIATED[] PROGMEM = "ssociated" ;
const char s_WIFLYDEVICE_ATTN[] PROGMEM = "$$$";
const char s_WIFLYDEVICE_VER[] PROGMEM = "ver" ;
const char s_WIFLYDEVICE_LEAVE_CMD_MODE[] PROGMEM ="exit";
const char s_WIFLYDEVICE_REBOOT[] PROGMEM ="reboot";
const char s_WIFLYDEVICE_SAVE[] PROGMEM ="save";
const char s_WIFLYDEVICE_GET_MAC[] PROGMEM =" get mac";
const char s_WIFLYDEVICE_GET_MAC_ADDR[] PROGMEM ="Addr=";
const char s_WIFLYDEVICE_GET_IP[] PROGMEM =" get ip";
const char s_WIFLYDEVICE_GET_GW[] PROGMEM = " "; // "GW=";
const char s_WIFLYDEVICE_GET_NM[] PROGMEM = " "; // "NM=";
const char s_WIFLYDEVICE_LEAVE[] PROGMEM ="leave";
const char s_WIFLYDEVICE_SET_SSID[] PROGMEM =" set wlan s ";
const char s_WIFLYDEVICE_SET_CHANNEL[] PROGMEM =" set wlan c ";
const char s_WIFLYDEVICE_SET_WIFI_AUTH[] PROGMEM =" set wlan a ";
const char s_WIFLYDEVICE_SET_WIFI_JOIN[] PROGMEM =" set wlan j ";
const char s_WIFLYDEVICE_SET_PASSPHRASE[] PROGMEM =" set w p ";
const char s_WIFLYDEVICE_NETWORK_SCAN[] PROGMEM ="scan ";
const char s_WIFLYDEVICE_AOK[] PROGMEM ="";
const char s_WIFLYDEVICE_SET_UART_BAUD[] PROGMEM ="set u b 9600 ";
const char s_WIFLYDEVICE_DEAUTH[] PROGMEM ="Deauth";
const char s_WIFLYDEVICE_SET_NTP[] PROGMEM =" set time a ";
const char s_WIFLYDEVICE_SET_NTP_ENABLE[] PROGMEM ="set time e ";
const char s_WIFLYDEVICE_SET_DEVICEID[] PROGMEM ="set opt deviceid ";
const char s_WIFLYDEVICE_IP_DETAILS[] PROGMEM ="get ip";
const char s_WIFLYDEVICE_GET_DNS_DETAILS[] PROGMEM ="get dns";
const char s_WIFLYDEVICE_GET_TIME[] PROGMEM ="show t t";
const char s_WIFLYDEVICE_SET_DHCP[] PROGMEM ="set ip dhcp ";
const char s_WIFLYDEVICE_SET_IP[] PROGMEM ="set ip a ";
const char s_WIFLYDEVICE_SET_NETMASK[] PROGMEM ="set ip n ";
const char s_WIFLYDEVICE_SET_GATEWAY[] PROGMEM ="set ip g ";
const char s_WIFLYDEVICE_SET_DNS[] PROGMEM ="set dns addr ";
const char s_WIFLYDEVICE_SET_LOCAL_PORT[] PROGMEM ="set ip local ";
const char s_WIFLYDEVICE_SET_REMOTE_PORT[] PROGMEM ="set ip remote ";
const char s_WIFLYDEVICE_SET_PROTOCOL[] PROGMEM ="set ip proto ";
const char s_WIFLYDEVICE_ERR_REBOOOT[] PROGMEM ="Attempting reboot";
const char s_WIFLYDEVICE_ERR_START_FAIL[] PROGMEM ="Failed to get cmd prompt:Halted.";
const char s_WIFLYDEVICE_SET_UART_MODE[] PROGMEM ="set u m 1 ";
const char s_WIFLYDEVICE_GET_WLAN[] PROGMEM ="get wlan ";
const char s_WIFLYDEVICE_GET_RSSI[] PROGMEM ="show rssi ";
const char s_WIFLYDEVICE_GET_BATTERY[] PROGMEM ="show batt ";
const char s_WIFLYDEVICE_GET_STATUS[] PROGMEM ="show conn ";
const char s_WIFLYDEVICE_RETURN[] PROGMEM ="\r";
const char s_WIFLYDEVICE_GET_IP_IND[] PROGMEM ="IP=";
const char s_WIFLYDEVICE_GET_NM_IND[] PROGMEM ="NM=";
const char s_WIFLYDEVICE_GET_GW_IND[] PROGMEM ="GW=";
const char s_WIFLYDEVICE_GET_DNS_IND[] PROGMEM ="DNS=";
const char s_WIFLYDEVICE_GET_WLAN_SSID_IND[] PROGMEM ="SSID=";
const char s_WIFLYDEVICE_GET_RSSI_IND[] PROGMEM ="RSSI=";
const char s_WIFLYDEVICE_GET_WLAN_DEV_IND[] PROGMEM ="DeviceID=";
const char s_WIFLYDEVICE_GET_BATTERY_IND[] PROGMEM ="Batt=";
const char s_WIFLYDEVICE_GET_TIME_IND[] PROGMEM ="RTC=";
const char s_WIFLYDEVICE_GET_STATUS_IND[] PROGMEM ="8";
const char s_WIFLYDEVICE_GET_IP_UP_IND[] PROGMEM ="F=";
// Index of strings
#define STI_WIFLYDEVICE_INDEX_JOIN 0
#define STI_WIFLYDEVICE_INDEX_ASSOCIATED 1
#define STI_WIFLYDEVICE_ATTN 2
#define STI_WIFLYDEVICE_VER 3
#define STI_WIFLYDEVICE_GET_MAC 4
#define STI_WIFLYDEVICE_GET_IP 5
#define STI_WIFLYDEVICE_GET_GW 6
#define STI_WIFLYDEVICE_GET_NM 7
#define STI_WIFLYDEVICE_LEAVE 8
#define STI_WIFLYDEVICE_SET_SSID 9
#define STI_WIFLYDEVICE_SET_PASSPHRASE 10
#define STI_WIFLYDEVICE_NETWORK_SCAN 11
#define STI_WIFLYDEVICE_AOK 12
#define STI_WIFLYDEVICE_SET_UART_BAUD 13
#define STI_WIFLYDEVICE_DEAUTH 14
#define STI_WIFLYDEVICE_SET_NTP 15
#define STI_WIFLYDEVICE_SET_NTP_ENABLE 16
#define STI_WIFLYDEVICE_SET_DEVICEID 17
#define STI_WIFLYDEVICE_GET_IP_DETAILS 18
#define STI_WIFLYDEVICE_LEAVE_CMD_MODE 19
#define STI_WIFLYDEVICE_GET_DNS_DETAILS 20
#define STI_WIFLYDEVICE_GET_TIME 21
#define STI_WIFLYDEVICE_SET_DHCP 22
#define STI_WIFLYDEVICE_SET_IP 23
#define STI_WIFLYDEVICE_SET_NETMASK 24
#define STI_WIFLYDEVICE_SET_GATEWAY 25
#define STI_WIFLYDEVICE_SET_DNS 26
#define STI_WIFLYDEVICE_ERR_REBOOT 27
#define STI_WIFLYDEVICE_ERR_START_FAIL 28
#define STI_WIFLYDEVICE_SET_UART_MODE 29
#define STI_WIFLYDEVICE_GET_WLAN 30
#define STI_WIFLYDEVICE_GET_RSSI 31
#define STI_WIFLYDEVICE_GET_BATTERY 32
#define STI_WIFLYDEVICE_LIBRARY_VERSION 33
#define STI_WIFLYDEVICE_SET_CHANNEL 34
#define STI_WIFLYDEVICE_SET_WIFI_AUTH 35
#define STI_WIFLYDEVICE_SET_WIFI_JOIN 36
#define STI_WIFLYDEVICE_GET_STATUS 37
#define STI_WIFLYDEVICE_GET_MAC_ADDR 38
#define STI_WIFLYDEVICE_RETURN 39
#define STI_WIFLYDEVICE_GET_IP_IND 40
#define STI_WIFLYDEVICE_GET_NM_IND 41
#define STI_WIFLYDEVICE_GET_GW_IND 42
#define STI_WIFLYDEVICE_GET_DNS_IND 43
#define STI_WIFLYDEVICE_GET_WLAN_SSID_IND 44
#define STI_WIFLYDEVICE_GET_RSSI_IND 45
#define STI_WIFLYDEVICE_GET_BATTERY_IND 46
#define STI_WIFLYDEVICE_GET_WLAN_DEV_IND 47
#define STI_WIFLYDEVICE_GET_TIME_IND 48
#define STI_WIFLYDEVICE_GET_STATUS_IND 49
#define STI_WIFLYDEVICE_GET_IP_UP_IND 50
#define STI_WIFLYDEVICE_OPEN 51
#define STI_WIFLYDEVICE_REBOOT 52
#define STI_WIFLYDEVICE_CLOSE 53
#define STI_WIFLYDEVICE_SET_LOCAL_PORT 54
#define STI_WIFLYDEVICE_SET_REMOTE_PORT 55
#define STI_WIFLYDEVICE_SET_PROTOCOL 56
#define STI_WIFLYDEVICE_SAVE 57
// String Table in Program space
const char * const WiFlyDevice_string_table[] PROGMEM =
{
// 0-based index, see STI_WIFLY_DEVICE_ list above.
s_WIFLYDEVICE_JOIN,
s_WIFLYDEVICE_ASSOCIATED,
s_WIFLYDEVICE_ATTN,
s_WIFLYDEVICE_VER,
s_WIFLYDEVICE_GET_MAC,
s_WIFLYDEVICE_GET_IP,
s_WIFLYDEVICE_GET_GW,
s_WIFLYDEVICE_GET_NM,
s_WIFLYDEVICE_LEAVE,
s_WIFLYDEVICE_SET_SSID,
// 10 follows
s_WIFLYDEVICE_SET_PASSPHRASE,
s_WIFLYDEVICE_NETWORK_SCAN,
s_WIFLYDEVICE_AOK,
s_WIFLYDEVICE_SET_UART_BAUD,
s_WIFLYDEVICE_DEAUTH,
s_WIFLYDEVICE_SET_NTP,
s_WIFLYDEVICE_SET_NTP_ENABLE,
s_WIFLYDEVICE_SET_DEVICEID,
s_WIFLYDEVICE_IP_DETAILS,
s_WIFLYDEVICE_LEAVE_CMD_MODE,
// 20 follows
s_WIFLYDEVICE_GET_DNS_DETAILS,
s_WIFLYDEVICE_GET_TIME,
s_WIFLYDEVICE_SET_DHCP,
s_WIFLYDEVICE_SET_IP,
s_WIFLYDEVICE_SET_NETMASK,
s_WIFLYDEVICE_SET_GATEWAY,
s_WIFLYDEVICE_SET_DNS,
s_WIFLYDEVICE_ERR_REBOOOT,
s_WIFLYDEVICE_ERR_START_FAIL,
s_WIFLYDEVICE_SET_UART_MODE,
// 30 follows
s_WIFLYDEVICE_GET_WLAN,
s_WIFLYDEVICE_GET_RSSI,
s_WIFLYDEVICE_GET_BATTERY,
s_WIFLYDEVICE_LIBRARY_VERSION,
s_WIFLYDEVICE_SET_CHANNEL,
s_WIFLYDEVICE_SET_WIFI_AUTH,
s_WIFLYDEVICE_SET_WIFI_JOIN,
s_WIFLYDEVICE_GET_STATUS,
s_WIFLYDEVICE_GET_MAC_ADDR,
s_WIFLYDEVICE_RETURN,
// 40 follows
s_WIFLYDEVICE_GET_IP_IND,
s_WIFLYDEVICE_GET_NM_IND,
s_WIFLYDEVICE_GET_GW_IND,
s_WIFLYDEVICE_GET_DNS_IND,
s_WIFLYDEVICE_GET_WLAN_SSID_IND,
s_WIFLYDEVICE_GET_RSSI_IND,
s_WIFLYDEVICE_GET_BATTERY_IND,
s_WIFLYDEVICE_GET_WLAN_DEV_IND,
s_WIFLYDEVICE_GET_TIME_IND,
s_WIFLYDEVICE_GET_STATUS_IND,
// 50 follows
s_WIFLYDEVICE_GET_IP_UP_IND,
s_WIFLYDEVICE_OPEN,
s_WIFLYDEVICE_REBOOT,
s_WIFLYDEVICE_CLOSE,
s_WIFLYDEVICE_SET_LOCAL_PORT,
s_WIFLYDEVICE_SET_REMOTE_PORT,
s_WIFLYDEVICE_SET_PROTOCOL,
s_WIFLYDEVICE_SAVE
};
// Utility Functions
//
// WFSIPArrayToStr
// Converts IPArray to a character string representation for WiFlySerial
//
// pIP pointer to array of 4 ints representing ip address e.g. {192,168,1,3}
// pStr Destination buffer of at least 16 characters "192.168.1.3"
// returns 0 on success
//
// Note: could be enhanced to support IPv6
// Convert a Buffer holding an IP address to a byte array.
// Minimal safety checks - be careful!
uint8_t* BufferToIP_Array(char* pBuffer, uint8_t* pIP) {
char* posStart=0;
char* posEnd=0;
char alphabuf[IP_ADDR_WIDTH];
posStart = pBuffer;
for (int i = 0; i<UC_N_IP_BYTES ; i++) {
memset(alphabuf,'\0',IP_ADDR_WIDTH);
posEnd = strchr(posStart,'.');
if (posEnd == NULL) {
posEnd = strchr(posStart,'\0');
}
strncpy(alphabuf, posStart, posEnd-posStart);
pIP[i] = (uint8_t) atoi( alphabuf );
// Start looking one after last dot.
posStart = posEnd +1;
}
return pIP;
}
// Convert a Buffer holding an IP address to a byte array.
// Minimal safety checks - be careful!
char* IP_ArrayToBuffer( const uint8_t* pIP, char* pBuffer, int buflen) {
memset (pBuffer,'\0',buflen);
for (int i =0; i< UC_N_IP_BYTES; i++) {
itoa( (int) pIP[i], strchr(pBuffer,'\0'), 10);
if (i < UC_N_IP_BYTES -1 ) {
strcat(pBuffer, ".");
}
}
return pBuffer;
}
/*
Command and Response
WiFly provides one of three results from commands:
1) ERR: Bad Args , from malformed commands.
2) AOK , from accepted commands
3) nothing, after an inquiries' response.
Some commands will provide specific messages
e.g. join has a possible result of
mode=WPA1 SCAN OK followed by 'Associated!' and by ip values.
(bad SSID) mode=NONE FAILED
(bad pwd) mode=WPA1 SCAN OK followed by 'Disconn ... AUTH-ERR'
and followed by 'Disconn from <SSID>'
after a successful join, a 'cr' is needed to get the prompt
The 'command prompt' is currently the version number in angle-brackets e.g. <2.21>
*/
//WiFlySerial
//Initializer for WiFlySerial library
//
// Parameters:
// pinReceive Arduino's receive pin to WiFly's TX pin
// pinSend Arduino's send pin to WiFly's RX pin
//
// Returns: N/A
WiFlySerial::WiFlySerial(byte pinReceive, byte pinSend) : uart (pinReceive, pinSend) {
// Set initial values for flags.
// On Arduino startup, WiFly state not known.
bWiFlyInCommandMode = false;
bWiFlyConnectionOpen = false;
fStatus = WIFLY_STATUS_OFFLINE ;
strcpy(szWiFlyPrompt, WiFlyFixedPrompts[WIFLY_MSG_PROMPT2] ); // ">"
iLocalPort = WIFLY_DEFAULT_LOCAL_PORT;
iRemotePort = WIFLY_DEFAULT_REMOTE_PORT;
// default is UTC timezone
lUTC_Offset_seconds = 0;
// ensure a default sink.
pDebugChannel = NULL;
pControl = WiFlyFixedPrompts[WIFLY_MSG_CLOSE];
// set default uart transmission speed to same as WiFly default speed.
uart.begin(WIFLY_DEFAULT_BAUD_RATE);
uart.listen();
uart.flush();
}
// begin
// Initializes WiFly interface and starts communication with WiFly device.
//
// Parameters: none.
// Returns: true on initialize success, false on failure.
boolean WiFlySerial::begin() {
boolean bStart = false;
char szCmd[SMALL_COMMAND_BUFFER_SIZE];
char szResponse[COMMAND_BUFFER_SIZE];
// char szIndicator[INDICATOR_BUFFER_SIZE];
//Device may or may not be:
// awake / asleep
// net-connected / connection lost
// IP assigned / no IP
// in command mode / data mode
// in known state / confused
// Start by setting command prompt.
bWiFlyInCommandMode = false;
StartCommandMode(szCmd, SMALL_COMMAND_BUFFER_SIZE);
// turn off echo
// set baud rate
bStart = SendCommand( GetBuffer_P(STI_WIFLYDEVICE_SET_UART_MODE, szCmd, SMALL_COMMAND_BUFFER_SIZE),
WiFlyFixedPrompts[WIFLY_MSG_AOK],
szResponse,
COMMAND_BUFFER_SIZE );
bStart = SendCommand( GetBuffer_P(STI_WIFLYDEVICE_SET_UART_BAUD, szCmd, SMALL_COMMAND_BUFFER_SIZE),
WiFlyFixedPrompts[WIFLY_MSG_AOK],
szResponse,
COMMAND_BUFFER_SIZE );
GetCmdPrompt();
//DebugPrint("GotPrompt:");
//DebugPrint(szWiFlyPrompt);
getDeviceStatus();
// try, then try again after reboot.
if (strlen(szWiFlyPrompt) < 1 ) {
// got a problem
DebugPrint(GetBuffer_P(STI_WIFLYDEVICE_ERR_REBOOT, szCmd, SMALL_COMMAND_BUFFER_SIZE));
reboot();
delay(WIFLY_RESTART_WAIT_TIME);
// try again
GetCmdPrompt();
if (strlen(szWiFlyPrompt) < 1 ) {
DebugPrint(GetBuffer_P(STI_WIFLYDEVICE_ERR_START_FAIL, szCmd, SMALL_COMMAND_BUFFER_SIZE));
bStart = false;
}
}
return bStart;
}
// ScanForPattern
//
// General-purpose stream watcher.
// Monitors incoming stream until given prompt is detected, or error conditions, or until timer expired
////
// Parameters
// ResponseBuffer buffer for WiFly response
// bufsize size of buffer
// pExpectedPrompt Marker to find
// bCollecting true: collect chars in buffer UNTIL marker found, false: discard UNTIL marker found
// WaitTime Timeout duration to wait for response
// bPromptAfterResult true: version prompt after result, false: version prompt precedes results (scan, join).
//
// Returns: (see .h file) OR-ed flags of the following
// WiFly Responses:
//#define PROMPT_NONE 0
//#define PROMPT_EXPECTED_TOKEN_FOUND 1
//#define PROMPT_READY 2
//#define PROMPT_CMD_MODE 4
//#define PROMPT_AOK 8
//#define PROMPT_OTHER 16
//#define PROMPT_CMD_ERR 32
//#define PROMPT_TIMEOUT 64
//#define PROMPT_OPEN 128
//#define PROMPT_CLOSE 256
int WiFlySerial::ScanForPattern( char* responseBuffer, const int buflen, const char *pExpectedPrompt, const boolean bCollecting, const unsigned long WaitTime, const boolean bPromptAfterResult) {
byte iPromptFound = PROMPT_NONE;
char chResponse = 'A';
int bufpos = 0;
int bufsize = buflen -1; //terminating null for bufsize
int iPromptIndex = 0;
boolean bWaiting = true;
boolean bReceivedCR = false;
WiFlyFixedPrompts[WIFLY_MSG_EXPECTED] = (char*) pExpectedPrompt;
WiFlyFixedPrompts[WIFLY_MSG_PROMPT] = (char*) szWiFlyPrompt;
char* pFixedCurrent[N_PROMPTS];
int iFixedPrompt = 0;
for (int i=0; i< N_PROMPTS; i++) {
pFixedCurrent[i] = WiFlyFixedPrompts[i];
}
memset (responseBuffer, '\0', bufsize);
unsigned long TimeAtStart = millis() ; // capture current time
while (bWaiting ) {
if ( uart.available() > 0 ) {
chResponse = uart.read();
DebugPrint(chResponse);
if ( bCollecting ) {
responseBuffer[bufpos]=chResponse;
if ( ++bufpos == bufsize ) {
bufpos = 0;
} // if buffer wrapped
} // if capturing
for ( iFixedPrompt = 0; iFixedPrompt< N_PROMPTS; iFixedPrompt++ ) {
if ( chResponse == *pFixedCurrent[iFixedPrompt] ) {
// deal with 'open' and 'scan' version-prompt appearing BEFORE result; ignore it
if ( (!bPromptAfterResult) && (iFixedPrompt == WIFLY_MSG_PROMPT || iFixedPrompt == WIFLY_MSG_PROMPT2) /* standard version-prompt */ ) {
bWaiting = true;
iPromptFound |= PROMPT_READY;
} else {
bWaiting = ( *(++pFixedCurrent[iFixedPrompt]) == '\0' ? false : true ) ; // done when end-of-string encountered.
if (!bWaiting) {
iPromptFound |= WiFlyFixedFlags[iFixedPrompt]; // if a prompt found then grab its flag.
}
} // handle prompt-BEFORE-result case
} else {
pFixedCurrent[iFixedPrompt] = WiFlyFixedPrompts[iFixedPrompt]; // not next char expected; reset to beginning of string.
} // if tracking expected response
}
// If the *OPEN* signal caught then a connection was opened.
if (iPromptFound & (PROMPT_OPEN | PROMPT_OPEN_ALREADY) ) {
bWiFlyConnectionOpen = true;
bWiFlyInCommandMode = false;
iPromptFound &= (!WiFlyFixedFlags[WIFLY_MSG_CLOSE]); // clear prior close
}
// If the *CLOS* signal caught then a connection was closed
// and we dropped into command mode
if (iPromptFound & PROMPT_CLOSE ) {
bWiFlyConnectionOpen = false;
bWiFlyInCommandMode = true;
iPromptFound &= (!WiFlyFixedFlags[WIFLY_MSG_OPEN]); // clear prior open
}
} // if anything in uart
// did we time-out?
if ( (millis() - TimeAtStart) >= WaitTime) {
bWaiting = false;
}
} // while waiting for a line
// could capture and compare with known prompt
if ( bCollecting ) {
responseBuffer[bufpos]='\0';
}
return (int) iPromptFound;
} // ScanForPattern
// Start Command Mode
//
// Attempt up to 5 times
// test is "Get a command prompt matching results of 'ver' command".
// if InCommand mode, try a 'cr'.
// If no useful result, assume not actually in command mode, force with $$$
//
// Returns true for Command mode entered, false if not (something weird afoot).
boolean WiFlySerial::StartCommandMode(char* pBuffer, const int bufSize) {
byte iPromptResult = 0;
char* responseBuffer;
boolean bWaiting = true;
int nTries = 0;
if (pBuffer == NULL) {
responseBuffer = (char*) malloc(bufSize); // defaults to COMMAND_BUFFER_SIZE
} else {
responseBuffer = pBuffer;
}
unsigned long TimeOutTime = millis() + ATTN_WAIT_TIME;
// check if actually in command mode:
while (!bWiFlyInCommandMode || bWaiting ) {
// if not effectively in command mode, try $$$
if ( !bWiFlyInCommandMode) {
uart.flush();
// Send $$$ , wait a moment, look for CMD
delay(COMMAND_MODE_GUARD_TIME );
uart << GetBuffer_P(STI_WIFLYDEVICE_ATTN, responseBuffer, bufSize) ;
uart.flush();
delay(COMMAND_MODE_GUARD_TIME );
if (nTries >= 2) {
uart << "\r";
uart.flush();
}
// expect CMD without a cr
// WiFlyFixedPrompts[WIFLY_MSG_CMD]
iPromptResult = ScanForPattern( responseBuffer, bufSize, "CMD", true, ATTN_WAIT_TIME);
if ( iPromptResult & ( PROMPT_EXPECTED_TOKEN_FOUND | PROMPT_READY |PROMPT_CMD_MODE |PROMPT_CMD_ERR ) ) {
bWiFlyInCommandMode = true;
bWaiting = false;
} else {
bWiFlyInCommandMode = false;
} // if one of several indicators of command-mode received.
} else {
// think we are in a command-mode - try a cr, then add a version command to get through.
// send a ver + cr, should see a prompt.
if (nTries > 2) {
uart << GetBuffer_P(STI_WIFLYDEVICE_VER, responseBuffer, bufSize);
// DebugPrint("ver=");
// DebugPrint(responseBuffer);
}
// DebugPrint("***scm:InCommandMode***");
uart << "\r\r";
// bring in a cr-terminated line
uart.flush();
// wait for up to time limit for a cr to flow by
iPromptResult = ScanForPattern( responseBuffer, bufSize, szWiFlyPrompt, false);
// could have timed out, or have *READY*, CMD or have a nice CR.
if ( iPromptResult & ( PROMPT_EXPECTED_TOKEN_FOUND | PROMPT_AOK | PROMPT_READY |PROMPT_CMD_MODE |PROMPT_CMD_ERR ) ) {
bWiFlyInCommandMode = true;
bWaiting = false;
} else {
bWiFlyInCommandMode = false;
} // if one of several indicators of command-mode received.
} // else in in command command mode
if ( millis() >= TimeOutTime) {
bWaiting = false;
}
nTries++;
} // while trying to get into command mode
// clean up as needed
if (pBuffer == NULL) {
free (responseBuffer);
}
return bWiFlyInCommandMode;
}
// GetCmdPrompt
// Obtains the WiFly command prompt string for use by other command functions.
// Parameters: None
// Sets global szWiFlyPrompt
// Returns command prompt on success or empty string on failure
boolean WiFlySerial::GetCmdPrompt () {
boolean bOk = false;
char responseBuffer[RESPONSE_BUFFER_SIZE];
if ( StartCommandMode(responseBuffer, RESPONSE_BUFFER_SIZE) ) {
uart << GetBuffer_P(STI_WIFLYDEVICE_VER, responseBuffer, RESPONSE_BUFFER_SIZE ) << "\r";
uart.flush();
ScanForPattern(responseBuffer, RESPONSE_BUFFER_SIZE, WiFlyFixedPrompts[WIFLY_MSG_PROMPT2], true, COMMAND_MODE_GUARD_TIME);
char* pPromptStart = strrchr(responseBuffer, '<') ;
char* pPromptEnd = strrchr (responseBuffer, '>');
if ( (pPromptStart < pPromptEnd ) && pPromptStart && pPromptEnd) {
strncpy(szWiFlyPrompt, pPromptStart , (size_t) (pPromptEnd - pPromptStart)+1 );
szWiFlyPrompt[(pPromptEnd - pPromptStart)+1] = '\0';
}
}
if ( strlen (szWiFlyPrompt) > 1 ) {
bOk = true;
// DebugPrint( F("CmdPrompt:") );
// DebugPrint(szWiFlyPrompt);
} else {
bOk = false;
}
return bOk;
}
// SendCommand
// Issues a command to the WiFly device
// Captures results in Returned result
//
//
// Parameters:
// Command The inquiry-command to send
// SuccessIndicator String to indicate success
// pResultBuffer A place to put results of the command
// bufsize Length of the pResultBuffer
// bCollecting true = collect results, false=ignore results.
// iWaitTime Time in milliseconds to wait for a result.
// bClear true = drain any preceeding and subsequent characters, false=ignore
// bPromptAfterResult true=commands end with a version-prompt, false=version-prompt precedes results.
//
// Returns true on SuccessIndicator presence, false if absent.
boolean WiFlySerial::SendCommand( char *pCmd, char *SuccessIndicator, char* pResultBuffer, const int bufsize,
const boolean bCollecting, const unsigned long iWaitTime, const boolean bClear, const boolean bPromptAfterResult) {
boolean bCommandOK = false;
char ch;
int iResponse = 0;
int iTry = 0;
char* Command = pCmd;
if (pCmd == pResultBuffer ) {
Command = (char*) malloc( sizeof(pCmd) +1 );
strcpy( Command, pCmd);
}
//
// clear out leftover characters coming in
if ( bClear ) {
// DebugPrint("Clearing:");
while ( available() ) {
ch = (char) read();
// DebugPrint( ch);
}
}
//
DebugPrint( "Cmd:");
DebugPrint( Command );
// DebugPrint( " Ind:" );
// DebugPrint( SuccessIndicator);
if ( StartCommandMode(pResultBuffer, bufsize) ) {
uart.flush();
while ( ((iResponse & PROMPT_EXPECTED_TOKEN_FOUND) != PROMPT_EXPECTED_TOKEN_FOUND) && iTry < COMMAND_RETRY_ATTEMPTS ) {
uart << Command << "\r" ;
uart.flush();
iResponse = ScanForPattern( pResultBuffer, bufsize, SuccessIndicator, bCollecting, iWaitTime, bPromptAfterResult );
// DebugPrint("Try#:");
// DebugPrint( iTry );
// DebugPrint(" Res:");
// DebugPrint(iResponse);
iTry++;
}
}
if ( pCmd == pResultBuffer ) {
free (Command);
}
if ( bClear ) {
ScanForPattern(strchr(pResultBuffer, '\0') +1, bufsize - strlen(pResultBuffer) -1, WiFlyFixedPrompts[WIFLY_MSG_CLOSE], false, DEFAULT_WAIT_TIME, true);
// while ( (ch = uart.read() ) > -1 ) {
// DebugPrint(ch);
// }
} // clear out leftover characters
bCommandOK = ( ((iResponse & PROMPT_EXPECTED_TOKEN_FOUND) == PROMPT_EXPECTED_TOKEN_FOUND) ? true : false );
return bCommandOK;
}
// convenient and version with own small ignored response buffer.
boolean WiFlySerial::SendCommandSimple( char* pCommand, char* pSuccessIndicator) {
char bufResponse[INDICATOR_BUFFER_SIZE];
return SendCommand( pCommand, pSuccessIndicator, bufResponse, INDICATOR_BUFFER_SIZE, false );
}
// SendInquiry
// Inquiries provide a device setting result, terminated with a command prompt.
// No specific 'ok/fail' result shown, only ERR or requested response.
// Results placed into global responsebuffer
//
// Parameters:
// Command The inquiry-command to send
// pBuffer pointer to a buffer for the response
// bufsize size of the buffer
//
// Returns true on command success, false on failure.
boolean WiFlySerial::SendInquiry( char *Command, char* pBuffer, const int bufsize) {
return SendCommand(Command, szWiFlyPrompt, pBuffer, bufsize, true);
}
// SendInquiry
// Inquiries provide a device setting result, terminated with a command prompt.
// No specific 'ok/fail' result shown, only ERR or requested response.
// Results placed into global responsebuffer
//
// Parameters:
// Command The inquiry-command to send
//
// Returns true on command success, false on failure.
boolean WiFlySerial::SendInquirySimple( char *Command ) {
char InquiryBuffer[RESPONSE_BUFFER_SIZE];
boolean bSendInquiry = false;
bSendInquiry = SendCommand(Command, szWiFlyPrompt, InquiryBuffer, RESPONSE_BUFFER_SIZE, true);
// should trim to returned result less ExpectedPrompt
return bSendInquiry;
}
// exitCommandMode
// Exits from WiFly command mode.
//
// Watch the NSS for further traffic.
//
// Parameters:
// None
// Returns true on command success, false on failure.
boolean WiFlySerial::exitCommandMode() {
char szCmd[INDICATOR_BUFFER_SIZE]; // exit command is short
char szPrompt[INDICATOR_BUFFER_SIZE]; // exit Prompt is short: EXIT (which looks like 'exit' but in upper case).
char szResponse[INDICATOR_BUFFER_SIZE]; // small buffer for result
bWiFlyInCommandMode = !SendCommand( GetBuffer_P(STI_WIFLYDEVICE_LEAVE_CMD_MODE, szCmd, INDICATOR_BUFFER_SIZE),
strupr(GetBuffer_P(STI_WIFLYDEVICE_LEAVE_CMD_MODE, szPrompt, INDICATOR_BUFFER_SIZE)),
szResponse, INDICATOR_BUFFER_SIZE, false );
bWiFlyInCommandMode = false;
return bWiFlyInCommandMode;
}
// showNetworkScan
// Displays list of available WiFi networks.
//
// Parameters:
// pNetScan Buffer for scan results (should be large)
// buflen length of buffer
char* WiFlySerial::showNetworkScan( char* pNetScan, const int buflen) {
SendCommand("scan","'", pNetScan, buflen, true, JOIN_WAIT_TIME, true, false) ;
return pNetScan;
}
// setProtocol
// Sets WiFly's communication protocol
// TCP or UDP
//
// Parameters:
// iProtocol Hex value for protocol - bit mapped values.
// Returns true for success, false for failure or error in call
//
// Note:
// Switching from one to the other requires a reboot of the WiFly.
// For UDP, set all other settings first (unlike example in manual) ; UDP traffic will start upon WiFly reboot.
// This version does not attempt to determine current mode. Reboot forced.
boolean WiFlySerial::setProtocol( unsigned int iProtocol) {
boolean bOk = false;
unsigned int iMode = 0, iTmp;
char bufMode[10];
iTmp = iProtocol & WIFLY_IPMODE_TCP;
if ( iTmp != 0x00 ) {
iMode |= 0x02;
}
iTmp = WIFLY_IPMODE_UDP & iProtocol;
if (iTmp ) {
iMode |= 0x01;
}
itoa( iMode, bufMode, 10);
bOk = issueSetting( STI_WIFLYDEVICE_SET_PROTOCOL, bufMode );
// Save settings
char szCommand[SMALL_COMMAND_BUFFER_SIZE];
GetBuffer_P(STI_WIFLYDEVICE_SAVE, szCommand, SMALL_COMMAND_BUFFER_SIZE);
bOk = SendCommandSimple(szCommand , WiFlyFixedPrompts[WIFLY_MSG_AOK]);
reboot();
// Allow WiFly to restart
delay (WIFLY_RESTART_WAIT_TIME);
return bOk;
}
// openConnection
// Opens a TCP connection to the provided URL and port (defaults to 80)
//
// Parameters:
// pURL IP or dns name of server to connect to.
// iWaitTime Time to wait for connection
//
// Returns: true on success, false on failure.
// Remote Port number is set through SetRemotePort
// Note that opened ports can be closed externally / lost connection at any time.
// Opening a connection switches to Data mode from Command mode.
//
// Note: Open and Scan each generate a version-prompt BEFORE results, not after.
boolean WiFlySerial::openConnection(const char* pURL, const unsigned long iWaitTime) {
char bufOpen[INDICATOR_BUFFER_SIZE];
char bufCommand[COMMAND_BUFFER_SIZE];
memset (bufCommand, '\0', COMMAND_BUFFER_SIZE);
GetBuffer_P(STI_WIFLYDEVICE_OPEN, bufCommand, COMMAND_BUFFER_SIZE);
strcat (bufCommand, pURL);
strcat (bufCommand, " ");
itoa( iRemotePort, strchr(bufCommand, '\0'), 10);
DebugPrint("openConnection:");
DebugPrint(bufCommand);
bWiFlyConnectionOpen = SendCommand(bufCommand,WiFlyFixedPrompts[WIFLY_MSG_OPEN], bufOpen, INDICATOR_BUFFER_SIZE, false, iWaitTime , true, false);
if( bWiFlyConnectionOpen) {
bWiFlyInCommandMode = false;
}
return bWiFlyConnectionOpen;
}
// closeConnection
// closes an open connection
//
// Parameters:
// bSafeClose (default) Use slow 'safe close'
// false if high confidence connection is in fact open,
// and can tolerate occasional errors if connection
// closes sooner than expected.
//
// returns true on close, false on failure.
// Side effects: bWiFlyConnectionOpen should become false
// and bWiFlyInCommandMode should become true.
//
// Notes:
// 1. When closed via a command the WiFly state is in command mode.
// 2. External connection close leaves WiFly in data mode
// 3. Closing a closed connection results in an error.
// 4. External connection close could happen at any time.
// 5. getDeviceStatus() gives actual WiFly status at the moment of calling.
// 6. When opened via listening, info from previous getDeviceStatus() is out-of-date.
// 7. The 'close' command results with a command-prompt, no 'AOK' or similar.
// then, a *CLOS* signal appears.
//
// returns true on closure, false on failure to close.
//
boolean WiFlySerial::closeConnection(boolean bSafeClose) {
// if a connection is open then close it.
char chDrain;
if ( bWiFlyConnectionOpen ) {
// first see if connection is *STILL* open.
boolean bClosed = false;
boolean bTrySafeClose = bSafeClose;
boolean bDoClose = true;
// repeat until closed...
while ( bWiFlyConnectionOpen ) {
if (bTrySafeClose) {
getDeviceStatus();
if ( isTCPConnected() && bWiFlyConnectionOpen ) {
bDoClose = true;
} else {
bDoClose = false;
bWiFlyConnectionOpen = false; // should be redundant as a caught *CLOS* will set this to false.
}
} // if doing safe close
if ( bDoClose ) {
drain();
char bufCmd[INDICATOR_BUFFER_SIZE];
char bufClose[INDICATOR_BUFFER_SIZE];
memset( bufCmd, '\0', INDICATOR_BUFFER_SIZE);
memset( bufClose, '\0', INDICATOR_BUFFER_SIZE);
// close command response is a prompt, then a *CLOS* signal after.
SendCommand(GetBuffer_P(STI_WIFLYDEVICE_CLOSE, bufCmd, INDICATOR_BUFFER_SIZE),WiFlyFixedPrompts[WIFLY_MSG_PROMPT], bufClose, INDICATOR_BUFFER_SIZE, true, DEFAULT_WAIT_TIME , false);
DebugPrint( bufCmd );
DebugPrint( bufClose );
drain();
bWiFlyInCommandMode = true;
}
} // while
} else {
// closed externally already.
// No change to bWiFlyCommandMode.
return true;
}
return true;
}
// drain
// Empties incoming buffer
int WiFlySerial::drain() {
char chDrain;
unsigned long TimeOutTime = millis() + DEFAULT_WAIT_TIME;
// DebugPrint("Waiting for signal");
while ( bWiFlyConnectionOpen && available() > 0 && millis() < TimeOutTime ) {
chDrain = read();
DebugPrint( chDrain );
}
// DebugPrint("Drained.");
}
// serveConnection
// Waits for a client to connect on the given port.
//
// Parameters:
// reconnectWaitTime Duration to wait before verifying wlan and reconnecting if needed.
//
// returns true on connection, false on internal failure.
//
boolean WiFlySerial::serveConnection( const unsigned long reconnectWaitTime )
{
char bufRequest[COMMAND_BUFFER_SIZE];
int iRequest;
boolean bReturn = false;
iRequest = ScanForPattern( bufRequest, COMMAND_BUFFER_SIZE, WiFlyFixedPrompts[WIFLY_MSG_OPEN], false,reconnectWaitTime );
if ( ( iRequest & PROMPT_EXPECTED_TOKEN_FOUND) == PROMPT_EXPECTED_TOKEN_FOUND ) {
//memset (bufRequest,'\0',COMMAND_BUFFER_SIZE);
bWiFlyInCommandMode = false;
bReturn = true;
} else {