-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathFatReader.cpp
488 lines (471 loc) · 15.1 KB
/
FatReader.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
/* Arduino FatReader Library
* Copyright (C) 2009 by William Greiman
*
* This file is part of the Arduino FatReader Library
*
* This Library is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 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 General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with the Arduino FatReader Library. If not, see
* <http://www.gnu.org/licenses/>.
*/
#include <string.h>
#if ARDUINO < 100
#include <WProgram.h>
#else // ARDUINO
#include <Arduino.h>
#endif // ARDUINO
#include <FatReader.h>
//------------------------------------------------------------------------------
/**
* Format the name field of the dir_t struct \a dir into the 13 byte array
* \a name in the standard 8.3 short name format.
*/
void dirName(dir_t &dir, char name[]) {
uint8_t j = 0;
for (uint8_t i = 0; i < 11; i++) {
if (dir.name[i] == ' ')
continue;
if (i == 8)
name[j++] = '.';
name[j++] = dir.name[i];
}
name[j] = 0;
}
//------------------------------------------------------------------------------
/**
* Print the name field of a dir_t structure in 8.3 format.
* Append a '/' if it is a subdirectory.
*
*/
void printEntryName(dir_t &dir) {
for (uint8_t i = 0; i < 11; i++) {
if (dir.name[i] == ' ')
continue;
if (i == 8)
Serial.write('.');
Serial.write(dir.name[i]);
}
if (DIR_IS_SUBDIR(dir)) {
// indicate subdirectory
Serial.write('/');
}
}
/**************************************************************************/
/*!
@brief list file in a directory
@param flags file flags
*/
/**************************************************************************/
void FatReader::ls(uint8_t flags) {
dir_t d;
if (isDir())
lsR(d, flags, 0);
}
//------------------------------------------------------------------------------
// recursive part of ls()
void FatReader::lsR(dir_t &d, uint8_t flags, uint8_t indent) {
while (readDir(d) > 0) {
// print any indent spaces
for (int8_t i = 0; i < indent; i++) {
Serial.write(' ');
}
printEntryName(d);
if (DIR_IS_SUBDIR(d)) {
Serial.println();
// recursive call if LS_R
if (flags & LS_R) {
FatReader s;
if (s.open(*vol_, d)) {
s.lsR(d, flags, indent + 2);
}
}
} else {
if (flags & LS_FLAG_FRAGMENTED) {
uint32_t c = (uint32_t)d.firstClusterHigh << 16;
c |= d.firstClusterLow;
// fragmented if has clusters and not contiguous
char f = c && !vol_->chainIsContiguous(c) ? '*' : ' ';
Serial.write(' ');
Serial.write(f);
}
if (flags & LS_SIZE) {
Serial.write(' ');
Serial.print(d.fileSize);
}
Serial.println();
}
}
}
//------------------------------------------------------------------------------
/** return the next cluster in a chain */
uint32_t FatVolume::nextCluster(uint32_t cluster) {
if (!validCluster(cluster)) {
return 0;
}
if (fatType_ == 32) {
uint32_t next;
uint32_t block = fatStartBlock_ + (cluster >> 7);
uint16_t offset = 0X1FF & (cluster << 2);
if (!rawRead(block, offset, (uint8_t *)&next, 4)) {
return 0;
}
return next;
}
if (fatType_ == 16) {
uint16_t next;
uint32_t block = fatStartBlock_ + (cluster >> 8);
uint16_t offset = 0X1FF & (cluster << 1);
if (!rawRead(block, offset, (uint8_t *)&next, 2)) {
return 0;
}
return next;
}
return 0;
}
//------------------------------------------------------------------------------
/**
* Open a file or subdirectory by index.
*
* \param[in] dir An open FatReader instance for the directory.
*
* \param[in] index The \a index for a file or subdirectory in the
* directory \a dir. \a index is the byte offset divided by 32 of
* the directory entry for the file or subdirectory.
*
* To determine the index for a file open it by name. The index for the
* file is then is: (dir.readPosition()/32 -1)
*
*
* \return The value one, true, is returned for success and
* the value zero, false, is returned for failure.
* Reasons for failure include the FAT volume has not been initialized, \a dir
* is not a directory, \a name is invalid, the file or subdirectory does not
* exist, or an I/O error occurred.
*/
uint8_t FatReader::open(FatReader &dir, uint16_t index) {
dir_t d;
// position directory file to entry
if (!dir.seekSet(32UL * index))
return false;
// read entry
if (dir.read(&d, 32) != 32)
return false;
// must be a real file or directory
if (!DIR_IS_FILE_OR_SUBDIR(d) || d.name[0] == DIR_NAME_FREE ||
d.name[0] == DIR_NAME_DELETED) {
return false;
}
return open(*dir.volume(), d);
}
//------------------------------------------------------------------------------
/**
* Open a file or subdirectory by name.
*
* \note The file or subdirectory, \a name, must be in the specified
* directory, \a dir, and must have a DOS 8.3 name.
*
* \param[in] dir An open FatReader instance for the directory.
*
* \param[in] name A valid 8.3 DOS name for a file or subdirectory in the
* directory \a dir.
*
* \return The value one, true, is returned for success and
* the value zero, false, is returned for failure.
* Reasons for failure include the FAT volume has not been initialized, \a dir
* is not a directory, \a name is invalid, the file or subdirectory does not
* exist, or an I/O error occurred.
*/
uint8_t FatReader::open(FatReader &dir, char *name) {
dir_t entry;
char dname[13];
dir.rewind();
while (dir.readDir(entry) > 0) {
dirName(entry, dname);
if (strcasecmp(dname, name))
continue;
return open(*(dir.vol_), entry);
}
return false;
}
//------------------------------------------------------------------------------
/**
* Open a file or subdirectory by directory structure.
*
* \param[in] vol The FAT volume that contains the file or subdirectory.
*
* \param[in] dir The directory structure describing the file or subdirectory.
*
* \return The value one, true, is returned for success and
* the value zero, false, is returned for failure.
* Reasons for failure include the FAT volume, \a vol, has not been initialized,
* \a vol is a FAT12 volume or \a dir is not a valid directory entry.
*/
uint8_t FatReader::open(FatVolume &vol, dir_t &dir) {
if (vol.fatType() < 16)
return false;
if (dir.name[0] == 0 || dir.name[0] == DIR_NAME_DELETED) {
return false;
}
firstCluster_ = (uint32_t)dir.firstClusterHigh << 16;
firstCluster_ |= dir.firstClusterLow;
if (DIR_IS_FILE(dir)) {
type_ = FILE_TYPE_NORMAL;
fileSize_ = dir.fileSize;
} else if (DIR_IS_SUBDIR(dir)) {
type_ = FILE_TYPE_SUBDIR;
fileSize_ = vol.chainSize(firstCluster_);
} else {
return false;
}
vol_ = &vol;
rewind();
return true;
}
//------------------------------------------------------------------------------
/**
* Open a volume's root directory.
*
* \param[in] vol The FAT volume containing the root directory to be opened.
*
* \return The value one, true, is returned for success and
* the value zero, false, is returned for failure.
* Reasons for failure include the FAT volume has not been initialized
* or it a FAT12 volume.
*/
uint8_t FatReader::openRoot(FatVolume &vol) {
if (vol.fatType() == 16) {
type_ = FILE_TYPE_ROOT16;
firstCluster_ = 0;
fileSize_ = 32 * vol.rootDirEntryCount();
} else if (vol.fatType() == 32) {
type_ = FILE_TYPE_ROOT32;
firstCluster_ = vol.rootDirStart();
fileSize_ = vol.chainSize(firstCluster_);
} else {
return false;
}
vol_ = &vol;
rewind();
return true;
}
//------------------------------------------------------------------------------
/**
* Check for a contiguous file and enable optimized reads if the
* file is contiguous.
*/
void FatReader::optimizeContiguous(void) {
if (isOpen() && firstCluster_) {
if (vol_->chainIsContiguous(firstCluster_)) {
type_ |= FILE_IS_CONTIGUOUS;
}
}
}
//------------------------------------------------------------------------------
/**
* Read data from a file at starting at the current read position.
*
* \param[out] buf Pointer to the location that will receive the data.
*
* \param[in] count Maximum number of bytes to read.
*
* \return For success read() returns the number of bytes read.
* A value less than \a count, including zero, will be returned
* if end of file is reached.
* If an error occurs, read() returns -1. Possible errors include
* read() called before a file has been opened, corrupt file system
* or an I/O error occurred.
*/
int16_t FatReader::read(void *buf, uint16_t count) {
uint8_t *dst = (uint8_t *)buf;
uint16_t nr = 0;
int16_t n = 0;
while (nr < count && (n = readBlockData(dst, count - nr)) > 0) {
if (!seekCur(n))
return -1;
dst += n;
nr += n;
}
return n < 0 ? -1 : nr;
}
//------------------------------------------------------------------------------
// read maximum amount possible from current physical block
int16_t FatReader::readBlockData(uint8_t *dst, uint16_t count) {
uint32_t block;
uint16_t offset = readPosition_ & 0X1FF;
if (count > (512 - offset))
count = 512 - offset;
if (count > (fileSize_ - readPosition_))
count = fileSize_ - readPosition_;
if (fileType() == FILE_TYPE_ROOT16) {
block = vol_->rootDirStart() + (readPosition_ >> 9);
} else {
uint8_t bpc = vol_->blocksPerCluster();
block = vol_->dataStartBlock() + (readCluster_ - 2) * bpc +
((readPosition_ >> 9) & (bpc - 1));
}
return vol_->rawRead(block, offset, dst, count) ? count : -1;
}
//------------------------------------------------------------------------------
/**
* Read the next directory entry from a directory file.
*
* \param[out] dir The dir_t struct that will receive the data.
*
* \return For success readDir() returns the number of bytes read.
* A value of zero will be returned if end of file is reached.
* If an error occurs, readDir() returns -1. Possible errors include
* readDir() called before a directory has been opened, this is not
* a directory file or an I/O error occurred.
*/
int8_t FatReader::readDir(dir_t &dir) {
int8_t n;
// if not a directory file return an error
if (!isDir())
return -1;
while ((n = read((uint8_t *)&dir, sizeof(dir_t))) == sizeof(dir_t) &&
dir.name[0] != DIR_NAME_FREE) {
if (dir.name[0] == DIR_NAME_DELETED || dir.name[0] == '.')
continue;
if (DIR_IS_FILE(dir) || DIR_IS_SUBDIR(dir))
return n;
}
return n < 0 ? n : 0;
}
//------------------------------------------------------------------------------
/** Set read position to start of file */
void FatReader::rewind(void) {
readCluster_ = firstCluster_;
readPosition_ = 0;
}
/**
* Set the read position for a file or directory to the current position plus
* \a offset.
*
* \param[in] offset The amount to advance the read position.
*
* \return The value one, true, is returned for success and
* the value zero, false, is returned for failure.
*/
uint8_t FatReader::seekCur(uint32_t offset) {
uint32_t newPos = readPosition_ + offset;
// can't position beyond end of file
if (newPos > fileSize_)
return false;
// number of clusters forward
uint32_t nc = (newPos >> 9) / vol_->blocksPerCluster() -
(readPosition_ >> 9) / vol_->blocksPerCluster();
// set new position - only corrupt file system can cause error now
readPosition_ = newPos;
// no clusters if FAT16 root
if (fileType() == FILE_TYPE_ROOT16)
return true;
// don't need to read FAT if contiguous
if (isContiguous()) {
readCluster_ += nc;
return true;
}
// read FAT chain while nc != 0
while (nc-- != 0) {
if (!(readCluster_ = vol_->nextCluster(readCluster_))) {
return false;
}
}
return true;
}
//------------------------------------------------------------------------------
/** check for contiguous chain */
uint8_t FatVolume::chainIsContiguous(uint32_t cluster) {
uint32_t next;
while ((next = nextCluster(cluster))) {
if (next != (cluster + 1)) {
return isEOC(next);
}
cluster = next;
}
return false;
}
//------------------------------------------------------------------------------
/** return the number of bytes in a cluster chain */
uint32_t FatVolume::chainSize(uint32_t cluster) {
uint32_t size = 0;
while ((cluster = nextCluster(cluster))) {
size += 512 * blocksPerCluster_;
}
return size;
}
//------------------------------------------------------------------------------
/**
* Initialize a FAT volume.
*
* \param[in] dev The SD card where the volume is located.
*
* \param[in] part The partition to be used. Legal values for \a part are
* 1-4 to use the corresponding partition on a device formatted with
* a MBR, Master Boot Record, or zero if the device is formatted as
* a super floppy with the FAT boot sector in block zero.
*
* \return The value one, true, is returned for success and
* the value zero, false, is returned for failure. Reasons for
* failure include not finding a valid partition, not finding a valid
* FAT file system in the specified partition or an I/O error.
*/
uint8_t FatVolume::init(SdReader &dev, uint8_t part) {
uint8_t buf[BPB_COUNT];
uint32_t volumeStartBlock = 0;
rawDevice_ = &dev;
// if part == 0 assume super floppy with FAT boot sector in block zero
// if part > 0 assume mbr volume with partition table
if (part) {
if (part > 4)
return false;
if (!rawRead(volumeStartBlock, PART_OFFSET + 16 * (part - 1), buf, 16)) {
return false;
}
part_t *part = (part_t *)buf;
if ((part->boot & 0X7F) != 0 || part->totalSectors < 100 ||
part->firstSector == 0) {
// not a valid partition
return false;
}
volumeStartBlock = part->firstSector;
}
if (!rawRead(volumeStartBlock, BPB_OFFSET, buf, BPB_COUNT)) {
return false;
}
bpb_t *bpb = (bpb_t *)buf;
if (bpb->bytesPerSector != 512 || bpb->fatCount == 0 ||
bpb->reservedSectorCount == 0 || bpb->sectorsPerCluster == 0 ||
(bpb->sectorsPerCluster & (bpb->sectorsPerCluster - 1)) != 0) {
// not valid FAT volume
return false;
}
fatCount_ = bpb->fatCount;
blocksPerCluster_ = bpb->sectorsPerCluster;
blocksPerFat_ =
bpb->sectorsPerFat16 ? bpb->sectorsPerFat16 : bpb->sectorsPerFat32;
rootDirEntryCount_ = bpb->rootDirEntryCount;
fatStartBlock_ = volumeStartBlock + bpb->reservedSectorCount;
rootDirStart_ = fatStartBlock_ + bpb->fatCount * blocksPerFat_;
dataStartBlock_ = rootDirStart_ + ((32 * bpb->rootDirEntryCount + 511) / 512);
totalBlocks_ =
bpb->totalSectors16 ? bpb->totalSectors16 : bpb->totalSectors32;
clusterCount_ = (totalBlocks_ - (dataStartBlock_ - volumeStartBlock)) /
bpb->sectorsPerCluster;
if (clusterCount_ < 4085) {
fatType_ = 12;
} else if (clusterCount_ < 65525) {
fatType_ = 16;
} else {
rootDirStart_ = bpb->fat32RootCluster;
fatType_ = 32;
}
return true;
}