Welcome to mirror list, hosted at ThFree Co, Russian Federation.

FileStore.cpp « Storage « src - github.com/Duet3D/RepRapFirmware.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 1a3b25e72628b4352af1193fa516eba9c3b2bde6 (plain)
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
//------------------------------------------------------------------------------------------------

#include "RepRapFirmware.h"
#include "FileStore.h"
#include "MassStorage.h"
#include "Platform.h"
#include "RepRap.h"

uint32_t FileStore::longestWriteTime = 0;

FileStore::FileStore() : writeBuffer(nullptr)
{
	Init();
}

void FileStore::Init()
{
	usageMode = FileUseMode::free;
	openCount = 0;
	closeRequested = false;
}

// Invalidate the file if it uses the specified FATFS object
bool FileStore::Invalidate(const FATFS *fs, bool doClose)
{
	if (file.fs == fs)
	{
		if (doClose)
		{
			(void)ForceClose();
		}
		else
		{
			file.fs = nullptr;
			if (writeBuffer != nullptr)
			{
				reprap.GetPlatform().GetMassStorage()->ReleaseWriteBuffer(writeBuffer);
				writeBuffer = nullptr;
			}
		}
		usageMode = FileUseMode::invalidated;
		return true;
	}
	return false;
}

// Return true if the file is open on the specified file system
bool FileStore::IsOpenOn(const FATFS *fs) const
{
	return openCount != 0 && file.fs == fs;
}

// Open a local file (for example on an SD card).
// This is protected - only Platform can access it.
bool FileStore::Open(const char* directory, const char* fileName, OpenMode mode)
{
	String<MaxFilenameLength> location;
	MassStorage::CombineName(location.GetRef(), directory, fileName);
	const bool writing = (mode == OpenMode::write || mode == OpenMode::append);

	if (writing)
	{
		// Try to create the path of this file if we want to write to it
		String<MaxFilenameLength> filePath;
		filePath.copy(location.c_str());

		size_t i = (isdigit(filePath[0]) && filePath[1] == ':') ? 2 : 0;
		if (filePath[i] == '/')
		{
			++i;
		}

		while (i < filePath.strlen())
		{
			if (filePath[i] == '/')
			{
				filePath[i] = 0;
				if (!reprap.GetPlatform().GetMassStorage()->DirectoryExists(filePath.GetRef()) && !reprap.GetPlatform().GetMassStorage()->MakeDirectory(filePath.c_str()))
				{
					reprap.GetPlatform().MessageF(ErrorMessage, "Failed to create directory %s while trying to open file %s\n", filePath.c_str(), location.c_str());
					return false;
				}
				filePath[i] = '/';
			}
			++i;
		}

		// Also try to allocate a write buffer so we can perform faster writes
		// We only do this if the mode is write, not append, because we don't want to use up a large buffer to append messages to the log file,
		// especially as we need to flush messages to SD card regularly.
		// Currently, append mode is used for the log file and for appending simulated print times to GCodes files (which required read access too).
		writeBuffer = (mode == OpenMode::write) ? reprap.GetPlatform().GetMassStorage()->AllocateWriteBuffer() : nullptr;
	}

	const FRESULT openReturn = f_open(&file, location.c_str(),
										(mode == OpenMode::write) ?  FA_CREATE_ALWAYS | FA_WRITE
											: (mode == OpenMode::append) ? FA_READ | FA_WRITE | FA_OPEN_ALWAYS
												: FA_OPEN_EXISTING | FA_READ);
	if (openReturn != FR_OK)
	{
		// We no longer report an error if opening a file in read mode fails unless debugging is enabled, because sometimes that is quite normal.
		// It is up to the caller to report an error if necessary.
		if (reprap.Debug(modulePlatform))
		{
			reprap.GetPlatform().MessageF(ErrorMessage, "Can't open %s to %s, error code %d\n", location.c_str(), (writing) ? "write" : "read", openReturn);
		}
		return false;
	}
	crc.Reset();
	usageMode = (writing) ? FileUseMode::readWrite : FileUseMode::readOnly;
	openCount = 1;
	return true;
}

void FileStore::Duplicate()
{
	switch (usageMode)
	{
	case FileUseMode::free:
		INTERNAL_ERROR;
		break;

	case FileUseMode::readOnly:
	case FileUseMode::readWrite:
		{
			const irqflags_t flags = cpu_irq_save();
			++openCount;
			cpu_irq_restore(flags);
		}
		break;

	case FileUseMode::invalidated:
	default:
		break;
	}
}

// This may be called from an ISR, in which case we need to defer the close
bool FileStore::Close()
{
	switch (usageMode)
	{
	case FileUseMode::free:
		if (!inInterrupt())
		{
			INTERNAL_ERROR;
		}
		return false;

	case FileUseMode::readOnly:
	case FileUseMode::readWrite:
		{
			const irqflags_t flags = cpu_irq_save();
			if (openCount > 1)
			{
				--openCount;
				cpu_irq_restore(flags);
				return true;
			}
			else if (inInterrupt())
			{
				closeRequested = true;
				cpu_irq_restore(flags);
				return true;
			}
			else
			{
				cpu_irq_restore(flags);
				return ForceClose();
			}
		}

	case FileUseMode::invalidated:
	default:
		{
			const irqflags_t flags = cpu_irq_save();
			if (openCount > 1)
			{
				--openCount;
			}
			else
			{
				usageMode = FileUseMode::free;
			}
			cpu_irq_restore(flags);
			return true;
		}
	}
}

bool FileStore::ForceClose()
{
	bool ok = true;
	if (usageMode == FileUseMode::readWrite)
	{
		ok = Flush();
	}

	if (writeBuffer != nullptr)
	{
		reprap.GetPlatform().GetMassStorage()->ReleaseWriteBuffer(writeBuffer);
		writeBuffer = nullptr;
	}

	const FRESULT fr = f_close(&file);
	usageMode = FileUseMode::free;
	closeRequested = false;
	openCount = 0;
	return ok && fr == FR_OK;
}

bool FileStore::Seek(FilePosition pos)
{
	switch (usageMode)
	{
	case FileUseMode::free:
		INTERNAL_ERROR;
		return false;

	case FileUseMode::readOnly:
	case FileUseMode::readWrite:
		return f_lseek(&file, pos) == FR_OK;

	case FileUseMode::invalidated:
	default:
		return false;
	}
}

FilePosition FileStore::Position() const
{
	return (usageMode == FileUseMode::readOnly || usageMode == FileUseMode::readWrite) ? file.fptr : 0;
}

uint32_t FileStore::ClusterSize() const
{
	return (usageMode == FileUseMode::readOnly || usageMode == FileUseMode::readWrite) ? file.fs->csize * 512u : 1;	// we divide by the cluster size so return 1 not 0 if there is an error
}

#if 0	// not currently used
bool FileStore::GoToEnd()
{
	return Seek(Length());
}
#endif

FilePosition FileStore::Length() const
{
	switch (usageMode)
	{
	case FileUseMode::free:
		INTERNAL_ERROR;
		return 0;

	case FileUseMode::readOnly:
		return file.fsize;

	case FileUseMode::readWrite:
		return (writeBuffer != nullptr) ? file.fsize + writeBuffer->BytesStored() : file.fsize;

	case FileUseMode::invalidated:
	default:
		return 0;
	}
}

// Single character read
bool FileStore::Read(char& b)
{
	return Read(&b, sizeof(char));
}

// Returns the number of bytes read or -1 if the read process failed
int FileStore::Read(char* extBuf, size_t nBytes)
{
	switch (usageMode)
	{
	case FileUseMode::free:
		INTERNAL_ERROR;
		return -1;

	case FileUseMode::readOnly:
	case FileUseMode::readWrite:
		{
			UINT bytes_read;
			FRESULT readStatus = f_read(&file, extBuf, nBytes, &bytes_read);
			if (readStatus != FR_OK)
			{
				reprap.GetPlatform().Message(ErrorMessage, "Cannot read file.\n");
				return -1;
			}
			return (int)bytes_read;
		}

	case FileUseMode::invalidated:
	default:
		return -1;
	}
}

// As Read but stop after '\n' or '\r\n' and null-terminate the string.
// If the next line is too long to fit in the buffer then the line will be split.
int FileStore::ReadLine(char* buf, size_t nBytes)
{
	const FilePosition lineStart = Position();
	const int r = Read(buf, nBytes);
	if (r < 0)
	{
		return r;
	}

	int i = 0;
	while (i < r && buf[i] != '\r' && buf[i] != '\n')
	{
		++i;
	}

	if (i + 1 < r && buf[i] == '\r' && buf[i + 1] == '\n')	// if stopped at CRLF (Windows-style line end)
	{
		Seek(lineStart + i + 2);							// seek to just after the CRLF
	}
	else if (i < r)											// if stopped at CR or LF
	{
		Seek(lineStart + i + 1);							// seek to just after the CR or LF
	}
	else if (i == (int)nBytes)
	{
		--i;												// make room for the null terminator
		Seek(lineStart + i);
	}
	buf[i] = 0;
	return i;
}

FRESULT FileStore::Store(const char *s, size_t len, size_t *bytesWritten)
{
	uint32_t time = Platform::GetInterruptClocks();
	crc.Update(s, len);
	const FRESULT writeStatus = f_write(&file, s, len, bytesWritten);
	time = Platform::GetInterruptClocks() - time;
	if (time > longestWriteTime)
	{
		longestWriteTime = time;
	}
	return writeStatus;
}

bool FileStore::Write(char b)
{
	return Write(&b, sizeof(char));
}

bool FileStore::Write(const char* b)
{
	return Write(b, strlen(b));
}

bool FileStore::Write(const char *s, size_t len)
{
	switch (usageMode)
	{
	case FileUseMode::free:
		INTERNAL_ERROR;
		return false;

	case FileUseMode::readOnly:
	case FileUseMode::readWrite:
		{
			size_t totalBytesWritten = 0;
			FRESULT writeStatus = FR_OK;
			if (writeBuffer == nullptr)
			{
				writeStatus = Store(s, len, &totalBytesWritten);
			}
			else
			{
				do
				{
					size_t bytesStored = writeBuffer->Store(s + totalBytesWritten, len - totalBytesWritten);
					if (writeBuffer->BytesLeft() == 0)
					{
						const size_t bytesToWrite = writeBuffer->BytesStored();
						size_t bytesWritten;
						writeStatus = Store(writeBuffer->Data(), bytesToWrite, &bytesWritten);
						writeBuffer->DataTaken();

						if (bytesToWrite != bytesWritten)
						{
							// Something went wrong
							break;
						}
					}
					totalBytesWritten += bytesStored;
				}
				while (writeStatus == FR_OK && totalBytesWritten != len);
			}

			if ((writeStatus != FR_OK) || (totalBytesWritten != len))
			{
				reprap.GetPlatform().Message(ErrorMessage, "Failed to write to file. Drive may be full.\n");
				return false;
			}
			return true;
		}

	case FileUseMode::invalidated:
	default:
		return 0;
	}
}

bool FileStore::Flush()
{
	switch (usageMode)
	{
	case FileUseMode::free:
		INTERNAL_ERROR;
		return false;

	case FileUseMode::readOnly:
		return true;

	case FileUseMode::readWrite:
		if (writeBuffer != nullptr)
		{
			const size_t bytesToWrite = writeBuffer->BytesStored();
			if (bytesToWrite != 0)
			{
				size_t bytesWritten;
				const FRESULT writeStatus = Store(writeBuffer->Data(), bytesToWrite, &bytesWritten);
				writeBuffer->DataTaken();

				if ((writeStatus != FR_OK) || (bytesToWrite != bytesWritten))
				{
					reprap.GetPlatform().Message(ErrorMessage, "Failed to write to file. Drive may be full.\n");
					return false;
				}
			}
		}
		return f_sync(&file) == FR_OK;

	case FileUseMode::invalidated:
	default:
		return false;
	}
}

// Truncate file at current file pointer
bool FileStore::Truncate()
{
	switch (usageMode)
	{
	case FileUseMode::free:
	case FileUseMode::readOnly:
		INTERNAL_ERROR;
		return false;

	case FileUseMode::readWrite:
		if (!Flush())
		{
			return false;
		}
		return f_truncate(&file) == FR_OK;

	case FileUseMode::invalidated:
	default:
		return false;
	}
}

// Return the file write time in milliseconds, and clear it
float FileStore::GetAndClearLongestWriteTime()
{
	const float ret = (float)longestWriteTime * StepClocksToMillis;
	longestWriteTime = 0;
	return ret;
}

#if 0	// not currently used

// Provide a cluster map for fast seeking. Needs _USE_FASTSEEK defined as 1 in conf_fatfs to make any difference.
// The first element of the table must be set to the total number of 32-bit entries in the table before calling this.
bool FileStore::SetClusterMap(uint32_t tbl[])
{
	switch (usageMode)
	{
	case FileUseMode::free:
		INTERNAL_ERROR;
		return false;

	case FileUseMode::readOnly:
	case FileUseMode::readWrite:
		{
			file.cltbl = tbl;
			const FRESULT ret = f_lseek(&file, CREATE_LINKMAP);
//			debugPrintf("ret %d need %u\n", (int)ret, tbl[0]);
			return ret == FR_OK;
		}

	case FileUseMode::invalidated:
	default:
		return false;
	}
}

#endif

// End