Class that contain only FATFileSystem

Fork of USBFileSystem by Erik -

USBFileSystem.cpp

Committer:
mkilivan
Date:
2014-12-19
Revision:
6:eeeea7fbb0a2
Parent:
2:9af05743d551

File content as of revision 6:eeeea7fbb0a2:

#include "USBFileSystem.h"

#define USBWRITE_TIMEOUT 100

USBFileSystem::USBFileSystem(const char* n) : FATFileSystem_ds(n) {
  localFunction = NULL;
  local_count = 0;
}


FileHandle* USBFileSystem::open(const char* name, int flags){    
    char n[64];
    sprintf(n, "%d:/%s", _fsid, name);
    bool write = true;
    
    /* POSIX flags -> FatFS open mode */
    BYTE openmode;
    if (flags & O_RDWR) {
        openmode = FA_READ|FA_WRITE;
        localOpen(true);
    } else if(flags & O_WRONLY) {
        openmode = FA_WRITE;
        localOpen(true);
    } else {
        openmode = FA_READ;
        write = false;
    }
    if(flags & O_CREAT) {
        if(flags & O_TRUNC) {
            openmode |= FA_CREATE_ALWAYS;
        } else {
            openmode |= FA_OPEN_ALWAYS;
        }
    }
    
    FIL fh;
    FRESULT res = f_open(&fh, n, openmode);
    if (res) {
        if (write)
            local_count--;
        return NULL;
    }
    if (flags & O_APPEND) {
        f_lseek(&fh, fh.fsize);
    }
    return new USBFileHandle(fh, this, write);
}

bool USBFileSystem::localSafe( void ){
    return (local_count == 0);
}

int USBFileSystem::disk_status_fat() { 
    int retval = _disk_status();
    
    if (retval == 0)
        return 4;
    else 
        return retval;
 }
 
 int USBFileSystem::disk_status_msd() { 
    int retval = _disk_status();
    
    if (retval == 0)
        return 4;
    else 
        return retval;
 }
 
int USBFileSystem::disk_write(const uint8_t * data, uint64_t block) {
      int retval= _disk_write(data, block);

    return retval;
}

void USBFileSystem::localOpen(bool open) {
    if (open) {
        local_count++;
    } else {
        local_count--;
    }
    
    //Pseudo-IRQ
    if (open && (local_count == 1)) {
        if (localFunction != NULL) 
            (*localFunction)(false);
    }
    if (!open && (local_count == 0)) {
        if (localFunction != NULL) 
            (*localFunction)(true);
    }
}
    
void USBFileSystem::attachLocal(void (*function)(bool)) {
    localFunction = function;
}