-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMyLib.cpp
More file actions
1612 lines (1339 loc) · 44.2 KB
/
MyLib.cpp
File metadata and controls
1612 lines (1339 loc) · 44.2 KB
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
#include <MyLib.h>
#ifdef MYLIB_ESP8266
extern "C" {
#include <user_interface.h> // for sleep mode
}
#include <ESP8266HTTPClient.h>
#include <WakeOnLan.h>
#endif
// **** MAC Address, Device Name ******************************************************************************
#ifdef MYLIB_ESP8266
uint8_t macAddrSTA[numMacAddr][6] = {
{0,0,0,0,0,0}, // No.0
{0x18,0xFE,0x34,0xD5,0xC7,0xA7}, // No.1
{0,0,0,0,0,0},
{0x5C,0xCF,0x7F,0x17,0xB0,0x99}, // No.3
{0x5C,0xCF,0x7F,0x17,0xC0,0xB2}, // No.4
{0x5C,0xCF,0x7F,0x17,0xB6,0x1F}, // No.5
{0x5C,0xCF,0x7F,0x16,0xDE,0x9F}, // No.6
{0x5C,0xCF,0x7F,0xD6,0x50,0xB4}, // No.7
{0x5C,0xCF,0x7F,0xD6,0x4F,0x0D}, // No.8
{0x5C,0xCF,0x7F,0x2C,0x83,0x9E}, // No.9
{0x5C,0xCF,0x7F,0x90,0xB6,0x36}, // No.10
{0xA0,0x20,0xA6,0x0A,0xC8,0xAF}, // No.11
{0xA0,0x20,0xA6,0x0A,0x20,0xC8}, // No.12
{0xEC,0xFA,0xBC,0x83,0x22,0xD9} // No.13
};
uint8_t macAddrAP[numMacAddr][6] = {
{0,0,0,0,0,0}, // No.0
{0x1A,0xFE,0x34,0xD5,0xC7,0xA7}, // No.1
{0,0,0,0,0,0},
{0x5E,0xCF,0x7F,0x17,0xB0,0x99}, // No.3
{0x5E,0xCF,0x7F,0x17,0xC0,0xB2}, // No.4
{0x5E,0xCF,0x7F,0x17,0xB6,0x1F}, // No.5
{0x5E,0xCF,0x7F,0x16,0xDE,0x9F}, // No.6
{0x5E,0xCF,0x7F,0xD6,0x50,0xB4}, // No.7
{0x5E,0xCF,0x7F,0xD6,0x4F,0x0D}, // No.8
{0x5E,0xCF,0x7F,0x2C,0x83,0x9E}, // No.9
{0x5E,0xCF,0x7F,0x90,0xB6,0x36}, // No.10
{0xA2,0x20,0xA6,0x0A,0xC8,0xAF}, // No.11
{0xA2,0x20,0xA6,0x0A,0x20,0xC8}, // No.12
{0xEE,0xFA,0xBC,0x83,0x22,0xD9} // No.13
};
int getIdOfMacAddrSTA(uint8_t *mac) {
for(int id=0; id<numMacAddr; id++){
if( macAddress2String(mac) == macAddress2String(macAddrSTA[id]) )
return id;
}
return -1;
}
int getIdOfMacAddrAP(uint8_t *mac) {
for(int id=0; id<numMacAddr; id++){
if( macAddress2String(mac) == macAddress2String(macAddrAP[id]) )
return id;
}
return -1;
}
String macAddress2String(uint8_t* macaddr) {
#ifdef OLDxxxx
String out = "";
for (int i = 0; i < 6; i++) {
if( macaddr[i] < 8 ) out += "0";
out += String(macaddr[i], HEX);
if (i < 5) out +=":";
}
return out;
#else
char s[18];
sprintf(s,"%02X:%02X:%02X:%02X:%02X:%02X",macaddr[0],macaddr[1],macaddr[2],macaddr[3],macaddr[4],macaddr[5]);
return String(s);
#endif
}
/*
uint8_t *macAddr2Arr(String mac) {
static uint8_t m[6];
m[0] = mac.substring(0,1).toInt();
m[1] = mac.substring(3,4).toInt();
m[2] = mac.substring(6,7).toInt();
m[3] = mac.substring(9,10).toInt();
m[4] = mac.substring(12,13).toInt();
m[5] = mac.substring(15,16).toInt();
return m;
}
*/
// get device id (mac id) of this device
int getDeviceId() {
uint8_t mac[4];
WiFi.macAddress(mac); // can work even when WiFi not connected
return getIdOfMacAddrSTA(mac);
}
String macId2DeviceName(int macId) {
return String("espnow")+(macId==5?5:3);
}
#endif // MYLIB_ESP8266
// **** Utils *************************************************************************************
#ifdef MYLIB_ESP8266
void ESP_restart() {
jsonConfig.save();
SPIFFS.end();
ESP.restart();
}
void ESP_deepSleep(uint32_t time_us, RFMode mode) {
jsonConfig.save();
SPIFFS.end();
ESP.deepSleep(time_us, mode);
}
#endif
// **** RTC User memory (ESP8266) **********************************************************
#ifdef MYLIB_ESP8266
bool ESP_rtcUserMemoryWrite(String text) {
char buf[512];
if( text.length() + 1 > 512 ) {
DebugOut.println("Error: too long string to save RTC memory.");
return false;
}
text.toCharArray(buf, 512); // toCharArray added 0 at the end of string
return ESP.rtcUserMemoryWrite(0, (uint32_t *)buf, 512);
}
String ESP_rtcUserMemoryRead() {
uint32_t buf[512/4];
char *str = (char *)buf;
if( ! ESP.rtcUserMemoryRead(0, buf, 512) )
return String("");
// check null existence
for(int i=0; i<512; i++) {
if( str[i] == 0 )
return String(str);
}
return String(""); // not a string
}
#endif
// **** DDNS *************************************************************************************
#ifdef MYLIB_ESP8266
void updateDDNS(){
//String addr = "http://dynupdate.no-ip.com/nic/update?hostname=sdkn104.hopto.org";
// http://sdkn104:gorosan@dynupdate.no-ip.com/nic/update?hostname=sdkn104.hopto.org
HTTPClient http;
http.begin("http://dynupdate.no-ip.com/nic/update?hostname=sdkn104.hopto.org");
http.setAuthorization(PRIVATE_DDNS_ID, PRIVATE_DDNS_PASS);
int httpCode = http.GET();
// httpCode will be negative on error
if(httpCode > 0) {
// HTTP header has been send and Server response header has been handled
DebugOut.println(String("connected to DDNS. Status code: ")+ httpCode);
} else {
DebugOut.println(String("failed to connect to DDNS, error: ")+ http.errorToString(httpCode).c_str());
}
http.end();
#if 0
WiFiClient client;
if (client.connect("dynupdate.no-ip.com", 80)) {
DebugOut.println("connected to DDNS");
String s = "GET /nic/update?hostname=sdkn104.hopto.org HTTP/1.1\r\n";
client.print(s);
client.print("Host: dynupdate.no-ip.com\r\n");
client.print("Connection: close\r\n");
client.print("Accept: */*\r\n");
client.print("User-Agent: Mozilla/4.0 (compatible; esp8266 Lua; Windows NT 5.1)\r\n");
client.print("\r\n");
DebugOut.println("Request has sent to DDNS");
}
#endif
}
#endif
// ***** URL Encode ******************************************************************************
String URLEncode(String smsg) {
const char *hex = "0123456789abcdef";
const char *msg = smsg.c_str();
String encodedMsg = "";
while (*msg!='\0'){
if( ('a' <= *msg && *msg <= 'z')
|| ('A' <= *msg && *msg <= 'Z')
|| ('0' <= *msg && *msg <= '9') ) {
encodedMsg += *msg;
} else {
encodedMsg += '%';
encodedMsg += hex[*msg >> 4];
encodedMsg += hex[*msg & 15];
}
msg++;
}
//DebugOut.println(encodedMsg);
return encodedMsg;
}
//***** Get Status ***********************************************************************
String thisSketch;
String setThisSketch(const char *src, const char *date, const char *time){
String the_path = src;
int slash_loc = the_path.lastIndexOf('\\');
String out = the_path.substring(slash_loc+1);
thisSketch = out + " (compiled on: " + date + " at " + time + ")";
return thisSketch;
}
String getThisSketch(){
return thisSketch;
}
#ifdef MYLIB_ESP8266
String getSystemInfo() {
String o = String("");
o += "**** system info *******\r\n";
o += "getSdkVersion: " + String(ESP.getSdkVersion());
o += "\r\ngetBootVersion: " + String(ESP.getBootVersion());
o += "\r\nChipID: ";
o += ESP.getChipId();
o += "\r\nFlashChipID: 0x";
o += ESP.getFlashChipId(), HEX;
o += "\r\nFlashChipSpeed[Hz]: ";
o += ESP.getFlashChipSpeed();
o += "\r\nFlashChipMode: ";
o += ESP.getFlashChipMode();
o += "=";
FlashMode_t ideMode = ESP.getFlashChipMode();
o += (ideMode == FM_QIO ? "QIO" : ideMode == FM_QOUT ? "QOUT" : ideMode == FM_DIO ? "DIO" : ideMode == FM_DOUT ? "DOUT" : "UNKNOWN");
o += "\r\nFlashChipSize[byte]: ";
o += ESP.getFlashChipSize();
o += "\r\nFlashChipRealSize[byte]: ";
o += ESP.getFlashChipRealSize();
o += "\r\nSketch size: ";
o += ESP.getSketchSize();
o += "\r\nFree Sketch Size: ";
o += ESP.getFreeSketchSpace();
o += "\r\nFreeHeap[byte]: ";
o += ESP.getFreeHeap();
o += "\r\nWiFi Mode: ";
o += WiFi.getMode();
o += "\r\nMAC Address for STA: ";
o += WiFi.macAddress();
o += "\r\nMAC Address for AP: ";
o += WiFi.softAPmacAddress();
o += "\r\nlocal IP for STA: ";
o += WiFi.localIP().toString();
o += "\r\nlocal IP for AP: ";
o += String(WiFi.softAPIP());
o += "\r\nReset Reason: " + String(ESP.getResetReason());
o += "\r\ngetResetInfo: " + String(ESP.getResetInfo());
o += "\r\nBoot mode: " + String(ESP.getBootMode());
o += "\r\nESP start time: " + getDateTime(getNow()-millis()/1000) + ", " + millis()/1000/60/60 + " hours ago";
String t = wifi_get_sleep_type()==NONE_SLEEP_T ? "NONE" : wifi_get_sleep_type()==MODEM_SLEEP_T ? "MODEM" : wifi_get_sleep_type()==LIGHT_SLEEP_T ? "LIGHT" : "OTHER";
o += "\r\nSleep mode: " + t;
o += "\r\n***********************\r\n";
return o;
}
void printSystemInfo() {
DebugOut.print(getSystemInfo());
}
String getFSInfo() {
FSInfo fs_info;
if( !SPIFFS.info(fs_info) ) { DebugOut.println("Error: fail to get info"); }
String o = String("");
o += "**** file system info *******\r\n";
o += "totalBytes: ";
o += fs_info.totalBytes;
o += "\r\nusedBytes: ";
o += fs_info.usedBytes;
o += "\r\nblockSize: ";
o += fs_info.blockSize;
o += "\r\npageSize: ";
o += fs_info.pageSize;
o += "\r\nmaxOpenFiles: ";
o += fs_info.maxOpenFiles;
o += "\r\nmaxPathLength: ";
o += fs_info.maxPathLength;
o += "\r\n***********************\r\n";
return o;
}
String getStatus() {
String o = String();
o += String("analogRead(A0): ") + analogRead(A0)
+ String("\r\ngetVcc: ") + ESP.getVcc() + " " + ESP.getVcc()/1024.0 + "V -- valid only if TOUT pin is open and ADC_MODE(ADC_VCC) called"
+ "\r\ndigitalRead(0): " + String(digitalRead(0))
+ "\r\ncurrent time: " + getDateTimeNow();
return o;
}
#endif
// ***** Interval Timer ********************************************************************************
CheckInterval::CheckInterval() : CheckInterval(1000, 0) {}
CheckInterval::CheckInterval(unsigned long interval) : CheckInterval(interval, 0) {}
CheckInterval::CheckInterval(unsigned long interval, int timeSrc) {
_timeSrc = timeSrc;
_interval = interval;
_prev = -1; // fire also at the first time
DebugOut.print("init interval ");
DebugOut.println(interval);
}
unsigned long CheckInterval::getTime() {
if( _timeSrc == 0 ) return millis(); // [msec]
else return now()*1000; // [msec], TimeLib.h
}
bool CheckInterval::check() {
//DebugOut.println(String("check interval; ")+getTime()+" "+_prev+" "+_interval);
unsigned long c = getTime() / _interval;
if( c != _prev ) {
_prev = c;
return true;
}
return false;
}
void CheckInterval::set(unsigned long interval) {
_interval = interval;
}
// **** Time Utility ***************************************************************
// return current Unix Time (seconds from Unix Epoch 1970/1/1 0:00 GMT(UTC))
time_t getNow() {
return now(); // based on Time.h
}
// unix time to local time (JST) string
String getDateTime(time_t tm){
char s[20];
const char* format = "%04d-%02d-%02d %02d:%02d:%02d";
time_t t = tm + 9*60*60; // JST
sprintf(s, format, year(t), month(t), day(t), hour(t), minute(t), second(t));
return String(s) + " JST";
}
// unix time to UTC string in ISO format
String getDateTimeISOUTC(time_t tm){
char s[20];
const char* format = "%04d-%02d-%02dT%02d:%02d:%02dZ";
time_t t = tm; // UTC
sprintf(s, format, year(t), month(t), day(t), hour(t), minute(t), second(t));
return String(s);
}
String getDateTimeNow(){
return getDateTime(getNow());
}
// converts time components to time_t (number of seconds from 1970/1/1 0:00, not accounting leap seconds)
// note: Unix Time also does not account leap seconds by definition
// note: year argument is full four digit year (or digits since 2000), i.e.1975, (year 8 is 2008)
// month argument = the month number - 1 (0,1,2,...,11)
// * copy from DateTime.h by T.Sadakane
#define LEAP_YEAR(_year) ((_year%4)==0)
static byte monthDays[]={31,28,31,30,31,30,31,31,30,31,30,31};
time_t makeTime(byte sec, byte min, byte hour, byte day, byte month, int year ){
int i;
time_t seconds;
if(year < 69)
year+= 2000;
// seconds from 1970 till 1 jan 00:00:00 this year
seconds= (year-1970)*(60*60*24L*365);
// add extra days for leap years
for (i=1970; i<year; i++) {
if (LEAP_YEAR(i)) {
seconds+= 60*60*24L;
}
}
// add days for this year
for (i=0; i<month; i++) {
if (i==1 && LEAP_YEAR(year)) {
seconds+= 60*60*24L*29;
} else {
seconds+= 60*60*24L*monthDays[i];
}
}
seconds+= (day-1)*3600*24L;
seconds+= hour*3600L;
seconds+= min*60L;
seconds+= sec;
return seconds;
}
// *************** WiFi Connect *************************************************
#ifdef MYLIB_ESP8266
bool WiFiConnect() {
return WiFiConnect(0);
}
bool WiFiConnect(int id) {
const char* ssid = PRIVATE_WIFI_SSID;
const char* password = PRIVATE_WIFI_PASS; // wifi password
return WiFiConnect(ssid, password, id);
}
bool WiFiConnect(const char *ssid, const char *password) {
return WiFiConnect(ssid, password, 0);
}
bool WiFiConnect(const char *ssid, const char *password, int id) {
DebugOut.print("connecting to WiFi ");
WiFi.mode(WIFI_STA); // default: WIFI_AP_STA, or load from flash (persistent function)
WiFi.begin(ssid, password);
if( id == 0 ) { // try auto detect of id
uint8_t mac[6];
WiFi.macAddress(mac);
id =getIdOfMacAddrSTA(mac);
if( id < 0 ) { id = 0; }
}
if( id > 0 ) { // static IP address
IPAddress staticIP(192,168,1,100+id);
IPAddress gateway(192,168,1,1);
IPAddress subnet(255,255,255,0);
WiFi.config(staticIP, gateway, subnet);
}
while (WiFi.status() != WL_CONNECTED) {
delay(500);
DebugOut.print(".");
}
DebugOut.println(" connected");
DebugOut.print("local IP: ");
DebugOut.println(WiFi.localIP().toString());
return true;
}
#endif
//**** FTP Client *******************************************************
#ifdef MYLIB_ESP8266
/*
FTP passive client
*/
FTPClient::FTPClient() {}
FTPClient::~FTPClient() {
DebugOut.println("FTP client stop");
_cclient.stop();
_dclient.stop();
}
int FTPClient::open(String server, String user, String pass) {
_serverIP = server;
if (_cclient.connect(_serverIP.c_str(),21)) {
DebugOut.println(F("connected to FTP server"));
} else {
DebugOut.println(F("failed to connect to FTP server"));
return 0;
}
if( getReply() > "220") { _cclient.stop(); return 0; }
sendCmd(String(F("USER "))+user);
if( getReply() > "331") return 0;
sendCmd(String(F("PASS "))+pass);
if( getReply() > "230") return 0;
sendCmd(F("SYST"));
if( getReply() > "215") return 0;
sendCmd(F("Type I"));
if( getReply() > "200") return 0;
return 1;
}
int FTPClient::get(String fileName) {
sendCmd(F("PASV"));
if( getReply() > "227") return 0;
unsigned int port = getPortFromPASVReply(reply);
if (_dclient.connect(_serverIP.c_str(),port)) {
DebugOut.print(F("connected to Data port " ));
DebugOut.println(port);
} else {
DebugOut.print(F("failed to connect to Data port "));
DebugOut.println(port);
return 0;
}
fileName.trim();
if( fileName.startsWith("/") ) fileName = fileName.substring(1);
sendCmd(String(F("RETR ")) + fileName);
if( getReply() > "226") return 0;
if( !SPIFFS.begin() ) DebugOut.println("Error: fail to mount SPIFFS"); // it is safe to duplicate call this
File f = SPIFFS.open(String("/")+fileName, "w");
if (!f) {
DebugOut.println("file open failed");
return 0;
}
while(_dclient.connected()) {
while(_dclient.available()) {
char c = _dclient.read(); // TODO: buffering?
f.write(c);
delay(0);
}
}
f.close();
_dclient.stop();
DebugOut.println(F("disconnected to Data port"));
if( getReply() > "226") return 0; // server reply after it disconnect (to show EOF)
return 1;
}
int FTPClient::put(String fileName) {
return put_internal(fileName, "STOR");
}
int FTPClient::append(String fileName) {
return put_internal(fileName, "APPE");
}
int FTPClient::put_internal(String fileName, String cmd) {
sendCmd(F("PASV"));
if( getReply() > "227") return 0;
unsigned int port = getPortFromPASVReply(reply);
if (_dclient.connect(_serverIP.c_str(),port)) {
DebugOut.print(F("connected to Data port " ));
DebugOut.println(port);
} else {
DebugOut.print(F("failed to connect to Data port "));
DebugOut.println(port);
return 0;
}
fileName.trim();
if( fileName.startsWith("/") ) fileName = fileName.substring(1);
sendCmd(String(cmd) + " " + fileName);
if( getReply() > "226") return 0;
if( !SPIFFS.begin() ) DebugOut.println("Error: fail to mount SPIFFS");
File f = SPIFFS.open(String("/")+fileName, "r");
if (!f) {
DebugOut.println("file open failed");
return 0;
}
while(f.available()) {
uint8_t c = f.read(); // TODO: buffering?
_dclient.write(c);
delay(0);
}
f.close();
_dclient.stop(); // close connection to send EOF
DebugOut.println(F("disconnected to Data port"));
if( getReply() > "226") return 0;
return 1;
}
int FTPClient::getPortFromPASVReply(String reply) {
char sarr[128];
reply.toCharArray(sarr,128);
char *tStr = strtok(sarr,"(,");
int array_pasv[6];
for ( int i = 0; i < 6; i++) {
tStr = strtok(NULL,"(,");
array_pasv[i] = atoi(tStr);
if(tStr == NULL) {
DebugOut.println(F("Bad PASV Answer"));
}
}
unsigned int hiPort = array_pasv[4] << 8;
unsigned int loPort = array_pasv[5] & 255;
hiPort = hiPort | loPort;
return (int)hiPort;
}
int FTPClient::bye() {
sendCmd(F("QUIT"));
if( getReply() > "221") return 0;
_cclient.stop();
DebugOut.println(F("disconnected to FTP server"));
return 1;
}
int FTPClient::pwd() {
sendCmd(F("XPWD"));
if( getReply() != "257") return 0;
return 1;
}
int FTPClient::cd(String dirName) {
dirName.trim();
sendCmd(String(F("CWD ")) + dirName);
if( getReply() > "250") return 0;
return 1;
}
int FTPClient::ls() {
sendCmd(F("PASV"));
if( getReply() > "227") return 0;
unsigned int port = getPortFromPASVReply(reply);
if (_dclient.connect(_serverIP.c_str(),port)) {
DebugOut.print(F("connected to Data port " ));
DebugOut.println(port);
} else {
DebugOut.print(F("failed to connect to Data port "));
DebugOut.println(port);
return 0;
}
sendCmd(F("LIST"));
if( getReply() >= "200") return 0;
while(_dclient.connected()) {
while(_dclient.available()) {
char c = _dclient.read(); // TODO: buffering?
char s[2] = { 0, 0};
s[0] = c;
DebugOut.print(s);
delay(0);
}
}
_dclient.stop(); // close connection to send EOF
DebugOut.println(F("disconnected to Data port"));
if( getReply() >= "200") return 0;
return 1;
}
String FTPClient::getReply() {
_cclient.setTimeout(1000); // in msec
String buf = _cclient.readStringUntil('\n'); // TODO: multiple line reply
DebugOut.println(buf);
reply = buf;
return buf.substring(0,3);
}
void FTPClient::sendCmd(String cmd){
_cclient.println(cmd);
DebugOut.print("---> ");
DebugOut.println(cmd);
}
#endif
//***** File *****************************************************************
#ifdef MYLIB_ESP8266
bool fileCreate(const char *path) {
File file = SPIFFS.open(path, "w");
if(!file) {
DebugOut.println("Error: fail to open file");
return false;
}
file.close();
return true;
}
bool fileDelete(const char *path) {
if( ! SPIFFS.exists(path) )
return true;
else {
bool res = SPIFFS.remove(path);
if( !res ) DebugOut.println("Error: fail to remove file");
return res;
}
}
String fileReadAll(const char *path) {
if(path == "/") {
DebugOut.println("ERROR: cannot read. bad path.");
return "";
}
if(!SPIFFS.exists(path)){
DebugOut.println("ERROR: cannot read. file not found.");
return "";
}
File file = SPIFFS.open(path, "r");
if(!file) {
DebugOut.println("ERROR: cannot read. open fail.");
return "";
}
String out = "";
while (file.available()) {
int t = file.read();
if( t == -1 ) break;
out += String((char)t);
}
file.close();
return out;
}
bool fileCopy(const char *path1, const char *path2) {
if(path1 == "/" || path2 == "/") {
DebugOut.println("ERROR: cannot copy. bad path.");
return false;
}
if(!SPIFFS.exists(path1)){
DebugOut.println("ERROR: cannot copy. file not found.");
return false;
}
if(SPIFFS.exists(path2)){
DebugOut.println("ERROR: cannot copy. file exists.");
return false;
}
File file1 = SPIFFS.open(path1, "r");
if(!file1) {
DebugOut.println("ERROR: cannot copy. open fail.");
return false;
}
File file2 = SPIFFS.open(path2, "w");
if(!file2) {
file1.close();
DebugOut.println("ERROR: cannot copy. open fail.");
return false;
}
while (file1.available()) {
int t = file1.read();
if( t == -1 ) break;
file2.write(t);
}
file1.close();
file2.close();
return true;
}
bool fileAppend(const char *path, const char *contents) {
if(path == "/") {
DebugOut.println("ERROR: bad path.");
return false;
}
File file = SPIFFS.open(path, "a");
if(!file) {
DebugOut.println("ERROR: open fail.");
return false;
}
file.print(contents);
file.close();
return true;
}
long fileSize(const char *path) {
long sz = 0;
File file = SPIFFS.open(path, "r");
if (file) {
sz = file.size();
file.close();
} else {
DebugOut.println("Error: cannot open file.");
}
return sz;
}
String jsonFileList(const char *path) {
Dir dir = SPIFFS.openDir(path);
String output = "[";
while(dir.next()){
File entry = dir.openFile("r");
if (output != "[") output += ',';
bool isDir = false;
output += "{\"type\":\"";
output += (isDir)?"dir":"file";
output += "\",\"name\":\"";
output += String(entry.name());
output += "\",\"size\":";
output += String(entry.size());
output += "}";
entry.close();
}
output += "]";
return output;
}
#endif
//***** LogFile ****************************************************************
// !!!! DONT USE DebugOut in LogFile Class, to avoid recursive loop
LogFile::LogFile(String fileName, int maxFileSize){
set(fileName, maxFileSize);
}
LogFile::LogFile(String fileName){
set(fileName);
}
void LogFile::set(String fileName, int maxFileSize){
_fileName = fileName;
_maxSize = maxFileSize;
}
void LogFile::set(String fileName){
_fileName = fileName;
}
#define PRINTERR(STR) { if( _fileName == DebugOut.FileName() ) Serial.println(STR); else DebugOut.println(STR); }
size_t LogFile::write(uint8_t c) {
#ifdef MYLIB_ARDUINO
Serial.write(c);
#else
if( _size >= _maxSize ) {
String fd = String(_fileName) + "_prev";
if( SPIFFS.exists(fd) ) { if( !SPIFFS.remove(fd) ) PRINTERR("Error: fail to remove file"); }
if( SPIFFS.rename(_fileName.c_str(), fd.c_str()) ) { PRINTERR("Error: fail to rename file"); }
_size = 0;
}
File fs = SPIFFS.open(_fileName, "a");
if(!fs){
PRINTERR(String("ERROR: fail to open file: ")+_fileName);
if( _fileName == DebugOut.FileName() ) {
Serial.println(" call SetToSerial()");
DebugOut.setToSerial(); // to prevent from SPIFFS trouble
}
return 0;
}
if( _size % 100 == 0 ) {
_size = fs.size();
}
fs.print((char)c);
fs.close();
_size++;
return 1;
#endif
}
size_t LogFile::write(const uint8_t *buffer, size_t size) {
for(int i=0; i<size; i++){
write(buffer[i]); // todo: buffering, for flash lifetime
}
return size;
}
//***** DebugOut *****************************************************************
DebugOutClass DebugOut;
size_t DebugOutClass::write(uint8_t c) {
if(_type == 0 ) { return Serial.print((char)c); }
else if( _type == 1 ) { return 0; }
#ifdef MYLIB_ESP8266
else if( _type == 2 ) {
if( !SPIFFS.begin() ) Serial.println("Error: fail to mount SPIFFS");
return _logFile.write(c);
}
#endif
return 0;
}
size_t DebugOutClass::write(const uint8_t *buffer, size_t size) {
for(int i=0; i<size; i++){
write(buffer[i]);
}
return size;
}
//***** IFTTT *****************************************************************
#ifdef MYLIB_ESP8266
void triggerIFTTT(String event, String value1, String value2, String value3){
DebugOut.println("triggerIFTTT: "+event);
String key = PRIVATE_IFTTT_KEY;
String url = String("http://maker.ifttt.com/trigger/")+URLEncode(event)+"/with/key/"+key
+ "?value1=" + URLEncode(value1) + "&value2=" + URLEncode(value2) + "&value3=" + URLEncode(value3)
+ " HTTP/1.1\r\n";
String resp = HttpGet(url.c_str());
DebugOut.println(" response: "+resp);
}
#endif
//***** Ubidots *****************************************************************
#ifdef MYLIB_ESP8266
void triggerUbidots(String device, String json){
String token = PRIVATE_UBIDOTS_TOKEN; // user key
String url = String("http://things.ubidots.com/api/v1.6/devices/")+URLEncode(device)+"/?token="+token;
//DebugOut.println(url+json);
HTTPClient http;
http.begin(url.c_str());
http.addHeader("Content-Type","application/json",false, false);
int httpCode = http.POST(json);
if(httpCode > 0) {
DebugOut.printf("code: %d\n", httpCode);
if(httpCode == HTTP_CODE_OK) {
DebugOut.println(http.getString());
}
} else {
DebugOut.printf("failed, error: %s\n", http.errorToString(httpCode).c_str());
}
http.end();
}
//***** M2X *****************************************************************
void triggerM2X(String device, String stream, String json){
String token = "986af386e86d7e7de57e3bd3d28d79c4"; //PRIVATE_UBIDOTS_TOKEN; // master user key
String deviceID = device == "espnow3" ? "2a88b48ac300692cc51fa8fc9fb61574" :
device == "espnow5" ? "32ac4bbc890c28cff300c27320e5f956" :
device == "basic" ? "680e9954ce06e550afe900116f3e264d" : "";
String url = "http://api-m2x.att.com/v2/devices/"+deviceID+"/streams/"+stream+"/value";
// String url = "http://api-m2x.att.com/v2/devices/"+deviceID;
DebugOut.println(String("triggerM2X:")+url+json);
HTTPClient http;
http.begin(url.c_str());
http.addHeader("Content-Type","application/json",false, false);
http.addHeader("X-M2X-KEY",token,false, false);
//int httpCode = http.PUT(json); // not available yet in arduino/esp8266 2.3.0
int httpCode = http.sendRequest("PUT",json);
//int httpCode = http.GET();
if(httpCode > 0) {
DebugOut.printf(" code: %d\n", httpCode);
if(httpCode == HTTP_CODE_OK) {
DebugOut.println(http.getString());
}
} else {
DebugOut.printf(" failed, error: %s\n", http.errorToString(httpCode).c_str());
}
http.end();
}
//***** BigQuery *****************************************************************
int triggerBigQuery(String table, String value1, String value2, String value3, String value4){
//String url = String("http://192.168.1.203/cgi-bin/bqInsertRcvTable.py?table=")+ URLEncode(table)
// + "&value1=" + URLEncode(value1)+"&value2="+URLEncode(value2) + "&value3=" + URLEncode(value3)
// + "&value4=" + URLEncode(value4);
String url = String("http://")+PRIVATE_GCP_PROJECT_ID+".appspot.com/"+PRIVATE_GCP_PROJECT_APP
+"/insertBQ?table="+ URLEncode(table)
+ "&value1=" + URLEncode(value1)+"&value2="+URLEncode(value2) + "&value3=" + URLEncode(value3)
+ "&value4=" + URLEncode(value4);
DebugOut.println(String("triggerBigQuery:")+url);
int code;
String resp = HttpGet(url.c_str(), &code);
DebugOut.println(String(" response: ")+resp);
DebugOut.println(String(" status code: ")+code);
return code;