/*
 * flash_spi_hal.h
 *
 *  Created on: 3/06/2021
 *      Author: alexrayne <alexraynepe196@gmail.com>
  ------------------------------------------------------------------------
    Copyright (c) alexrayne

   All rights reserved.
   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions are met:
   - Redistributions of source code must retain the above copyright
     notice, this list of conditions and the following disclaimer.
   - Redistributions in binary form must reproduce the above copyright
     notice, this list of conditions and the following disclaimer in the
     documentation and/or other materials provided with the distribution.
   - Neither the name of ARM nor the names of its contributors may be used
     to endorse or promote products derived from this software without
     specific prior written permission.
   *
   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
   AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE
   LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
   CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
   SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
   INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
   CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
   ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
   POSSIBILITY OF SUCH DAMAGE. *
  ------------------------------------------------------------------------
      SPIFlash_GenDevice:
            //  девайс общего стиля - реализует базовый набор команд флешек с
            //          3,4 байтной адресацией
 */

#ifndef BSP_HAL_FLASH_SPI_HAL_H_
#define BSP_HAL_FLASH_SPI_HAL_H_

#include "flash_hal.h"
#include "ssp_hal.h"


// SPI флешки наследуют общий набор команд
enum FlashCmdId{
    // Basic commands flash/EE
      FLASH_CMD_WRDI      =  0x04     // Write Disable
    , FLASH_CMD_WREN      =  0x06     // Write Enable
    , FLASH_CMD_WRSR      =  0x01     // Write Register (Status-1, Configuration-1)
    , FLASH_CMD_RDSR      =  0x05     // Read Status Register-1
    , FLASH_CMD_READ      =  0x03     // Read (3- or 4-byte address)
    , FLASH_CMD_PP        =  0x02     // Page Program (3- or 4-byte address)

    // flash sectored commands
    , FLASH_CMD_FAST_READ =  0x0B     // Fast Read (3- or 4-byte address)
    , FLASH_CMD_4FAST_READ=  0x0C     // Fast Read 4-byte address
    , FLASH_CMD_SE_64K    =  0xD8     // Erase 64 kB or 256 kB (3- or 4-byte address)
    , FLASH_CMD_SE_32K    =  0x52     // Erase 32 kB
    , FLASH_CMD_SE_4K     =  0x20     // Erase sector
    , FLASH_CMD_BE        =  0x60     // Bulk Erase
    , FLASH_CMD_BE2       =  0xC7     // Bulk Erase (alternate command)
    , FLASH_CMD_RDID      =  0x9F     // Read ID (JEDEC Manufacturer ID and JEDEC CFI)
    , FLASH_CMD_RES       =  0xAB     // Read Electronic Signature
    , FLASH_CMD_RESET     =  0xF0     // Software Reset
};
enum StatusFlagID {
      FLASH_SR_WIP       =  (1 << 0) // Write in Progress
    , FLASH_SR_WEL       =  (1 << 1) // Write Enable Latch
    , FLASH_SR_E_ERR     =  (1 << 5) // Erase Error Occurred
};



struct SPIFlash_GenDevice;
typedef struct SPIFlash_GenDevice SPIFlash_GenDevice;

struct SPIFlash_GenDevice{
    FLASH_Device    flash;
    SSP_IODevice    ssp;

    // protected:
    uint8_t         CMD_SE;  //CMD_SE selected by chip conf

    // все сложные операции имеют контекст своей работы, он здесь
    union ctx_t {
        struct {
            //unsigned secsz;
            unsigned from;
            unsigned len;
        }erase;
    } ctx;
};


// текущий статус WEL, не обновляет статус флеши.
static inline
bool    flashspi_is_WEL(SPIFlash_GenDevice* this) {
    return flash_is_WEL(&this->flash);
};

// установка занятости флеша делается после отправки соответствующих операций,
//      позволяет видет актуальный статус флеша еще до опроса его статуса.
static inline
void  flashspi_force_busy(SPIFlash_GenDevice* this) {
    flash_force_busy(&this->flash);
};



DevResult flashspi_init(SPIFlash_GenDevice* this);
//DevResult flashspi_deinit(SPIFlash_GenDevice* this);



//////////////////////////////////////////////////////////////////////////////
//----------------------------------------------------------------------------
//  По умолчанию SR_WEL сбрасывается после большинства операций модификации.
//  Чтобы не дергать постоянно write_enable, этот класс кеширует
//  последнее состояние WEL, и сам подает флешке write_enable по всякую операцию
//  записи.
//  ИСПОЛЬЗОВАНИЕ:
//  перед началом изменения флеши надо один раз вызвать write_enable(true);
//  запрет записи делается явным вызовом write_enable(false)

typedef SPIFlash_GenDevice SPIFlash_WritableDevice;

DevResult wre_flashspi_init(SPIFlash_WritableDevice* this);

// все операции модификации снимают разрешение записи (WE) после выполнения.
//  Поэтому статус WE сделаю полем класса, и все операции модификации
//  предваряю разрешением записи в соответсвии с полем.
DevResult wre_flashspi_write_enable(SPIFlash_WritableDevice* self, bool onoff);



//////////////////////////////////////////////////////////////////////////////

// EEPROM device have no erase functions - they leave it dummy.
DevResult eepromspi_init(SPIFlash_GenDevice* this);
DevResult wre_eepromspi_init(SPIFlash_WritableDevice* this);



//////////////////////////////////////////////////////////////////////////////
/// низкоуровневые операции работы со страницами.
///  flashspi:read/write/erase работают через них.

PTResult flashspi_ask_page(FLASH_Device* self, void* dst, flash_page_t page, unsigned len);
PTResult flashspi_post_page(FLASH_Device* self, void* src, flash_page_t page, unsigned len);

DevResult flashspi_read_page(FLASH_Device* self, void* dst, flash_page_t page, unsigned len);
DevResult flashspi_write_page(FLASH_Device* self, void* src, flash_page_t page, unsigned len);

DevResult flashspi_erase_sec(FLASH_Device* self, void* dst, flash_page_t page, unsigned len);
DevResult flashspi_erase_64k(FLASH_Device* self, void* dst, flash_page_t page, unsigned len);

DevResult flashspi_wr_cmd1(FLASH_Device* self, flash_page_t page, uint8_t cmd);

//-------------------------------------------------------------------------------------------------
PTResult wre_flashspi_post_page(FLASH_Device* self, void* src, flash_addr_t page, unsigned len);
DevResult wre_flashspi_write_page(FLASH_Device* self, void* src, flash_addr_t page, unsigned len);
DevResult wre_flashspi_erase_sec(FLASH_Device* self, void* dst, flash_page_t page, unsigned len);
DevResult wre_flashspi_erase_64k(FLASH_Device* self, void* dst, flash_page_t page, unsigned len);

DevResult wre_flashspi_wr_cmd1(FLASH_Device* self, flash_page_t page, uint8_t cmd);



#endif /* BSP_HAL_FLASH_SPI_HAL_H_ */
