/*
 * shimatta_sdio-driver.h
 *
 *  Created on: Apr 26, 2015
 *  Mario Hüttel
 */

#ifndef FATFS_SHIMATTA_SDIO_DRIVER_SHIMATTA_SDIO_DRIVER_H_
#define FATFS_SHIMATTA_SDIO_DRIVER_SHIMATTA_SDIO_DRIVER_H_

#include <diskio.h>
#include <stm32f4xx.h>


DSTATUS SDIO_status();
DSTATUS SDIO_initialize();
DRESULT SDIO_disk_read(BYTE *buff, DWORD sector, UINT count);
DRESULT SDIO_disk_write(const BYTE *buff, DWORD sector, UINT count);
DRESULT SDIO_disk_ioctl(BYTE cmd, void* buff);
DWORD	get_fattime();

#define CURRENT_STATE_IDLE 0
#define CURRENT_STATE_READY 1
#define CURRENT_STATE_IDENT 2
#define CURRENT_STATE_STBY 3
#define CURRENT_STATE_TRAN 4
#define CURRENT_STATE_DATA 5
#define CURRENT_STATE_RCV 6
#define CURRENT_STATE_PRG 7
#define CURRENT_STATE_DIS 8


typedef struct _CardStatus {
    uint32_t reserved           : 3;
    uint32_t AKE_SEQ_ERROR      : 1;
    uint32_t reserved_2         : 1;
    uint32_t APP_CMD            : 1;
    uint32_t reserved_3         : 2;
    uint32_t READY_FOR_DATA     : 1;
    uint32_t CURRENT_STATE      : 4;
    uint32_t ERASE_RESET        : 1;
    uint32_t CARD_ECC_DIABLED   : 1;
    uint32_t WP_ERASE_SKIP      : 1;
    uint32_t CSD_OVERWRITE      : 1;
    uint32_t reserved17         : 1;
    uint32_t reserved18         : 1;
    uint32_t ERROR              : 1;
    uint32_t CC_ERROR           : 1;
    uint32_t CARD_ECC_FAILED    : 1;
    uint32_t ILLEGAL_COMMAND    : 1;
    uint32_t COM_CRC_ERROR      : 1;
    uint32_t LOCK_UNLOCK_FAILED : 1;
    uint32_t CARD_IS_LOCKED     : 1;
    uint32_t WP_VIOLATION       : 1;
    uint32_t ERASE_PARAM        : 1;
    uint32_t ERASE_SEQ_ERROR    : 1;
    uint32_t BLOCK_LEN_ERROR    : 1;
    uint32_t ADDRESS_ERROR      : 1;
    uint32_t OUT_OF_RANGE       : 1;
}CardStatus_t;

#define CARD_SD 1
#define CARD_MMC 2//Never use. MMC not supported
#define CARD_NONE 0

typedef struct _SDInfo {
    uint32_t rca;
    uint8_t  type;
}SDInfo_t

typedef union _StatusConv {
    CardStatus_t statusstruct;
    uint32_t value;
}StatusConv_t;

//General Definitions
//Blocksize: 512 = 2^9 => 9
#define BLOCKSIZE 9     //9
//Hardware Flow: Prevents over- and underruns.
#define HW_FLOW   0     //0
//1 bit: 0
//4 bit: 1
#define BUSWIDTH  1     //1
//Initial Transfer CLK (ca. 400kHz)
#define INITCLK   120   //120
//Working CLK (Maximum)
#define WORKCLK   0     //0
//Data Timeout in CLK Cycles
#define DTIMEOUT  150   //150
//DMA Stream used for TX and RX DMA2 Stream 3 or 6 possible
#define DMASTREAM DMA2_Stream3



//Port Definitions

#define PORTCLKMASK (RCC_AHB1ENR_GPIODEN | RCC_AHB1ENR_GPIOCEN)

#define ALTFUNC     12

#define CLKPORT     GPIOC
#define D0PORT      GPIOC
#define D1PORT      GPIOC
#define D2PORT      GPIOC
#define D3PORT      GPIOC
#define CMDPORT     GPIOD

#define CLKPIN      12
#define D0PIN       8
#define D1PIN       9
#define D2PIN       10
#define D3PIN       11
#define CMDPIN      2

#endif /* FATFS_SHIMATTA_SDIO_DRIVER_SHIMATTA_SDIO_DRIVER_H_ */
