#include "tusb.h"
#if CFG_TUH_MSC
#include "ffconf.h"
#include "diskio.h"
static DSTATUS disk_state[CFG_TUH_DEVICE_MAX];
static DRESULT wait_for_io_complete(uint8_t usb_addr)
{
while ( !tuh_msc_ready(usb_addr) )
{
#if CFG_TUSB_OS != OPT_OS_NONE
osal_task_delay(10);
#endif
}
return RES_OK;
}
void diskio_init(void)
{
memset(disk_state, STA_NOINIT, CFG_TUH_DEVICE_MAX);
}
DSTATUS disk_initialize ( BYTE pdrv )
{
disk_state[pdrv] &= (~STA_NOINIT); return disk_state[pdrv];
}
void disk_deinitialize ( BYTE pdrv )
{
disk_state[pdrv] |= STA_NOINIT; }
DSTATUS disk_status (BYTE pdrv)
{
return disk_state[pdrv];
}
DRESULT disk_read (BYTE pdrv, BYTE*buff, DWORD sector, BYTE count)
{
uint8_t usb_addr = pdrv+1;
if ( TUSB_ERROR_NONE != tuh_msc_read10(usb_addr, 0, buff, sector, count) ) return RES_ERROR;
return wait_for_io_complete(usb_addr);
}
DRESULT disk_write (BYTE pdrv, const BYTE* buff, DWORD sector, BYTE count)
{
uint8_t usb_addr = pdrv+1;
if ( TUSB_ERROR_NONE != tuh_msc_write10(usb_addr, 0, buff, sector, count) ) return RES_ERROR;
return wait_for_io_complete(usb_addr);
}
DRESULT disk_ioctl (BYTE pdrv, BYTE cmd, void* buff)
{
(void) buff; (void) pdrv;
if (cmd != CTRL_SYNC) return RES_ERROR;
return RES_OK;
}
static inline uint8_t month2number(char* p_ch)
{
char const * const month_str[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
for(uint8_t i=0; i<12; i++)
{
if ( strncmp(p_ch, month_str[i], 3) == 0 ) return i+1;
}
return 1;
}
static inline uint8_t c2i(char ch)
{
return ch - '0';
}
DWORD get_fattime (void)
{
union {
struct {
DWORD second : 5;
DWORD minute : 6;
DWORD hour : 5;
DWORD day_in_month : 5;
DWORD month : 4;
DWORD year : 7;
};
DWORD value;
} timestamp;
char compile_date[] = __DATE__; char* p_ch;
p_ch = strtok (compile_date, " ");
timestamp.month = month2number(p_ch);
p_ch = strtok (NULL, " ");
timestamp.day_in_month = 10*c2i(p_ch[0])+ c2i(p_ch[1]);
p_ch = strtok (NULL, " ");
timestamp.year = 1000*c2i(p_ch[0]) + 100*c2i(p_ch[1]) + 10*c2i(p_ch[2]) + c2i(p_ch[3]) - 1980;
static uint8_t sec = 0;
static uint8_t min = 0;
static uint8_t hour = 0;
if (++sec >= 60)
{
sec = 0;
if (++min >= 60)
{
min = 0;
if (++hour >= 24)
{
hour = 0; }
}
}
timestamp.hour = hour;
timestamp.minute = min;
timestamp.second = sec;
return timestamp.value;
}
#endif