-
Notifications
You must be signed in to change notification settings - Fork 4.9k
Expand file tree
/
Copy pathMavLinkFtpClientImpl.cpp
More file actions
824 lines (755 loc) · 26.8 KB
/
MavLinkFtpClientImpl.cpp
File metadata and controls
824 lines (755 loc) · 26.8 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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#include "MavLinkFtpClientImpl.hpp"
#if defined(_WIN32)
#include <Windows.h>
#define AIRSIM_SLEEP_MS(ms) ::Sleep((DWORD)(ms))
#else
#include <thread>
#include <chrono>
#define AIRSIM_SLEEP_MS(ms) std::this_thread::sleep_for(std::chrono::milliseconds(ms))
#endif
#include <mutex>
#include "Utils.hpp"
#include "FileSystem.hpp"
#include <sys/stat.h>
using namespace mavlink_utils;
using namespace mavlinkcom;
using namespace mavlinkcom_impl;
using milliseconds = std::chrono::milliseconds;
#define MAXIMUM_ROUND_TRIP_TIME 200 // 200 milliseconds should be plenty of time for single round trip to remote node.
#define TIMEOUT_INTERVAL 10 // 10 * MAXIMUM_ROUND_TRIP_TIME means we have a problem.
// These definitions are copied from PX4 implementation
/// @brief This is the payload which is in mavlink_file_transfer_protocol_t.payload. We pad the structure ourselves to
/// 32 bit alignment to avoid usage of any pack pragmas.
struct FtpPayload
{
uint16_t seq_number; ///< sequence number for message
uint8_t session; ///< Session id for read and write commands
uint8_t opcode; ///< Command opcode
uint8_t size; ///< Size of data
uint8_t req_opcode; ///< Request opcode returned in kRspAck, kRspNak message
uint8_t burst_complete; ///< Only used if req_opcode=kCmdBurstreadFile - 1: set of burst packets complete, 0: More burst packets coming.
uint8_t padding; ///< 32 bit aligment padding
uint32_t offset; ///< Offsets for List and Read commands
uint8_t data; ///< command data, varies by Opcode
};
void setPayloadFilename(FtpPayload* payload, const char* filename)
{
const size_t maxFileName = 251 - sizeof(FtpPayload);
size_t len = strlen(filename);
if (len > maxFileName) {
len = maxFileName;
}
strncpy(reinterpret_cast<char*>(&payload->data), filename, len);
payload->size = static_cast<uint8_t>(len);
}
/// @brief Command opcodes
enum Opcode : uint8_t
{
kCmdNone, ///< ignored, always acked
kCmdTerminateSession, ///< Terminates open Read session
kCmdResetSessions, ///< Terminates all open Read sessions
kCmdListDirectory, ///< List files in <path> from <offset>
kCmdOpenFileRO, ///< Opens file at <path> for reading, returns <session>
kCmdReadFile, ///< Reads <size> bytes from <offset> in <session>
kCmdCreateFile, ///< Creates file at <path> for writing, returns <session>
kCmdWriteFile, ///< Writes <size> bytes to <offset> in <session>
kCmdRemoveFile, ///< Remove file at <path>
kCmdCreateDirectory, ///< Creates directory at <path>
kCmdRemoveDirectory, ///< Removes Directory at <path>, must be empty
kCmdOpenFileWO, ///< Opens file at <path> for writing, returns <session>
kCmdTruncateFile, ///< Truncate file at <path> to <offset> length
kCmdRename, ///< Rename <path1> to <path2>
kCmdCalcFileCRC32, ///< Calculate CRC32 for file at <path>
kCmdBurstreadFile, ///< Burst download session file
kRspAck = 128, ///< Ack response
kRspNak ///< Nak response
};
/// @brief Error codes returned in Nak response PayloadHeader.data[0].
enum ErrorCode : uint8_t
{
kErrNone,
kErrFail, ///< Unknown failure
kErrFailErrno, ///< Command failed, errno sent back in PayloadHeader.data[1]
kErrInvalidDataSize, ///< PayloadHeader.size is invalid
kErrInvalidSession, ///< Session is not currently open
kErrNoSessionsAvailable, ///< All available Sessions in use
kErrEOF, ///< Offset past end of file for List and Read commands
kErrRetriesExhausted,
kErrUnknownCommand ///< Unknown command opcode
};
static const char kDirentFile = 'F'; ///< Identifies File returned from List command
static const char kDirentDir = 'D'; ///< Identifies Directory returned from List command
static const char kDirentSkip = 'S'; ///< Identifies Skipped entry from List command
MavLinkFtpClientImpl::MavLinkFtpClientImpl(int localSystemId, int localComponentId)
: MavLinkNodeImpl(localSystemId, localComponentId)
{
}
MavLinkFtpClientImpl::~MavLinkFtpClientImpl()
{
}
bool MavLinkFtpClientImpl::isSupported()
{
// request capabilities, it will respond with AUTOPILOT_VERSION.
MavLinkAutopilotVersion ver;
assertNotPublishingThread();
if (!getCapabilities().wait(5000, &ver)) {
throw std::runtime_error(Utils::stringf("Five second timeout waiting for response to mavlink command MAV_CMD_REQUEST_AUTOPILOT_CAPABILITIES"));
}
return (ver.capabilities & static_cast<int>(MAV_PROTOCOL_CAPABILITY::MAV_PROTOCOL_CAPABILITY_FTP)) != 0;
}
void MavLinkFtpClientImpl::subscribe()
{
if (subscription_ == 0) {
subscription_ = getConnection()->subscribe([=](std::shared_ptr<MavLinkConnection> connection, const MavLinkMessage& msg) {
unused(connection);
handleResponse(msg);
});
}
}
void MavLinkFtpClientImpl::list(MavLinkFtpProgress& progress, const std::string& remotePath, std::vector<MavLinkFileInfo>& files)
{
if (waiting_) {
cancel();
}
ensureConnection();
progress_ = &progress;
files_ = &files;
command_ = FtpCommandList;
remote_file_ = remotePath;
size_t len = remote_file_.size();
if (len > 1 && remote_file_[len - 1] == '/') {
// must trim trailing slashes so PX4 doesn't hang!
remote_file_ = remote_file_.substr(0, len - 1);
}
file_index_ = 0;
runStateMachine();
progress.complete = true;
files_ = nullptr;
progress_ = nullptr;
}
void MavLinkFtpClientImpl::get(MavLinkFtpProgress& progress, const std::string& remotePath, const std::string& localPath)
{
if (waiting_) {
cancel();
}
ensureConnection();
progress_ = &progress;
command_ = FtpCommandGet;
local_file_ = localPath;
remote_file_ = remotePath;
bytes_read_ = 0;
file_size_ = 0;
remote_file_open_ = false;
runStateMachine();
progress_ = nullptr;
progress.complete = true;
}
void MavLinkFtpClientImpl::put(MavLinkFtpProgress& progress, const std::string& remotePath, const std::string& localPath)
{
local_file_ = localPath;
remote_file_ = remotePath;
if (waiting_) {
cancel();
}
ensureConnection();
progress_ = &progress;
command_ = FtpCommandPut;
if (openSourceFile()) {
remote_file_open_ = false;
runStateMachine();
}
progress_ = nullptr;
progress.complete = true;
}
void MavLinkFtpClientImpl::remove(MavLinkFtpProgress& progress, const std::string& remotePath)
{
remote_file_ = remotePath;
if (waiting_) {
cancel();
}
ensureConnection();
progress_ = &progress;
command_ = FtpCommandRemove;
runStateMachine();
progress_ = nullptr;
progress.complete = true;
}
void MavLinkFtpClientImpl::mkdir(MavLinkFtpProgress& progress, const std::string& remotePath)
{
remote_file_ = remotePath;
if (waiting_) {
cancel();
}
ensureConnection();
progress_ = &progress;
command_ = FtpCommandMkdir;
runStateMachine();
progress_ = nullptr;
progress.complete = true;
}
void MavLinkFtpClientImpl::rmdir(MavLinkFtpProgress& progress, const std::string& remotePath)
{
remote_file_ = remotePath;
if (waiting_) {
cancel();
}
ensureConnection();
progress_ = &progress;
command_ = FtpCommandRmdir;
runStateMachine();
progress_ = nullptr;
progress.complete = true;
}
void MavLinkFtpClientImpl::runStateMachine()
{
waiting_ = true;
retries_ = 0;
total_time_ = milliseconds::zero();
messages_ = 0;
progress_->cancel = false;
progress_->error = 0;
progress_->current = 0;
progress_->goal = 0;
progress_->complete = false;
progress_->longest_delay = 0;
progress_->message_count = 0;
int before = 0;
subscribe();
nextStep();
const int monitorInterval = 30; // milliseconds between monitoring progress.
double rate = 0;
double totalSleep = 0;
while (waiting_) {
std::this_thread::sleep_for(std::chrono::milliseconds(monitorInterval));
totalSleep += monitorInterval;
int after = 0;
{
std::lock_guard<std::mutex> guard(mutex_);
after = messages_;
if (messages_ > 0) {
rate = static_cast<double>(total_time_.count()) / static_cast<double>(messages_);
if (progress_ != nullptr) {
progress_->average_rate = rate;
}
}
}
if (before == after) {
if (totalSleep > (MAXIMUM_ROUND_TRIP_TIME * TIMEOUT_INTERVAL)) {
Utils::log("ftp command timeout, not getting a response, so retrying\n", Utils::kLogLevelWarn);
retry();
totalSleep = 0;
}
}
else {
totalSleep = 0;
}
before = after;
}
waiting_ = false;
}
void MavLinkFtpClientImpl::nextStep()
{
switch (command_) {
case FtpCommandList:
listDirectory();
break;
case FtpCommandGet:
readFile();
break;
case FtpCommandPut:
writeFile();
break;
case FtpCommandRemove:
removeFile();
break;
case FtpCommandMkdir:
mkdir();
break;
case FtpCommandRmdir:
rmdir();
break;
default:
break;
}
}
void MavLinkFtpClientImpl::removeFile()
{
MavLinkFileTransferProtocol ftp;
FtpPayload* payload = reinterpret_cast<FtpPayload*>(&ftp.payload[0]);
ftp.target_component = getTargetComponentId();
ftp.target_system = getTargetSystemId();
payload->opcode = kCmdRemoveFile;
setPayloadFilename(payload, remote_file_.c_str());
sendMessage(ftp);
recordMessageSent();
}
void MavLinkFtpClientImpl::mkdir()
{
MavLinkFileTransferProtocol ftp;
FtpPayload* payload = reinterpret_cast<FtpPayload*>(&ftp.payload[0]);
ftp.target_component = getTargetComponentId();
ftp.target_system = getTargetSystemId();
payload->opcode = kCmdCreateDirectory;
setPayloadFilename(payload, remote_file_.c_str());
sendMessage(ftp);
recordMessageSent();
}
void MavLinkFtpClientImpl::rmdir()
{
MavLinkFileTransferProtocol ftp;
FtpPayload* payload = reinterpret_cast<FtpPayload*>(&ftp.payload[0]);
ftp.target_component = getTargetComponentId();
ftp.target_system = getTargetSystemId();
payload->opcode = kCmdRemoveDirectory;
setPayloadFilename(payload, remote_file_.c_str());
sendMessage(ftp);
recordMessageSent();
}
void MavLinkFtpClientImpl::listDirectory()
{
MavLinkFileTransferProtocol ftp;
FtpPayload* payload = reinterpret_cast<FtpPayload*>(&ftp.payload[0]);
ftp.target_component = getTargetComponentId();
ftp.target_system = getTargetSystemId();
payload->opcode = kCmdListDirectory;
setPayloadFilename(payload, remote_file_.c_str());
payload->offset = file_index_;
sendMessage(ftp);
recordMessageSent();
}
bool MavLinkFtpClientImpl::openSourceFile()
{
file_ptr_ = fopen(local_file_.c_str(), "rb");
if (file_ptr_ == nullptr) {
if (progress_ != nullptr) {
progress_->error = errno;
progress_->message = Utils::stringf("Error opening file '%s' for reading, rc=%d", remote_file_.c_str(), progress_->error);
}
return false;
}
fseek(file_ptr_, 0, SEEK_END);
long pos = ftell(file_ptr_);
fseek(file_ptr_, 0, SEEK_SET);
file_size_ = static_cast<uint64_t>(pos);
if (progress_ != nullptr) {
progress_->goal = file_size_;
}
return true;
}
bool MavLinkFtpClientImpl::createLocalFile()
{
if (file_ptr_ == nullptr) {
auto path = FileSystem::getFullPath(local_file_);
if (FileSystem::isDirectory(path)) {
// user was lazy, only told us where to put the file, so we borrow the name of the file
// from the source.
auto remote = FileSystem::getFileName(normalize(remote_file_));
local_file_ = FileSystem::combine(path, remote);
}
else {
// check if directory exists.
FileSystem::removeLeaf(path);
if (FileSystem::isDirectory(path)) {
// perfect.
}
else if (FileSystem::exists(path)) {
if (progress_ != nullptr) {
progress_->error = errno;
progress_->message = Utils::stringf("Error opening file because '%s' is not a directory", path.c_str());
}
return false;
}
else {
if (progress_ != nullptr) {
progress_->error = errno;
progress_->message = Utils::stringf("Error opening file because '%s' should be a directory but it was not found", path.c_str());
}
return false;
}
}
file_ptr_ = fopen(local_file_.c_str(), "wb");
if (file_ptr_ == nullptr) {
if (progress_ != nullptr) {
progress_->error = errno;
progress_->message = Utils::stringf("Error opening file '%s' for writing, rc=%d", local_file_.c_str(), errno);
}
return false;
}
file_size_ = 0;
}
return true;
}
void MavLinkFtpClientImpl::readFile()
{
if (!remote_file_open_) {
MavLinkFileTransferProtocol ftp;
FtpPayload* payload = reinterpret_cast<FtpPayload*>(&ftp.payload[0]);
ftp.target_component = getTargetComponentId();
ftp.target_system = getTargetSystemId();
payload->opcode = kCmdOpenFileRO;
setPayloadFilename(payload, remote_file_.c_str());
sendMessage(ftp);
recordMessageSent();
}
else {
if (createLocalFile()) {
// use last_message_ so we preserve the sessionid.
FtpPayload* payload = reinterpret_cast<FtpPayload*>(&last_message_.payload[0]);
payload->opcode = kCmdReadFile;
payload->offset = bytes_read_;
last_message_.target_component = getTargetComponentId();
last_message_.target_system = getTargetSystemId();
sendMessage(last_message_);
recordMessageSent();
if (progress_ != nullptr) {
progress_->current = bytes_read_;
}
}
else {
// could not create the local file, so stop.
waiting_ = false;
}
}
}
void MavLinkFtpClientImpl::writeFile()
{
if (!remote_file_open_) {
MavLinkFileTransferProtocol ftp;
FtpPayload* payload = reinterpret_cast<FtpPayload*>(&ftp.payload[0]);
ftp.target_component = getTargetComponentId();
ftp.target_system = getTargetSystemId();
payload->opcode = kCmdOpenFileWO;
strcpy(reinterpret_cast<char*>(&payload->data), remote_file_.c_str());
payload->size = static_cast<uint8_t>(remote_file_.size());
sendMessage(ftp);
recordMessageSent();
}
else {
// must use last_message_ so we preserve the session id.
MavLinkFileTransferProtocol& ftp = last_message_;
FtpPayload* payload = reinterpret_cast<FtpPayload*>(&ftp.payload[0]);
payload->opcode = kCmdWriteFile;
payload->seq_number = sequence_;
fseek(file_ptr_, bytes_written_, SEEK_SET);
uint8_t* data = &payload->data;
size_t bytes = fread(data, 1, 251 - 12, file_ptr_);
if (progress_ != nullptr) {
progress_->current = bytes_written_;
}
if (bytes == 0) {
success_ = true;
reset();
int err = ferror(file_ptr_);
if (err != 0) {
if (progress_ != nullptr) {
progress_->error = err;
progress_->message = Utils::stringf("error reading local file, errno=%d", err);
}
}
fclose(file_ptr_);
file_ptr_ = nullptr;
waiting_ = false;
}
else {
payload->offset = bytes_written_;
payload->size = static_cast<uint8_t>(bytes);
ftp.target_component = getTargetComponentId();
ftp.target_system = getTargetSystemId();
sendMessage(ftp);
recordMessageSent();
}
}
}
void MavLinkFtpClientImpl::cancel()
{
// todo: wait for any pending responses from PX4 so we can safely start a new command.
reset();
}
void MavLinkFtpClientImpl::close()
{
if (file_ptr_ != nullptr) {
reset();
fclose(file_ptr_);
file_ptr_ = nullptr;
}
if (subscription_ != 0) {
getConnection()->unsubscribe(subscription_);
subscription_ = 0;
}
}
void MavLinkFtpClientImpl::reset()
{
MavLinkFileTransferProtocol ftp;
ftp.target_component = getTargetComponentId();
ftp.target_system = getTargetSystemId();
FtpPayload* payload = reinterpret_cast<FtpPayload*>(&ftp.payload[0]);
payload->opcode = kCmdResetSessions;
sendMessage(ftp);
recordMessageSent();
}
void MavLinkFtpClientImpl::handleListResponse()
{
FtpPayload* payload = reinterpret_cast<FtpPayload*>(&last_message_.payload[0]);
if (payload->offset != file_index_) {
// todo: error handling here? sequence is out of order...
Utils::log(Utils::stringf("list got offset %d, but expecting file index %d\n", payload->offset, file_index_), Utils::kLogLevelError);
retry();
return;
}
if (payload->offset == 0 && payload->size == 0) {
// directory must be empty then, can't do nextStep because
// it will just loop for ever re-requesting zero offset into
// empty directory.
reset();
success_ = true;
waiting_ = false;
return;
}
// result should be a list of null terminated file names.
uint8_t* data = &payload->data;
for (int offset = 0; offset < payload->size;) {
uint8_t dirType = data[offset];
offset++;
retries_ = 0;
file_index_++;
int len = 0;
std::string name = reinterpret_cast<char*>(&data[offset]);
if (dirType == kDirentSkip) {
// skipping this entry
}
else if (dirType == kDirentFile) {
size_t i = name.find_last_of('\t');
MavLinkFileInfo info;
info.is_directory = false;
len = static_cast<int>(name.size());
if (i > 0) {
// remove the file size field.
std::string size(name.begin() + i + 1, name.end());
info.size = Utils::to_integer(size);
name.erase(name.begin() + i, name.end());
}
info.name = name;
//printf("%s\n", name.c_str());
if (files_ != nullptr) {
files_->push_back(info);
}
}
else if (dirType == kDirentDir) {
MavLinkFileInfo info;
info.is_directory = true;
info.name = name;
len = static_cast<int>(name.size());
if (files_ != nullptr) {
files_->push_back(info);
}
}
offset += len + 1;
}
if (progress_ != nullptr) {
progress_->current = file_index_;
}
// request the next batch.
nextStep();
}
void MavLinkFtpClientImpl::handleReadResponse()
{
FtpPayload* payload = reinterpret_cast<FtpPayload*>(&last_message_.payload[0]);
if (payload->req_opcode == kCmdOpenFileRO) {
remote_file_open_ = true;
bytes_read_ = 0;
retries_ = 0;
sequence_ = payload->seq_number;
uint32_t* size = reinterpret_cast<uint32_t*>(&payload->data);
file_size_ = static_cast<uint64_t>(*size);
if (progress_ != nullptr) {
progress_->goal = file_size_;
}
nextStep();
}
else if (payload->req_opcode == kCmdReadFile) {
int seq = static_cast<int>(payload->seq_number);
if (seq != sequence_ + 1) {
Utils::log(Utils::stringf("packet %d is out of sequence, expecting number %d\n", seq, sequence_ + 1), Utils::kLogLevelError);
// perhaps this was a late response after we did a retry, so ignore it.
return;
}
else if (file_ptr_ != nullptr) {
sequence_ = payload->seq_number;
fwrite(&payload->data, payload->size, 1, file_ptr_);
bytes_read_ += payload->size;
retries_ = 0;
nextStep();
}
}
}
void MavLinkFtpClientImpl::handleWriteResponse()
{
FtpPayload* payload = reinterpret_cast<FtpPayload*>(&last_message_.payload[0]);
if (payload->req_opcode == kCmdOpenFileWO) {
remote_file_open_ = true;
bytes_written_ = 0;
retries_ = 0;
sequence_ = payload->seq_number;
nextStep();
}
else if (payload->req_opcode == kCmdWriteFile) {
int seq = static_cast<int>(payload->seq_number);
if (seq != sequence_ + 1) {
Utils::log(Utils::stringf("packet %d is out of sequence, expecting number %d\n", seq, sequence_ + 1), Utils::kLogLevelError);
// perhaps this was a late response after we did a retry, so ignore it.
return;
}
uint32_t* size = reinterpret_cast<uint32_t*>(&payload->data);
// payload->size contains the bytes_written from PX4, so that's how much we advance.
bytes_written_ += static_cast<int>(*size);
retries_ = 0;
sequence_++;
nextStep();
}
}
void MavLinkFtpClientImpl::handleRemoveResponse()
{
success_ = true;
waiting_ = false;
}
void MavLinkFtpClientImpl::handleRmdirResponse()
{
success_ = true;
waiting_ = false;
}
void MavLinkFtpClientImpl::handleMkdirResponse()
{
success_ = true;
waiting_ = false;
}
void MavLinkFtpClientImpl::handleResponse(const MavLinkMessage& msg)
{
if (msg.msgid == static_cast<int>(MavLinkMessageIds::MAVLINK_MSG_ID_FILE_TRANSFER_PROTOCOL)) {
last_message_.decode(msg);
recordMessageReceived();
FtpPayload* payload = reinterpret_cast<FtpPayload*>(&last_message_.payload[0]);
if (payload->opcode == kRspNak) {
// reached the end of the list or the file.
if (file_ptr_ != nullptr) {
fclose(file_ptr_);
file_ptr_ = nullptr;
}
int error = static_cast<int>(payload->data);
if (error == kErrEOF) {
// end of file or directory listing.
success_ = true;
error = 0;
}
else {
success_ = false;
if (progress_ != nullptr) {
if (error == kErrFailErrno) {
const uint8_t* data = &(payload->data);
error = static_cast<int>(data[1]);
progress_->error = error;
progress_->message = Utils::stringf("ftp kErrFailErrno %d", error);
}
else {
progress_->error = error;
progress_->message = Utils::stringf("ftp error %d", error);
}
}
}
errorCode_ = error;
waiting_ = false;
reset();
}
else if (payload->opcode == kRspAck) {
if (progress_ != nullptr) {
progress_->message_count++;
}
// success, data should be following...
switch (payload->req_opcode) {
case kCmdListDirectory:
handleListResponse();
break;
case kCmdOpenFileRO:
case kCmdReadFile:
handleReadResponse();
break;
case kCmdOpenFileWO:
case kCmdWriteFile:
handleWriteResponse();
break;
case kCmdResetSessions:
// ack on this cmd is a noop
break;
case kCmdRemoveFile:
handleRemoveResponse();
break;
case kCmdRemoveDirectory:
handleRmdirResponse();
break;
case kCmdCreateDirectory:
handleMkdirResponse();
break;
default:
// todo: how to handle this? For now we ignore it and let the watchdog kick in and do a retry.
Utils::log(Utils::stringf("Unexpected ACK with req_opcode=%d\n", static_cast<int>(payload->req_opcode)), Utils::kLogLevelWarn);
break;
}
}
}
}
void MavLinkFtpClientImpl::MavLinkFtpClientImpl::retry()
{
retries_++;
if (retries_ < 10) {
Utils::log(Utils::stringf("retry %d\n", retries_), Utils::kLogLevelWarn);
nextStep();
}
else {
// give up then.
errorCode_ = kErrRetriesExhausted;
success_ = false;
waiting_ = false;
reset();
}
}
void MavLinkFtpClientImpl::recordMessageSent()
{
// tell watchdog we are sending a request
std::lock_guard<std::mutex> guard(mutex_);
start_time_ = std::chrono::duration_cast<milliseconds>(std::chrono::system_clock::now().time_since_epoch());
}
void MavLinkFtpClientImpl::recordMessageReceived()
{
std::lock_guard<std::mutex> guard(mutex_);
messages_++;
milliseconds endTime = std::chrono::duration_cast<milliseconds>(std::chrono::system_clock::now().time_since_epoch());
milliseconds duration = endTime - start_time_;
total_time_ += duration;
if (progress_ != nullptr && duration.count() > progress_->longest_delay) {
progress_->longest_delay = static_cast<double>(duration.count());
}
}
std::string MavLinkFtpClientImpl::replaceAll(std::string s, char toFind, char toReplace)
{
size_t pos = s.find_first_of(toFind, 0);
while (pos != std::string::npos) {
s.replace(pos, 1, 1, toReplace);
pos = s.find_first_of(toFind, 0);
}
return s;
}
std::string MavLinkFtpClientImpl::normalize(std::string arg)
{
if (FileSystem::kPathSeparator == '\\') {
return replaceAll(arg, '/', '\\'); // make sure user input matches what FileSystem will do when resolving paths.
}
return arg;
}
std::string MavLinkFtpClientImpl::toPX4Path(std::string arg)
{
if (FileSystem::kPathSeparator == '\\') {
return replaceAll(arg, '\\', '/'); // PX4 uses '/'
}
return arg;
}