-
Notifications
You must be signed in to change notification settings - Fork 60
/
Copy pathGSwifi.cpp
1378 lines (1165 loc) · 39.7 KB
/
GSwifi.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) 2013 gsfan, MIT License
* Copyright (C) 2013-2014 Masakazu Ohtsuka
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software
* and associated documentation files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge, publish, distribute,
* sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/** @file
* @brief Gainspan wi-fi module library for Arduino
* GS1011MIC, GS1011MIP, GainSpan WiFi Breakout, etc.
*/
#include "Arduino.h"
#include "pgmStrToRAM.h"
#include "GSwifi.h"
#include "GSwifi_const.h"
#include "MemoryFree.h"
#include "convert.h"
#include "ringbuffer.h"
#include "version.h"
#include "timer.h"
#include "base64encoder.h"
#include "log.h"
#include "cert.h"
#include <avr/eeprom.h>
#include "const.h"
#include "env.h"
#include "commands.h"
extern void software_reset();
extern void wifi_hardware_reset();
extern struct RingBuffer commands;
#define RESPONSE_LINES_ENDED -1
#define NEXT_TOKEN_CID 0
#define NEXT_TOKEN_IP 1
#define NEXT_TOKEN_PORT 2
#define NEXT_TOKEN_LENGTH 3
#define NEXT_TOKEN_DATA 4
// memory is corruputed or something terrible that only AVR reset can rescue us
#define ASSERT(a) if (!(a)) { software_reset(); }
static char __buf_cmd[GS_CMD_SIZE + 1];
static void base64encoded( char encoded ) {
Serial1X.print(encoded);
GSLOG_PRINT(encoded);
}
GSwifi::GSwifi( HardwareSerialX *serial ) :
serial_(serial),
server_cid_(-1)
{
_buf_cmd = &ring_buffer_;
ring_init( _buf_cmd, __buf_cmd, GS_CMD_SIZE + 1 );
}
// factory should issue following commands:
// % AT
// % ATE0
// % ATB=38400
// % AT&W0
// % AT&Y0
int8_t GSwifi::setup(GSEventHandler on_disconnect, GSEventHandler on_reset) {
on_disconnect_ = on_disconnect;
on_reset_ = on_reset;
clear();
// baud rate is written into default profile in factory
serial_->begin(57600);
// how to change baud rate (2.5.1 has only one profile, don't need to send AT&Y0)
// setBaud(57600);
// command(PB("ATE0",1), GSCOMMANDMODE_NORMAL);
// command(PB("AT&W0",1), GSCOMMANDMODE_NORMAL);
// command(PB("AT&Y0",1), GSCOMMANDMODE_NORMAL);
// need this to ignore initial response
command(PB("AT",1), GSCOMMANDMODE_NORMAL);
if (did_timeout_) {
// return here to speed up after hardware reset
return -1;
}
// disable external PA
// we might be connected to GS1011MIPS or GS1011MEPS
command(PB("AT+EXTPA=0",1), GSCOMMANDMODE_NORMAL);
delay( 100 );
// explicitly set transmit power
command(PB("AT+WP=0",1), GSCOMMANDMODE_NORMAL);
// write this before AT&K1, cert includes XON or XOFF hex
writeCert();
// enable software flow control
command(PB("AT&K1",1), GSCOMMANDMODE_NORMAL);
// get my mac address
command(PB("AT+NMAC=?",1), GSCOMMANDMODE_MAC);
// disable association keep alive timer
command(PB("AT+PSPOLLINTRL=0",1), GSCOMMANDMODE_NORMAL);
// set system time (must be within cert valid period)
command(PB("AT+SETTIME=01/01/2015,00:00:00",1), GSCOMMANDMODE_NORMAL);
if (did_timeout_) {
return -1;
}
return 0;
}
// mDNS setup has to be done while joined to network
int8_t GSwifi::setupMDNS() {
char *cmd;
// no impact on discoverability
// command(PB("AT+DHCPSRV",1), GSCOMMANDMODE_NORMAL);
command(PB("AT+MDNSSTART",1), GSCOMMANDMODE_NORMAL);
// ex: "00:1d:c9:01:99:99"
cmd = PB("AT+MDNSHNREG=IRKitXXXX,local",1);
strcpy( cmd+13, hostname() );
cmd[22] = ',';
command(cmd, GSCOMMANDMODE_MDNS);
cmd = PB("AT+MDNSSRVREG=IRKitXXXX,,_irkit,_tcp,local,80",1);
strcpy( cmd+14, hostname() );
cmd[23] = ',';
command(cmd, GSCOMMANDMODE_MDNS);
command(PB("AT+MDNSANNOUNCE",1), GSCOMMANDMODE_NORMAL);
if (did_timeout_) {
return -1;
}
return 0;
}
#ifdef FACTORY_CHECKER
int8_t GSwifi::factorySetup(uint32_t initial_baud) {
clear();
// version 2.5.1 firmware starts with 115200 baud rate
// version 2.5.1 (Tue, Dec 10, 2013 at 2:14 PM) firmware starts with 9600 baud rate
// version 2.4.3 firmware starts with 9600 baud rate
serial_->begin(initial_baud);
// need this to ignore invalid response
command(PB("AT",1), GSCOMMANDMODE_NORMAL, GS_TIMEOUT_SHORT);
if (did_timeout_) {
return -1;
}
setBaud(57600);
command(PB("ATE0",1), GSCOMMANDMODE_NORMAL);
// enable bulk data mode
command(PB("AT+BDATA=1",1), GSCOMMANDMODE_NORMAL);
command(PB("AT&W0",1), GSCOMMANDMODE_NORMAL);
if (did_timeout_) {
return -1;
}
return 0;
}
int8_t GSwifi::checkVersion() {
command(PB("AT+VER=?",1), GSCOMMANDMODE_VERSION);
if (did_timeout_) {
return -1;
}
return 0;
}
const char *GSwifi::appVersion() {
return versions_[ 0 ];
}
const char *GSwifi::gepsVersion() {
return versions_[ 1 ];
}
const char *GSwifi::wlanVersion() {
return versions_[ 2 ];
}
#endif // FACTORY_CHECKER
// does recurse
int8_t GSwifi::close (int8_t cid) {
char *cmd = PB("AT+NCLOSE=0", 1);
cmd[ 10 ] = i2x(cid);
TIMER_STOP( timers_[cid] );
command(cmd, GSCOMMANDMODE_NORMAL);
if (did_timeout_) {
return -1;
}
return 0;
}
void GSwifi::clear () {
joined_ = false;
listening_ = false;
limited_ap_ = false;
resetResponse(GSCOMMANDMODE_NONE);
gs_mode_ = GSMODE_COMMAND;
ring_clear(_buf_cmd);
memset(ipaddr_, 0, sizeof(ipaddr_));
for (uint8_t i=0; i<16; i++) {
TIMER_STOP( timers_[i] );
}
}
void GSwifi::loop() {
TIMER_STOP( timeout_timer_ );
checkActivity();
for (uint8_t i=0; i<16; i++) {
if (! cidIsRequest(i) &&
TIMER_FIRED(timers_[i])) {
TIMER_STOP(timers_[i]);
GSLOG_PRINT("!E4 "); GSLOG_PRINTLN(i);
// request (from us) timeout means GS is in trouble,
// and it's easy to just rescue ourselves to reset
wifi_hardware_reset();
return;
}
}
}
void GSwifi::reset () {
command(PB("AT+RESET",1), GSCOMMANDMODE_NONE, GS_TIMEOUT_NOWAIT);
}
// received a character from UART
void GSwifi::parseByte(uint8_t dat) {
static uint8_t next_token; // split each byte into tokens (cid,ip,port,length,data)
static bool escape = false;
char temp[GS_MAX_PATH_LENGTH+1];
if (dat == ESCAPE) {
// 0x1B : Escape
GSLOG_PRINT("e< ");
}
else { // if (next_token != NEXT_TOKEN_DATA) {
GSLOG_WRITE(dat);
}
if (gs_mode_ == GSMODE_COMMAND) {
if (escape) {
// esc
switch (dat) {
case 'O':
case 'F':
// ignore
break;
case 'Z':
case 'H':
gs_mode_ = GSMODE_DATA_RX_BULK;
next_token = NEXT_TOKEN_CID;
break;
default:
// GSLOG_PRINT("!E1 "); GSLOG_PRINTLN2(dat,HEX);
break;
}
escape = false;
}
else {
if (dat == ESCAPE) {
escape = true;
}
else if (dat == '\n') {
// end of line
parseLine();
}
else if (dat != '\r') {
if ( ! ring_isfull(_buf_cmd) ) {
ring_put(_buf_cmd, dat);
}
else {
GSLOG_PRINTLN("!E2");
}
}
}
return;
}
else if (gs_mode_ != GSMODE_DATA_RX_BULK) {
return;
}
static uint16_t len;
static char len_chars[5];
static int8_t current_cid;
static GSREQUESTSTATE request_state;
if (next_token == NEXT_TOKEN_CID) {
// dat is cid
current_cid = x2i(dat);
ASSERT((0 <= current_cid) && (current_cid <= 16));
next_token = NEXT_TOKEN_LENGTH;
len = 0;
}
else if (next_token == NEXT_TOKEN_LENGTH) {
// Data Length is 4 ascii char represents decimal value i.e. 1400 byte (0x31 0x34 0x30 0x30)
len_chars[ len ++ ] = dat;
if (len >= 4) {
len_chars[ len ] = 0;
len = atoi(len_chars); // length of data
next_token = NEXT_TOKEN_DATA;
if (content_lengths_[ current_cid ] > 0) {
// this is our 2nd bulk message from GS for this response
// we already swallowed HTTP response headers,
// following should be body
request_state = GSREQUESTSTATE_BODY;
}
else {
request_state = GSREQUESTSTATE_HEAD1;
}
ring_clear( _buf_cmd ); // reuse _buf_cmd to store HTTP request
}
}
else if (next_token == NEXT_TOKEN_DATA) {
len --;
if (cidIsRequest(current_cid)) { // request against us
static uint16_t error_code;
static int8_t routeid;
switch (request_state) {
case GSREQUESTSTATE_HEAD1:
if (dat != '\n') {
if ( ! ring_isfull(_buf_cmd) ) {
ring_put( _buf_cmd, dat );
}
// ignore overflowed
}
else {
// end of request line
// reuse "temp" buffer to parse method and path
int8_t result = parseRequestLine((char*)temp, 7);
GSMETHOD method = GSMETHOD_UNKNOWN;
if ( result == 0 ) {
method = x2method(temp);
result = parseRequestLine((char*)temp, GS_MAX_PATH_LENGTH);
}
if ( result != 0 ) {
// couldn't detect method or path
request_state = GSREQUESTSTATE_ERROR;
error_code = 400;
ring_clear(_buf_cmd);
break;
}
routeid = router(method, temp);
if ( routeid < 0 ) {
request_state = GSREQUESTSTATE_ERROR;
error_code = 404;
ring_clear(_buf_cmd);
break;
}
request_state = GSREQUESTSTATE_HEAD2;
continuous_newlines_ = 0;
content_lengths_[ current_cid ] = 0;
ring_clear(_buf_cmd);
}
break;
case GSREQUESTSTATE_HEAD2:
if(0 == parseHead2(dat, current_cid)) {
request_state = GSREQUESTSTATE_BODY;
// dispatched once, at start of body
dispatchRequestHandler(current_cid, routeid, GSREQUESTSTATE_BODY_START);
}
break;
case GSREQUESTSTATE_BODY:
if (content_lengths_[ current_cid ] > 0) {
content_lengths_[ current_cid ] --;
}
if (ring_isfull(_buf_cmd)) {
dispatchRequestHandler(current_cid, routeid, request_state); // POST, user callback should write()
}
ring_put(_buf_cmd, dat);
break;
case GSREQUESTSTATE_ERROR:
// skip until received whole request
break;
case GSREQUESTSTATE_RECEIVED:
default:
break;
}
// end of bulk transfered data
if (len == 0) {
gs_mode_ = GSMODE_COMMAND;
if ( request_state == GSREQUESTSTATE_ERROR ) {
writeHead( current_cid, error_code );
writeEnd();
ring_put( &commands, COMMAND_CLOSE );
ring_put( &commands, current_cid );
}
else {
if (content_lengths_[ current_cid ] == 0) {
// if Content-Length header was longer than <ESC>Z length,
// we wait til next bulk transfer
request_state = GSREQUESTSTATE_RECEIVED;
}
// user callback should write(), writeEnd() and close()
dispatchRequestHandler(current_cid, routeid, request_state);
}
ring_clear(_buf_cmd);
}
}
else {
// is request from us
static uint16_t status_code;
switch (request_state) {
case GSREQUESTSTATE_HEAD1:
if (dat != '\n') {
if ( ! ring_isfull(_buf_cmd) ) {
// ignore if overflowed
ring_put( _buf_cmd, dat );
}
}
else {
uint8_t i=0;
// skip 9 characters "HTTP/1.1 "
while (i++ < 9) {
ring_get( _buf_cmd, &temp[0], 1 );
}
// copy 3 numbers representing status code into temp buffer
temp[ 3 ] = 0;
int8_t count = ring_get( _buf_cmd, temp, 3 );
if (count != 3) {
// protocol error
// we should receive something like: "200 OK", "401 Unauthorized"
status_code = 999;
request_state = GSREQUESTSTATE_ERROR;
break;
}
status_code = atoi(temp);
request_state = GSREQUESTSTATE_HEAD2;
continuous_newlines_ = 0;
content_lengths_[ current_cid ] = 0;
ring_clear(_buf_cmd);
}
break;
case GSREQUESTSTATE_HEAD2:
if(0 == parseHead2(dat, current_cid)) {
request_state = GSREQUESTSTATE_BODY;
// dispatched once, at start of body
dispatchResponseHandler(current_cid, status_code, GSREQUESTSTATE_BODY_START);
}
break;
case GSREQUESTSTATE_BODY:
if (content_lengths_[ current_cid ] > 0) {
content_lengths_[ current_cid ] --;
}
if (ring_isfull(_buf_cmd)) {
dispatchResponseHandler(current_cid, status_code, GSREQUESTSTATE_BODY);
}
ring_put(_buf_cmd, dat);
break;
case GSREQUESTSTATE_ERROR:
case GSREQUESTSTATE_RECEIVED:
default:
break;
}
if (len == 0) {
gs_mode_ = GSMODE_COMMAND;
if ( request_state == GSREQUESTSTATE_ERROR ) {
dispatchResponseHandler(current_cid, status_code, request_state);
}
else {
if (content_lengths_[ current_cid ] == 0) {
// if Content-Length header was longer than <ESC>Z length,
// we wait til all response body received.
// we need to close our clientRequest before handling it.
// GS often locks when closing 2 connections in a row
// ex: POST /keys from iPhone (cid:1) -> POST /keys to server (cid:2)
// response from server arrives -> close(1) -> close(2) -> lock!!
// the other way around: close(2) -> close(1) doesn't lock :(
request_state = GSREQUESTSTATE_RECEIVED;
}
dispatchResponseHandler(current_cid, status_code, request_state);
}
ring_clear( _buf_cmd );
}
} // is response
} // (next_token == NEXT_TOKEN_DATA)
}
int8_t GSwifi::parseHead2(uint8_t dat, int8_t cid) {
if (dat == '\n') {
continuous_newlines_ ++;
}
else if (dat == '\r') {
// preserve
}
else {
continuous_newlines_ = 0;
if ( ! ring_isfull(_buf_cmd) ) {
// ignore if overflowed
ring_put( _buf_cmd, dat );
}
}
if (continuous_newlines_ == 1) {
// check "Content-Length: x" header
// if it's non 0, wait for more body data
// otherwise disconnect after handling response
// GS splits HTTP requests/responses into multiple bulk messages,
// 1st ends just after headers, and 2nd contains only response body
// "Content-Length: " .length = 16
// "Content-Length: 9999".length = 20
char content_length_chars[21];
memset( content_length_chars, 0, 21 );
uint8_t copied = ring_get( _buf_cmd, content_length_chars, 20 );
if ((copied >= 16) &&
(strncmp(content_length_chars, "Content-Length: ", 16) == 0)) {
content_length_chars[20] = 0;
content_lengths_[ cid ] = atoi(&content_length_chars[16]);
}
ring_clear(_buf_cmd);
}
if (continuous_newlines_ == 2) {
// if detected double (\r)\n, switch to body mode
ring_clear(_buf_cmd);
return 0;
}
return -1;
}
int8_t GSwifi::parseRequestLine (char *token, uint8_t token_size) {
uint8_t i;
for ( i = 0; i <= token_size; i++ ) {
if (ring_isempty( _buf_cmd )) {
return -1; // space didn't appear
}
ring_get( _buf_cmd, token+i, 1 );
if (token[i] == ' ') {
token[i] = '\0';
break;
}
}
if ( i == token_size + 1 ) {
return -1; // couldnt detect token
}
return 0;
}
int8_t GSwifi::router (GSMETHOD method, const char *path) {
if (method == GSMETHOD_UNKNOWN) {
return -1;
}
uint8_t i;
for (i = 0; i < route_count_; i ++) {
if ((method == routes_[i].method) &&
(strncmp(path, routes_[i].path, GS_MAX_PATH_LENGTH) == 0)) {
return i;
}
}
return -1;
}
void GSwifi::clearRoutes () {
route_count_ = 0;
}
int8_t GSwifi::registerRoute (GSwifi::GSMETHOD method, const char *path) {
if ( route_count_ >= GS_MAX_ROUTES ) {
return -1;
}
routes_[ route_count_ ].method = method;
sprintf( routes_[ route_count_ ].path, "%s", path );
route_count_ ++;
}
void GSwifi::setRequestHandler (GSRequestHandler handler) {
request_handler_ = handler;
}
// request against us
int8_t GSwifi::dispatchRequestHandler (int8_t cid, int8_t routeid, GSREQUESTSTATE state) {
return request_handler_(cid, routeid, state);
}
// response to our request
int8_t GSwifi::dispatchResponseHandler (int8_t cid, uint16_t status_code, GSREQUESTSTATE state) {
return handlers_[ cid ](cid, status_code, state);
}
inline void GSwifi::setCidIsRequest(int8_t cid, bool is_request) {
if (is_request) {
cid_bitmap_ |= _BV(cid);
}
else {
cid_bitmap_ &= ~_BV(cid);
}
}
// request against us
inline bool GSwifi::cidIsRequest(int8_t cid) {
return cid_bitmap_ & _BV(cid);
}
int8_t GSwifi::writeHead (int8_t cid, uint16_t status_code) {
char *cmd = PB("S0",1);
cmd[ 1 ] = i2x(cid);
escape( cmd );
serial_->print(P("HTTP/1.0 "));
char *msg;
switch (status_code) {
case 200:
msg = P("200 OK");
break;
case 400:
msg = P("400 Bad Request");
break;
case 404:
msg = P("404 Not Found");
break;
case 500:
default:
msg = P("500 Internal Server Error");
break;
}
serial_->println(msg);
serial_->print("Access-Control-Allow-Origin: *\r\nServer: IRKit/");
serial_->println(version);
serial_->println(P("Content-Type: text/plain\r\n"));
}
void GSwifi::write (const char *data) {
serial_->print(data);
}
void GSwifi::write (const char data) {
serial_->print(data);
}
void GSwifi::write (const uint8_t data) {
serial_->print(data);
}
void GSwifi::write (const uint16_t data) {
serial_->print(data);
}
int8_t GSwifi::writeEnd () {
escape( "E" );
}
void GSwifi::writeCert() {
// Binary format, store in memory
command( "AT+TCERTADD=cacert,0,753,1", GSCOMMANDMODE_NORMAL );
resetResponse(GSCOMMANDMODE_NORMAL);
// ESCAPE 'W' is written in pgm too (thus +2)
for (uint16_t i=0; i<753 + 2; i++) {
uint8_t read = pgm_read_byte_near(der + i);
serial_->write( read );
Serial.print( read, HEX );
}
setBusy(true);
waitResponse(GS_TIMEOUT);
}
GSwifi::GSMETHOD GSwifi::x2method(const char *method) {
if (strncmp(method, "GET", 3) == 0) {
return GSMETHOD_GET;
}
else if (strncmp(method, "POST", 4) == 0) {
return GSMETHOD_POST;
}
return GSMETHOD_UNKNOWN;
}
void GSwifi::parseLine () {
static char buf[GS_CMD_SIZE];
while (! ring_isempty(_buf_cmd)) {
// received "\n"
uint8_t i = 0;
while ( (! ring_isempty(_buf_cmd)) &&
(i < sizeof(buf) - 1) ) {
ring_get( _buf_cmd, &buf[i], 1 );
if (buf[i] == '\n') {
break;
}
i ++;
}
if (i == 0) continue;
buf[i] = 0;
if ( (gs_mode_ == GSMODE_COMMAND) &&
(gs_commandmode_ != GSCOMMANDMODE_NONE) ) {
parseCmdResponse(buf);
}
if (strncmp(buf, P("CONNECT "), 8) == 0 && buf[8] >= '0' && buf[8] <= 'F' && buf[9] != 0) {
// connect from client
// CONNECT 0 1 192.168.2.1 63632
// 1st cid is our http server's
// 2nd cid is for client
// next line will be "[ESC]Z10140GET / ..."
int8_t cid = x2i(buf[10]); // 2nd cid = HTTP client cid
ASSERT((0 <= cid) && (cid <= 16));
setCidIsRequest(cid, true);
content_lengths_[ cid ] = 0;
// don't close other connections,
// other connections close theirselves on their turn
// ignore client's IP and port
}
else if (strncmp(buf, P("DISCONNECT "), 11) == 0) {
int8_t cid = x2i(buf[11]);
ASSERT((0 <= cid) && (cid <= 16));
if (cid == server_cid_) {
// if it's our server, this is fatal
reset();
}
else if (! cidIsRequest(cid) ) {
// request *from* us was disconnected (ex: polling)
dispatchResponseHandler(cid, HTTP_STATUSCODE_DISCONNECT, GSREQUESTSTATE_ERROR);
}
}
else if (strncmp(buf, P("DISASSOCIATED"), 13) == 0 ||
strncmp(buf, P("Disassociat"), 11) == 0) {
// Disassociated
// Disassociation Event
clear();
on_disconnect_();
gs_failure_ = true;
}
else if (strncmp(buf, P("APP Reset"), 9) == 0 ||
strncmp(buf, P("Serial2WiFi APP"), 15) == 0) {
// APP Reset-APP SW Reset
// APP Reset-Wlan Except
// Serial2Wifi APP
on_reset_();
gs_failure_ = true;
}
// else if (strncmp(buf, P("Out of StandBy-Timer"), 20) == 0 ||
// strncmp(buf, P("Out of StandBy-Alarm"), 20) == 0) {
// }
// else if (strncmp(buf, P("Out of Deep Sleep"), 17) == 0 ) {
// }
}
}
void GSwifi::parseCmdResponse (char *buf) {
GSLOG_PRINT(P("c< ")); GSLOG_PRINTLN(buf);
if (strncmp(buf, "OK", 3) == 0) {
gs_ok_ = true;
}
else if (strncmp(buf, "ERROR", 5) == 0) {
gs_failure_ = true;
}
switch(gs_commandmode_) {
case GSCOMMANDMODE_NORMAL:
gs_response_lines_ = RESPONSE_LINES_ENDED;
break;
case GSCOMMANDMODE_CONNECT:
if (strncmp(buf, P("CONNECT "), 8) == 0 && buf[9] == 0) {
// both "AT+NSTCP=port" and "AT+NCTCP=ip,port" responds with
// CONNECT <cid>
// following lines are needed for client cids,
// but won't be a problem if we run it for a server cid
gs_response_lines_ = RESPONSE_LINES_ENDED;
int8_t cid = x2i(buf[8]);
ASSERT((0 <= cid) && (cid <= 16));
setCidIsRequest(cid, false);
content_lengths_[ cid ] = 0;
// don't close other connections,
// other connections close theirselves on their turn
TIMER_STOP(timers_[cid]);
connected_cid_ = cid;
}
break;
case GSCOMMANDMODE_DHCP:
if (gs_response_lines_ == 0 && strstr(buf, P("SubNet"))) {
gs_response_lines_ ++;
}
else if (gs_response_lines_ == 1) {
gs_response_lines_ = RESPONSE_LINES_ENDED;
}
break;
case GSCOMMANDMODE_DNSLOOKUP:
if (strncmp(buf, P("IP:"), 3) == 0) {
sprintf( ipaddr_, "%s", &buf[3] );
gs_response_lines_ = RESPONSE_LINES_ENDED;
}
break;
case GSCOMMANDMODE_MDNS:
if (gs_response_lines_ == 0) {
// 1st line is just OK
gs_response_lines_ ++;
}
else if (gs_response_lines_ == 1) {
// 2nd line is something like:
// " Registration Success!! for RR: IRKitXXXX"
gs_response_lines_ = RESPONSE_LINES_ENDED;
}
break;
case GSCOMMANDMODE_MAC:
if ((gs_response_lines_ == 0) && (buf[2] == ':')) {
// 1st line is something like:
// "00:1d:c9:01:99:99"
for (uint8_t i=0; i<17; i++) {
if (buf[i] >= 'a') {
buf[i] -= 0x20; // a -> A
}
}
sprintf( mac_, "%s", buf );
gs_response_lines_ ++;
}
else if (gs_response_lines_ == 1) {
// 2nd line is just "OK"
gs_response_lines_ = RESPONSE_LINES_ENDED;
}
break;
#ifdef FACTORY_CHECKER
case GSCOMMANDMODE_VERSION:
// expects something like:
// S2W APP VERSION=2.4.3
// S2W GEPS VERSION=2.4.3
// S2W WLAN VERSION=2.4.1
if (gs_response_lines_ == 0) {
memset(versions_, 0, sizeof(versions_));
snprintf(versions_[0], 8, buf+16);
gs_response_lines_ ++;
}
else if (gs_response_lines_ == 1) {
snprintf(versions_[1], 8, buf+17);
gs_response_lines_ ++;
}
else if (gs_response_lines_ == 2) {
snprintf(versions_[2], 8, buf+17);
gs_response_lines_ = RESPONSE_LINES_ENDED;
}
break;
#endif
default:
break;
}
return;
}
void GSwifi::command (const char *cmd, GSCOMMANDMODE res, uint8_t timeout_second) {
// GSLOG_PRINT(P("F: 0x")); GSLOG_PRINTLN2( freeMemory(), HEX );
GSLOG_PRINT(P("c> "));
resetResponse(res);
serial_->println(cmd);
GSLOG_PRINTLN(cmd);
if (timeout_second == GS_TIMEOUT_NOWAIT) {
return;
}
setBusy(true);
waitResponse(timeout_second);
}
void GSwifi::escape (const char *cmd, uint8_t timeout_second) {
GSLOG_PRINT(P("e> "));
resetResponse(GSCOMMANDMODE_NONE);
serial_->write( ESCAPE );
serial_->print(cmd); // without ln
GSLOG_PRINTLN(cmd);
}
void GSwifi::resetResponse (GSCOMMANDMODE res) {
gs_ok_ = false;
gs_failure_ = false;
gs_response_lines_ = 0;
gs_commandmode_ = res;
}
bool GSwifi::setBusy(bool busy) {
if (busy) {
did_timeout_ = false;
}
return busy_ = busy;
}
uint8_t GSwifi::checkActivity() {
static uint8_t continuous_timeouts_ = 0;
while ( serial_->available() &&
! TIMER_FIRED(timeout_timer_) ) {
parseByte( serial_->read() );
if ( gs_failure_ ||
(gs_ok_ &&
(gs_response_lines_ == RESPONSE_LINES_ENDED ||
gs_commandmode_ == GSCOMMANDMODE_NONE)) ) {
gs_commandmode_ = GSCOMMANDMODE_NONE;
continuous_timeouts_ = 0;
setBusy(false);
break;
}
}
if ( busy_ &&
TIMER_FIRED(timeout_timer_) ) {
TIMER_STOP(timeout_timer_);
GSLOG_PRINTLN("!E24");
did_timeout_ = true;
continuous_timeouts_ ++;
setBusy(false);
}
// need a GS hardware reset, which we issue in setup()
ASSERT( continuous_timeouts_ <= 5 );
return busy_;
}
void GSwifi::waitResponse (uint8_t timeout_second) {
TIMER_START( timeout_timer_, timeout_second );
while ( checkActivity() ) {
}
}
int8_t GSwifi::join (GSSECURITY sec, const char *ssid, const char *pass, int dhcp, char *name_) {
char *cmd;
uint8_t offset;
if (joined_) {
return -1;
}
disconnect();
// infrastructure mode
command(PB("AT+WM=0",1), GSCOMMANDMODE_NORMAL);
// set DHCP name with mac address
cmd = PB("AT+NDHCP=1,%",1);
strcpy( cmd+11, hostname());