Commit b92d3e1f authored by Damien George's avatar Damien George
Browse files

stmhal: Add fatfs support, working with flash and SD card.

parent 9e5ea4d7
......@@ -10,7 +10,7 @@ CMSIS_DIR=cmsis
HAL_DIR=hal
USBDEV_DIR=usbdev
#USBHOST_DIR=usbhost
#FATFS_DIR=fatfs
FATFS_DIR=fatfs
#CC3K_DIR=cc3k
DFU=../tools/dfu.py
......@@ -23,7 +23,7 @@ INC += -I$(CMSIS_DIR)/devinc
INC += -I$(HAL_DIR)/inc
INC += -I$(USBDEV_DIR)/core/inc -I$(USBDEV_DIR)/class/cdc/inc
#INC += -I$(USBHOST_DIR)
#INC += -I$(FATFS_DIR)
INC += -I$(FATFS_DIR)/src
#INC += -I$(CC3K_DIR)
CFLAGS_CORTEX_M4 = -mthumb -mtune=cortex-m4 -mabi=aapcs-linux -mcpu=cortex-m4 -mfpu=fpv4-sp-d16 -mfloat-abi=hard -fsingle-precision-constant -Wdouble-promotion
......@@ -80,7 +80,9 @@ SRC_C = \
rtc.c \
flash.c \
storage.c \
file.c \
sdcard.c \
diskio.c \
# lcd.c \
# servo.c \
......@@ -89,7 +91,6 @@ SRC_C = \
# audio.c \
# i2c.c \
# adc.c \
# file.c \
# pybwlan.c \
SRC_S = \
......@@ -137,10 +138,9 @@ SRC_USBDEV = $(addprefix $(USBDEV_DIR)/,\
usbd_storage_msd.c \
)
SRC_FATFS = $(addprefix $(FATFS_DIR)/,\
SRC_FATFS = $(addprefix $(FATFS_DIR)/src/,\
ff.c \
diskio.c \
ccsbcs.c \
option/ccsbcs.c \
)
SRC_CC3K = $(addprefix $(CC3K_DIR)/,\
......@@ -162,9 +162,7 @@ OBJ += $(addprefix $(BUILD)/, $(SRC_C:.c=.o))
OBJ += $(addprefix $(BUILD)/, $(SRC_S:.s=.o))
OBJ += $(addprefix $(BUILD)/, $(SRC_HAL:.c=.o))
OBJ += $(addprefix $(BUILD)/, $(SRC_USBDEV:.c=.o))
#OBJ += $(addprefix $(BUILD)/, $(SRC_STMUSBD:.c=.o))
#OBJ += $(addprefix $(BUILD)/, $(SRC_STMUSBH:.c=.o))
#OBJ += $(addprefix $(BUILD)/, $(SRC_FATFS:.c=.o))
OBJ += $(addprefix $(BUILD)/, $(SRC_FATFS:.c=.o))
#OBJ += $(addprefix $(BUILD)/, $(SRC_CC3K:.c=.o))
OBJ += $(BUILD)/pins_$(BOARD).o
......
/*-----------------------------------------------------------------------*/
/* Low level disk I/O module skeleton for FatFs (C)ChaN, 2013 */
/*-----------------------------------------------------------------------*/
/* If a working storage control module is available, it should be */
/* attached to the FatFs via a glue function rather than modifying it. */
/* This is an example of glue functions to attach various exsisting */
/* storage control module to the FatFs module with a defined API. */
/*-----------------------------------------------------------------------*/
#include <stdint.h>
#include <stdio.h>
#include "ff.h" /* FatFs lower layer API */
#include "diskio.h" /* FatFs lower layer API */
#include "misc.h"
#include "storage.h"
#include "sdcard.h"
PARTITION VolToPart[] = {
{0, 1}, // Logical drive 0 ==> Physical drive 0, 1st partition
{1, 0}, // Logical drive 1 ==> Physical drive 1 (auto detection)
/*
{0, 2}, // Logical drive 2 ==> Physical drive 0, 2nd partition
{0, 3}, // Logical drive 3 ==> Physical drive 0, 3rd partition
*/
};
/* Definitions of physical drive number for each media */
#define PD_FLASH (0)
#define PD_SDCARD (1)
/*-----------------------------------------------------------------------*/
/* Initialize a Drive */
/*-----------------------------------------------------------------------*/
DSTATUS disk_initialize (
BYTE pdrv /* Physical drive nmuber (0..) */
)
{
switch (pdrv) {
case PD_FLASH:
storage_init();
return 0;
case PD_SDCARD:
if (!sdcard_power_on()) {
return STA_NODISK;
}
// TODO return STA_PROTECT if SD card is read only
return 0;
}
return STA_NOINIT;
}
/*-----------------------------------------------------------------------*/
/* Get Disk Status */
/*-----------------------------------------------------------------------*/
DSTATUS disk_status (
BYTE pdrv /* Physical drive nmuber (0..) */
)
{
switch (pdrv) {
case PD_FLASH :
// flash is ready
return 0;
case PD_SDCARD:
// TODO return STA_PROTECT if SD card is read only
return 0;
}
return STA_NOINIT;
}
/*-----------------------------------------------------------------------*/
/* Read Sector(s) */
/*-----------------------------------------------------------------------*/
DRESULT disk_read (
BYTE pdrv, /* Physical drive nmuber (0..) */
BYTE *buff, /* Data buffer to store read data */
DWORD sector, /* Sector address (LBA) */
UINT count /* Number of sectors to read (1..128) */
)
{
switch (pdrv) {
case PD_FLASH:
for (int i = 0; i < count; i++) {
if (!storage_read_block(buff + i * FLASH_BLOCK_SIZE, sector + i)) {
return RES_ERROR;
}
}
return RES_OK;
case PD_SDCARD:
if (!sdcard_read_blocks(buff, sector, count)) {
return RES_ERROR;
}
return RES_OK;
}
return RES_PARERR;
}
/*-----------------------------------------------------------------------*/
/* Write Sector(s) */
/*-----------------------------------------------------------------------*/
#if _USE_WRITE
DRESULT disk_write (
BYTE pdrv, /* Physical drive nmuber (0..) */
const BYTE *buff, /* Data to be written */
DWORD sector, /* Sector address (LBA) */
UINT count /* Number of sectors to write (1..128) */
)
{
switch (pdrv) {
case PD_FLASH:
for (int i = 0; i < count; i++) {
if (!storage_write_block(buff + i * FLASH_BLOCK_SIZE, sector + i)) {
return RES_ERROR;
}
}
return RES_OK;
case PD_SDCARD:
if (!sdcard_write_blocks(buff, sector, count)) {
return RES_ERROR;
}
return RES_OK;
}
return RES_PARERR;
}
#endif
/*-----------------------------------------------------------------------*/
/* Miscellaneous Functions */
/*-----------------------------------------------------------------------*/
#if _USE_IOCTL
DRESULT disk_ioctl (
BYTE pdrv, /* Physical drive nmuber (0..) */
BYTE cmd, /* Control code */
void *buff /* Buffer to send/receive control data */
)
{
switch (pdrv) {
case PD_FLASH:
switch (cmd) {
case CTRL_SYNC:
storage_flush();
return RES_OK;
case GET_BLOCK_SIZE:
*((DWORD*)buff) = 1; // high-level sector erase size in units of the small (512) block size
return RES_OK;
}
break;
case PD_SDCARD:
switch (cmd) {
case CTRL_SYNC:
return RES_OK;
case GET_BLOCK_SIZE:
*((DWORD*)buff) = 1; // high-level sector erase size in units of the small (512) block size
return RES_OK;
}
break;
}
return RES_PARERR;
}
#endif
DWORD get_fattime (
void
)
{
// TODO replace with call to RTC
int year = 2013;
int month = 10;
int day = 12;
int hour = 21;
int minute = 42;
int second = 13;
return ((year - 1980) << 25) | ((month) << 21) | ((day) << 16) | ((hour) << 11) | ((minute) << 5) | (second / 2);
}
/*-----------------------------------------------------------------------
/ Low level disk interface modlue include file (C)ChaN, 2013
/-----------------------------------------------------------------------*/
#ifndef _DISKIO_DEFINED
#define _DISKIO_DEFINED
#ifdef __cplusplus
extern "C" {
#endif
#define _USE_WRITE 1 /* 1: Enable disk_write function */
#define _USE_IOCTL 1 /* 1: Enable disk_ioctl fucntion */
#include "integer.h"
/* Status of Disk Functions */
typedef BYTE DSTATUS;
/* Results of Disk Functions */
typedef enum {
RES_OK = 0, /* 0: Successful */
RES_ERROR, /* 1: R/W Error */
RES_WRPRT, /* 2: Write Protected */
RES_NOTRDY, /* 3: Not Ready */
RES_PARERR /* 4: Invalid Parameter */
} DRESULT;
/*---------------------------------------*/
/* Prototypes for disk control functions */
DSTATUS disk_initialize (BYTE pdrv);
DSTATUS disk_status (BYTE pdrv);
DRESULT disk_read (BYTE pdrv, BYTE*buff, DWORD sector, UINT count);
DRESULT disk_write (BYTE pdrv, const BYTE* buff, DWORD sector, UINT count);
DRESULT disk_ioctl (BYTE pdrv, BYTE cmd, void* buff);
DWORD get_fattime (void);
/* Disk Status Bits (DSTATUS) */
#define STA_NOINIT 0x01 /* Drive not initialized */
#define STA_NODISK 0x02 /* No medium in the drive */
#define STA_PROTECT 0x04 /* Write protected */
/* Command code for disk_ioctrl fucntion */
/* Generic command (used by FatFs) */
#define CTRL_SYNC 0 /* Flush disk cache (for write functions) */
#define GET_SECTOR_COUNT 1 /* Get media size (for only f_mkfs()) */
#define GET_SECTOR_SIZE 2 /* Get sector size (for multiple sector size (_MAX_SS >= 1024)) */
#define GET_BLOCK_SIZE 3 /* Get erase block size (for only f_mkfs()) */
#define CTRL_ERASE_SECTOR 4 /* Force erased a block of sectors (for only _USE_ERASE) */
/* Generic command (not used by FatFs) */
#define CTRL_POWER 5 /* Get/Set power status */
#define CTRL_LOCK 6 /* Lock/Unlock media removal */
#define CTRL_EJECT 7 /* Eject media */
#define CTRL_FORMAT 8 /* Create physical format on the media */
/* MMC/SDC specific ioctl command */
#define MMC_GET_TYPE 10 /* Get card type */
#define MMC_GET_CSD 11 /* Get CSD */
#define MMC_GET_CID 12 /* Get CID */
#define MMC_GET_OCR 13 /* Get OCR */
#define MMC_GET_SDSTAT 14 /* Get SD status */
/* ATA/CF specific ioctl command */
#define ATA_GET_REV 20 /* Get F/W revision */
#define ATA_GET_MODEL 21 /* Get model name */
#define ATA_GET_SN 22 /* Get serial number */
/* MMC card type flags (MMC_GET_TYPE) */
#define CT_MMC 0x01 /* MMC ver 3 */
#define CT_SD1 0x02 /* SD ver 1 */
#define CT_SD2 0x04 /* SD ver 2 */
#define CT_SDC (CT_SD1|CT_SD2) /* SD */
#define CT_BLOCK 0x08 /* Block addressing */
#ifdef __cplusplus
}
#endif
#endif
/*---------------------------------------------------------------------------/
/ FatFs - FAT file system module configuration file R0.10 (C)ChaN, 2013
/----------------------------------------------------------------------------/
/
/ CAUTION! Do not forget to make clean the project after any changes to
/ the configuration options.
/
/----------------------------------------------------------------------------*/
#ifndef _FFCONF
#define _FFCONF 80960 /* Revision ID */
#include "mpconfigport.h"
/*---------------------------------------------------------------------------/
/ Functions and Buffer Configurations
/----------------------------------------------------------------------------*/
#define _FS_TINY 1 /* 0:Normal or 1:Tiny */
/* When _FS_TINY is set to 1, FatFs uses the sector buffer in the file system
/ object instead of the sector buffer in the individual file object for file
/ data transfer. This reduces memory consumption 512 bytes each file object. */
#define _FS_READONLY 0 /* 0:Read/Write or 1:Read only */
/* Setting _FS_READONLY to 1 defines read only configuration. This removes
/ writing functions, f_write(), f_sync(), f_unlink(), f_mkdir(), f_chmod(),
/ f_rename(), f_truncate() and useless f_getfree(). */
#define _FS_MINIMIZE 0 /* 0 to 3 */
/* The _FS_MINIMIZE option defines minimization level to remove API functions.
/
/ 0: All basic functions are enabled.
/ 1: f_stat(), f_getfree(), f_unlink(), f_mkdir(), f_chmod(), f_utime(),
/ f_truncate() and f_rename() function are removed.
/ 2: f_opendir(), f_readdir() and f_closedir() are removed in addition to 1.
/ 3: f_lseek() function is removed in addition to 2. */
#define _USE_STRFUNC 0 /* 0:Disable or 1-2:Enable */
/* To enable string functions, set _USE_STRFUNC to 1 or 2. */
#define _USE_MKFS 1 /* 0:Disable or 1:Enable */
/* To enable f_mkfs() function, set _USE_MKFS to 1 and set _FS_READONLY to 0 */
#define _USE_FASTSEEK 0 /* 0:Disable or 1:Enable */
/* To enable fast seek feature, set _USE_FASTSEEK to 1. */
#define _USE_LABEL 0 /* 0:Disable or 1:Enable */
/* To enable volume label functions, set _USE_LAVEL to 1 */
#define _USE_FORWARD 0 /* 0:Disable or 1:Enable */
/* To enable f_forward() function, set _USE_FORWARD to 1 and set _FS_TINY to 1. */
/*---------------------------------------------------------------------------/
/ Locale and Namespace Configurations
/----------------------------------------------------------------------------*/
#define _CODE_PAGE (MICROPY_LFN_CODE_PAGE)
/* The _CODE_PAGE specifies the OEM code page to be used on the target system.
/ Incorrect setting of the code page can cause a file open failure.
/
/ 932 - Japanese Shift-JIS (DBCS, OEM, Windows)
/ 936 - Simplified Chinese GBK (DBCS, OEM, Windows)
/ 949 - Korean (DBCS, OEM, Windows)
/ 950 - Traditional Chinese Big5 (DBCS, OEM, Windows)
/ 1250 - Central Europe (Windows)
/ 1251 - Cyrillic (Windows)
/ 1252 - Latin 1 (Windows)
/ 1253 - Greek (Windows)
/ 1254 - Turkish (Windows)
/ 1255 - Hebrew (Windows)
/ 1256 - Arabic (Windows)
/ 1257 - Baltic (Windows)
/ 1258 - Vietnam (OEM, Windows)
/ 437 - U.S. (OEM)
/ 720 - Arabic (OEM)
/ 737 - Greek (OEM)
/ 775 - Baltic (OEM)
/ 850 - Multilingual Latin 1 (OEM)
/ 858 - Multilingual Latin 1 + Euro (OEM)
/ 852 - Latin 2 (OEM)
/ 855 - Cyrillic (OEM)
/ 866 - Russian (OEM)
/ 857 - Turkish (OEM)
/ 862 - Hebrew (OEM)
/ 874 - Thai (OEM, Windows)
/ 1 - ASCII (Valid for only non-LFN cfg.)
*/
#define _USE_LFN (MICROPY_ENABLE_LFN) /* 0 to 3 */
#define _MAX_LFN 255 /* Maximum LFN length to handle (12 to 255) */
/* The _USE_LFN option switches the LFN feature.
/
/ 0: Disable LFN feature. _MAX_LFN has no effect.
/ 1: Enable LFN with static working buffer on the BSS. Always NOT reentrant.
/ 2: Enable LFN with dynamic working buffer on the STACK.
/ 3: Enable LFN with dynamic working buffer on the HEAP.
/
/ To enable LFN feature, Unicode handling functions ff_convert() and ff_wtoupper()
/ function must be added to the project.
/ The LFN working buffer occupies (_MAX_LFN + 1) * 2 bytes. When use stack for the
/ working buffer, take care on stack overflow. When use heap memory for the working
/ buffer, memory management functions, ff_memalloc() and ff_memfree(), must be added
/ to the project. */
#define _LFN_UNICODE 0 /* 0:ANSI/OEM or 1:Unicode */
/* To switch the character encoding on the FatFs API to Unicode, enable LFN feature
/ and set _LFN_UNICODE to 1. */
#define _STRF_ENCODE 3 /* 0:ANSI/OEM, 1:UTF-16LE, 2:UTF-16BE, 3:UTF-8 */
/* When Unicode API is enabled, character encoding on the all FatFs API is switched
/ to Unicode. This option selects the character encoding on the file to be read/written
/ via string functions, f_gets(), f_putc(), f_puts and f_printf().
/ This option has no effect when _LFN_UNICODE is 0. */
#define _FS_RPATH 0 /* 0 to 2 */
/* The _FS_RPATH option configures relative path feature.
/
/ 0: Disable relative path feature and remove related functions.
/ 1: Enable relative path. f_chdrive() and f_chdir() function are available.
/ 2: f_getcwd() function is available in addition to 1.
/
/ Note that output of the f_readdir() fnction is affected by this option. */
/*---------------------------------------------------------------------------/
/ Drive/Volume Configurations
/----------------------------------------------------------------------------*/
#define _VOLUMES 2
/* Number of volumes (logical drives) to be used. */
#define _MULTI_PARTITION 1 /* 0:Single partition, 1:Enable multiple partition */
/* When set to 0, each volume is bound to the same physical drive number and
/ it can mount only first primaly partition. When it is set to 1, each volume
/ is tied to the partitions listed in VolToPart[]. */
#define _MAX_SS 512 /* 512, 1024, 2048 or 4096 */
/* Maximum sector size to be handled.
/ Always set 512 for memory card and hard disk but a larger value may be
/ required for on-board flash memory, floppy disk and optical disk.
/ When _MAX_SS is larger than 512, it configures FatFs to variable sector size
/ and GET_SECTOR_SIZE command must be implemented to the disk_ioctl() function. */
#define _USE_ERASE 0 /* 0:Disable or 1:Enable */
/* To enable sector erase feature, set _USE_ERASE to 1. Also CTRL_ERASE_SECTOR command
/ should be added to the disk_ioctl() function. */
#define _FS_NOFSINFO 0 /* 0 or 1 */
/* If you need to know the correct free space on the FAT32 volume, set this
/ option to 1 and f_getfree() function at first time after volume mount will
/ force a full FAT scan.
/
/ 0: Load all informations in the FSINFO if available.
/ 1: Do not trust free cluster count in the FSINFO.
*/
/*---------------------------------------------------------------------------/
/ System Configurations
/----------------------------------------------------------------------------*/
#define _WORD_ACCESS 0 /* 0 or 1 */
/* The _WORD_ACCESS option is an only platform dependent option. It defines
/ which access method is used to the word data on the FAT volume.
/
/ 0: Byte-by-byte access. Always compatible with all platforms.
/ 1: Word access. Do not choose this unless under both the following conditions.
/
/ * Byte order on the memory is little-endian.
/ * Address miss-aligned word access is always allowed for all instructions.
/
/ If it is the case, _WORD_ACCESS can also be set to 1 to improve performance
/ and reduce code size.
*/
/* A header file that defines sync object types on the O/S, such as
/ windows.h, ucos_ii.h and semphr.h, must be included prior to ff.h. */
#define _FS_REENTRANT 0 /* 0:Disable or 1:Enable */
#define _FS_TIMEOUT 1000 /* Timeout period in unit of time ticks */
#define _SYNC_t HANDLE /* O/S dependent type of sync object. e.g. HANDLE, OS_EVENT*, ID and etc.. */
/* The _FS_REENTRANT option switches the re-entrancy (thread safe) of the FatFs module.
/
/ 0: Disable re-entrancy. _SYNC_t and _FS_TIMEOUT have no effect.
/ 1: Enable re-entrancy. Also user provided synchronization handlers,
/ ff_req_grant(), ff_rel_grant(), ff_del_syncobj() and ff_cre_syncobj()
/ function must be added to the project. */
#define _FS_LOCK 0 /* 0:Disable or >=1:Enable */
/* To enable file lock control feature, set _FS_LOCK to 1 or greater.
The value defines how many files can be opened simultaneously. */
#endif /* _FFCONFIG */
#include <stdio.h>
#include "misc.h"
#include "mpconfig.h"
#include "qstr.h"
#include "obj.h"
#include "file.h"
#include "ff.h"
typedef struct _pyb_file_obj_t {
mp_obj_base_t base;
FIL fp;
} pyb_file_obj_t;
void file_obj_print(void (*print)(void *env, const char *fmt, ...), void *env, mp_obj_t self_in, mp_print_kind_t kind) {
printf("<file %p>", self_in);
}
mp_obj_t file_obj_read(mp_obj_t self_in, mp_obj_t arg) {
pyb_file_obj_t *self = self_in;
int n = mp_obj_get_int(arg);
byte *buf = m_new(byte, n);
UINT n_out;
f_read(&self->fp, buf, n, &n_out);
return mp_obj_new_str(buf, n_out, false);
}
mp_obj_t file_obj_write(mp_obj_t self_in, mp_obj_t arg) {
pyb_file_obj_t *self = self_in;
uint l;
const char *s = mp_obj_str_get_data(arg, &l);
UINT n_out;
FRESULT res = f_write(&self->fp, s, l, &n_out);
if (res != FR_OK) {
printf("File error: could not write to file; error code %d\n", res);
} else if (n_out != l) {
printf("File error: could not write all data to file; wrote %d / %d bytes\n", n_out, l);
}
return mp_const_none;
}
mp_obj_t file_obj_close(mp_obj_t self_in) {
pyb_file_obj_t *self = self_in;
f_close(&self->fp);
return mp_const_none;
}
static MP_DEFINE_CONST_FUN_OBJ_2(file_obj_read_obj, file_obj_read);
static MP_DEFINE_CONST_FUN_OBJ_2(file_obj_write_obj, file_obj_write);
static MP_DEFINE_CONST_FUN_OBJ_1(file_obj_close_obj, file_obj_close);
// TODO gc hook to close the file if not already closed
static const mp_method_t file_methods[] = {
{ "read", &file_obj_read_obj },
{ "write", &file_obj_write_obj },
{ "close", &file_obj_close_obj },
{NULL, NULL},
};
static const mp_obj_type_t file_obj_type = {
{ &mp_type_type },
.name = MP_QSTR_File,
.print = file_obj_print,
.methods = file_methods,
};
STATIC mp_obj_t pyb_io_open(mp_obj_t o_filename, mp_obj_t o_mode) {
const char *filename = mp_obj_str_get_str(o_filename);
const char *mode = mp_obj_str_get_str(o_mode);
pyb_file_obj_t *self = m_new_obj(pyb_file_obj_t);
self->base.type = &file_obj_type;
if (mode[0] == 'r') {
// open for reading
FRESULT res = f_open(&self->fp, filename, FA_READ);
if (res != FR_OK) {
printf("FileNotFoundError: [Errno 2] No such file or directory: '%s'\n", filename);
return mp_const_none;
}
} else if (mode[0] == 'w') {
// open for writing, truncate the file first
FRESULT res = f_open(&self->fp, filename, FA_WRITE | FA_CREATE_ALWAYS);
if (res != FR_OK) {
printf("?FileError: could not create file: '%s'\n", filename);
return mp_const_none;
}
} else {
printf("ValueError: invalid mode: '%s'\n", mode);
return mp_const_none;
}
return self;