/*
 * winbond.cpp
 *
 *  Created on: 15 янв. 2019 г.
 *      Author: alexrayne
 *-----------------------------------------------------------------------------
 * драйвера чипов флеш:
 *  W25Q64 - winbond 64M spi/qpi flash
 */

#include <compiler-port.h>
#include <string.h>
#include "x25_flash.hpp"
#include "x25_flash.h"


#include <trace_probes.h>

#ifndef trace_ssp_wr
trace_need(ssp_wr)
trace_need(ssp_rd)
#endif


//-------------------  W25Q64  ------------------------------------
//static
const FLASH_SPI_x25::ID_t   FLASH_SPI_x25::ID_W25Q64 = {
              struct_field(vendor_id)   FLASH_SPI_x25::idWINBOND
            , struct_field(chip_id)     FLASH_SPI_x25::idW25Q64_SPI
            };

#define KB (1<<10)
//static
const FLASH_SPI_x25::Describe   FLASH_SPI_x25::info_W25Q64 = {
      struct_field(nb_sectors)          W25Q64_SECTORS
    , struct_field(nb_pages_in_sector)  (W25Q64_SEC_SIZE/W25Q64_PAGE_SIZE)
    , struct_field(page_size)           W25Q64_PAGE_SIZE
    //  0.7 ..3 ms
    , struct_field(burn_page_ticks)     ( OSTicksMS(3) )
    , struct_field(erase_ticks)         OSTicksMS(400)
    , struct_field(erase_all_ticks)     OSTicksMS(100000)
};


FLASH_SPI_x25::FLASH_SPI_x25(dev_name name)
: inherited(name)
{
    assign_info( &info_W25Q64 );
    //mode(mode_default_8bit);
    mode(SSP_MODE_W25Q64);
    style(addr3BYTE | addrLE);
    CMD_SE = CMD_SE_4K;
}



//virtual
DevResult FLASH_SPI_x25::init(){
    //return inherited::init();
    mode(SSP_MODE_W25Q64);
    style(addr3BYTE | addrLE);
    return DEV_OK;
};

//virtual
DevResult FLASH_SPI_x25::deinit(){
    return inherited::deinit();
}


// bound - начальная подготовка флеши к работе, сверка ID, и параметров
//virtual
DevResult FLASH_SPI_x25::bind(){
    ID_t    id;
    cs_hold(true);
    trace_ssp_wr_on();
    DevResult ok = postByte(CMD_RDID);
    trace_ssp_wr_off();
    trace_ssp_rd_on();
    cs_hold(false);
    ok = readData(id.raw, id.idLEN);
    trace_ssp_rd_off();
    if (ok != id.idLEN)
        return ok;
    ok = memcmp(id.raw, ID_W25Q64.raw, id.idLEN);
    if (ok == 0)
        return DEV_OK;
    return DEV_NO_SUPPORT_ID_ERR;

}



