forked from gemi254/ESP32-CAM_MJPEG2SD
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ftp.cpp
364 lines (326 loc) · 10.6 KB
/
ftp.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
#include "Arduino.h"
#include <WiFi.h>
#include <WiFiClient.h>
#include <WiFiUdp.h>
#include "FS.h" // SD Card ESP32
#include "SD_MMC.h"
#include <vector> // Dynamic string array
#include <regex>
#include "esp_log.h"
static const char* TAG = "ftp";
//Defined in custom config file myConfig.h
extern char ftp_server[];
extern char ftp_user[];
extern char ftp_port[];
extern char ftp_pass[];
extern char ftp_wd[];
//FTP buffers
char rspBuf[255]; //Ftp response buffer
char rspCount;
#define BUFF_EXT 100
#define BUFF_SIZE (32 * 1024)+BUFF_EXT // Upload data buffer size
#define RESPONSE_TIMEOUT 10000
unsigned int hiPort; //Data connection port
static File root;
//WiFi Clients
WiFiClient client;
WiFiClient dclient;
extern bool doPlayback;
bool isAVI(File &fh);
size_t readClientBuf(File &fh, byte* &clientBuf, size_t buffSize);
size_t isSubArray(uint8_t* haystack, uint8_t* needle, size_t hSize, size_t nSize);
void efail(){
byte thisByte = 0;
client.println(F("QUIT"));
unsigned long start = millis();
while (!client.available() && millis() < start + RESPONSE_TIMEOUT) delay(1);
while (client.available()) {
thisByte = client.read();
Serial.write(thisByte);
}
client.stop();
ESP_LOGI(TAG, "Ftp command disconnected");
}
byte eRcv(bool bFail=true){
byte respCode;
byte thisByte;
unsigned long start = millis();
while (!client.available() && millis() < start + RESPONSE_TIMEOUT) delay(1);
respCode = client.peek();
rspCount = 0;
while (client.available()) {
thisByte = client.read();
if (rspCount < sizeof(rspBuf)) { // if (rspCount < 127) {
rspBuf[rspCount] = thisByte;
rspCount++;
rspBuf[rspCount] = 0;
}
}
//Skip line feed at end
rspBuf[rspCount-1]=0;
ESP_LOGI(TAG, "Ftp resp: %s",rspBuf);
if (respCode >= '4' || respCode >= '5' ) {
if(bFail) efail();
return 0;
}
return 1;
}
//Connect to ftp and change to root dir
bool ftpConnect(){
//Connect
if (client.connect(ftp_server, String(ftp_port).toInt()) ) {
ESP_LOGI(TAG, "Ftp command connected at %s:%s", ftp_server,ftp_port);
} else {
ESP_LOGE(TAG, "Error opening ftp connection to %s:%s\n", ftp_server, ftp_port);
return 0;
}
if (!eRcv()) return 0;
client.print("USER ");
client.println(ftp_user);
if (!eRcv()) return 0;
//ESP_LOGV(TAG, "Ftp pass:%s", ftp_pass);
client.print("PASS ");
client.println(ftp_pass);
if (!eRcv()) return 0;
client.println("SYST");
if (!eRcv()) return 0;
client.println("Type I");
if (!eRcv()) return 0;
client.println("PASV");
if (!eRcv()) return 0;
char *tStr = strtok(rspBuf, "(,");
int array_pasv[6];
for ( int i = 0; i < 6; i++) {
tStr = strtok(NULL, "(,");
array_pasv[i] = atoi(tStr);
if (tStr == NULL)
{
ESP_LOGE(TAG, "Bad PASV Answer");
return 0;
}
}
unsigned int loPort;
hiPort = array_pasv[4] << 8;
loPort = array_pasv[5] & 255;
//if(dbg) Serial.print(F("Data port: "));
hiPort = hiPort | loPort;
ESP_LOGI(TAG, "Data port: %i",hiPort);
ESP_LOGI(TAG, "Change to root dir: %s", ftp_wd);
client.print("CWD ");
client.println(ftp_wd);
if (!eRcv()){
dclient.stop();
return 0;
}
return 1;
}
//Properly disconnect from ftp
byte ftpDisconnect(){
client.println("QUIT");
bool retVal = eRcv() ? 1 : 0;
root.close();
dclient.stop();
client.stop();
if (retVal) ESP_LOGI(TAG, "Ftp command disconnected");
return retVal;
}
//Check if it is to create remote directory and change to this dir
bool ftpCheckDirPath(String filePath, String &fileName){
int lv=0;
std::vector<String> dirPaths; // declare dir tree paths
for (char* token = strtok((char *)filePath.c_str(), "/"); token; token = strtok(NULL, "/")){
dirPaths.push_back(token);
lv++;
}
//Create sub dirs
for(int i=lv-2; i>=0; --i){
ESP_LOGI(TAG, "Searching for sub dir[%i]: %s",i,dirPaths[i].c_str() );
client.print("CWD ");
client.println(dirPaths[i].c_str());
eRcv(false); //Don't stop if dir not exists
//Create dir if not exists
char *tStr = strtok(rspBuf, " ");
//Serial.printf("Res: %s\n",tStr);
if(strcmp(tStr,"550")==0){
ESP_LOGI(TAG, "Create dir: %s", dirPaths[i].c_str());
client.print("MKD ");
client.println(dirPaths[i].c_str());
if (!eRcv()){
client.stop();
return 0;
}
//Change to new dir
ESP_LOGI(TAG, "Change to dir: %s", dirPaths[i].c_str());
client.print("CWD ");
client.println(dirPaths[i].c_str());
if (!eRcv()){
client.stop();
return 0;
}
}
}
//Store filename without path
fileName = dirPaths[lv-1];
return 1;
}
//Store sdfile to current ftp dir
bool ftpStoreFile(String file, File &fh){
uint32_t fileSize = fh.size();
// determine if file is suitable for conversion to AVI
std::string sfile(file.c_str());
if (isAVI(fh)) {
sfile = std::regex_replace(sfile, std::regex("mjpeg"), "avi");
file = String(sfile.data());
ESP_LOGI(TAG, "Ftp store renamed file: %s size: %0.1fMB", file.c_str(),(float)(fileSize/(1024*1024)));
}else{
ESP_LOGI(TAG, "Ftp store file: %s size: %0.1fMB", file.c_str(),(float)(fileSize/(1024*1024)));
}
//Connect to data port
if (dclient.connect(ftp_server, hiPort)) {
ESP_LOGI(TAG, "Ftp data connected");
} else{
ESP_LOGE(TAG, "Ftp data connection failed");
return 0;
}
client.print("STOR ");
client.println(file);
if (!eRcv()){
dclient.stop();
return 0;
}
ESP_LOGI(TAG, "Uploading..");
//byte clientBuf[BUFF_SIZE];
byte *clientBuf = (byte*)ps_malloc(BUFF_SIZE * sizeof(byte));
if(clientBuf==NULL){
ESP_LOGE(TAG, "Memory allocation failed ..");
dclient.stop();
return 0;
}
unsigned int buffCount=0;
uint32_t writeBytes=0;
unsigned long uploadStart = millis();
size_t readLen, writeLen = 0;
do {
readLen = readClientBuf(fh, clientBuf, BUFF_SIZE-BUFF_EXT); // obtain modified data to send
if(readLen) writeLen = dclient.write((const uint8_t *)clientBuf, readLen);
if(readLen>0 && writeLen==0){
ESP_LOGE(TAG, "Write buffer failed ..");
dclient.stop();
return 0;
}
writeBytes += writeLen;
if(buffCount%5==0){
ESP_LOGI(TAG, "Uploaded %0.0f%%", ( (double)writeBytes / fileSize)*100.0f );
}
++buffCount;
} while (readLen);
if(readLen<BUFF_SIZE) ESP_LOGI(TAG, "Uploaded 100%%");
float uploadDur = (millis() - uploadStart)/1024;
free(clientBuf);
ESP_LOGI(TAG, "Done Uploaded in %3.1f sec",uploadDur);
dclient.stop();
return 1;
}
//Upload a single file or whole directory to ftp
void uploadFolderOrFileFtp(String sdName, const bool removeAfterUpload, uint8_t levels){
ESP_LOGI(TAG, "Ftp upload name: %s", sdName.c_str());
if(sdName=="" || sdName=="/"){
ESP_LOGE(TAG, "Root or null is not allowed %s",sdName.c_str());
return;
}
String ftpName = "";
//Ftp connect
if(!ftpConnect()){
return;
}
root = SD_MMC.open(sdName);
if (!root) {
ESP_LOGE(TAG, "Failed to open: %s", sdName.c_str());
ftpDisconnect();
return;
}
if (!root.isDirectory()) { //Upload a single file
ESP_LOGI(TAG, "Uploading file: %s", sdName.c_str());
if(!ftpCheckDirPath(sdName, ftpName)){
ESP_LOGE(TAG, "Create ftp dir path %s failed", sdName.c_str());
ftpDisconnect();
return;
}
if(!ftpStoreFile(ftpName, root)){
ESP_LOGE(TAG, "Store file %s to ftp failed", ftpName.c_str());
ftpDisconnect();
return;
}
root.close();
ESP_LOGV(TAG, "File closed");
if(removeAfterUpload){
ESP_LOGI(TAG, "Removing file %s", sdName.c_str());
SD_MMC.remove(sdName.c_str());
}
}else{ //Upload a whole directory
ESP_LOGI(TAG, "Uploading directory: %s", sdName.c_str());
File fh = root.openNextFile();
sdName = fh.name();
if(!ftpCheckDirPath(sdName, ftpName)){
ESP_LOGE(TAG, "Create ftp dir path %s failed", sdName.c_str());
ftpDisconnect();
return;
}
bool bUploadOK=false;
while (fh) {
sdName = fh.name();
bUploadOK = false;
if (fh.isDirectory()) {
ESP_LOGI(TAG, "Sub directory: %s, Not uploading", sdName.c_str());
/*if (levels) {
std::string strfile(file.name());
const char* f="TEST";
doUploadFtp(f, removeAfterUpload, levels – 1);
}*/
} else {
byte bPos = sdName.lastIndexOf(".");
if (sdName.substring(bPos+1) == "mjpeg") {
bPos = sdName.lastIndexOf("/");
String ftpName = sdName.substring(bPos+1);
ESP_LOGI(TAG, "Uploading sub sd file %s to %s", sdName.c_str(),ftpName.c_str());
bUploadOK = ftpStoreFile(ftpName, fh);
if(!bUploadOK){
ESP_LOGE(TAG, "Store file %s to ftp failed", ftpName.c_str());
}
}
}
//Remove if ok
if(removeAfterUpload && bUploadOK){
ESP_LOGI(TAG, "Removing file %s\n", sdName.c_str());
SD_MMC.remove(sdName.c_str());
}
fh = root.openNextFile();
}
}
//Disconnect from ftp
ftpDisconnect();
}
static bool removeAfterUpload=false; //Delete file if successfully uploaded
static void taskUpload(void * parameter){
// prevent SD access by other tasks
String fname((char*) parameter);
delay(1000); // allow other tasks to finish off
ESP_LOGV(TAG, "Entering upload task fname: %s\n",fname.c_str());
uploadFolderOrFileFtp(fname, removeAfterUpload, 0);
ESP_LOGV(TAG, "Ending uploadTask");
vTaskDelete( NULL );
}
void createUploadTask(const char* val, bool move=false){
doPlayback = false;
static char fname[100];
strcpy(fname, val); // else wont persist
removeAfterUpload = move;
ESP_LOGV(TAG, "Starting upload task with val: %s and delete on upload %i\n",val,removeAfterUpload);
xTaskCreate(
&taskUpload, /* Task function. */
"taskUpload", /* String with name of task. */
4096*2, /* Stack size in bytes. */
(void *)fname, /* Parameter passed as input of the task */
1, /* Priority of the task. */
NULL); /* Task handle. */
}