/*
 * sci_boot.h
 *
 *  Created on: 27/04/2022
 *      Author: <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. *
 * ----------------------------------------------------------------------------------------------------------------
 *  host for Renesas RA2 chips SCI boot
 *  Хост загрузки Renesas RA2 чипа по sci
 */

#ifndef FIRMWARE_SCI_BOOT_H_
#define FIRMWARE_SCI_BOOT_H_


#include <stdint.h>
#include <OsProcess.h>
#include "hal_uart.h"
#include <project-conf.h>



//==============================================================================================================
/// размер буфера обмена с бутлоадером
#ifndef RBOOTSCI_FRAME_LOAD_LIMIT
#define RBOOTSCI_FRAME_LOAD_LIMIT 128
#endif


enum RBootSCIError{
    RBOOTSCI_OK = 0,
};
typedef int RBootError;


/// @ brief инициализировать демон загрузчика
void rboot_sci_init( UART_Device* uart );



//==============================================================================================================
//      контрольтекущей операции загнрузчика

/// @ brief ожидание завершения текущей операции
PT_THREAD( rboot_sci_wait() );

/// @ brief сбросить теущий процесс
PT_THREAD( rboot_sci_abort() );



typedef enum RBOOTState{
    RBOOT_STATE_INIT,
    RBOOT_STATE_0ACK,
    RBOOT_STATE_BOOT,
    RBOOT_STATE_AUTH,
    RBOOT_STATE_CMD,
} RBOOTState;

RBOOTState  rboot_state(void);



//==============================================================================================================
/// @brief переводит целевой чип в режим загрузки, и устанавливает связь
PT_THREAD( rboot_sci_start() );



typedef union RBootId{
    uint8_t     raw[16];
    uint32_t    w[4];
} RBootId;

PT_THREAD( rboot_sci_auth( const RBootId* id) );

PT_THREAD( rboot_sci_baud( unsigned baud) );


typedef struct RBOOTSign{
    unsigned    sci_freq;
    unsigned    baud_limit;
    uint8_t     area_num;
    uint8_t     chip_type;
    uint8_t     verl;
    uint8_t     verh;
} RBOOTSign;

PT_THREAD( rboot_sci_sign( RBOOTSign* y ) );



typedef enum RBOOTAreaType{
    RBOOT_AREA_CODE  = 0,        // (User area in Code flash)
    RBOOT_AREA_DATA  = 1,        // (User area in Data flash)
    RBOOT_AREA_CONF  = 2,        // (Config area)
} RBOOTAreaType;


typedef struct RBOOTArea{
    RBOOTAreaType  type;

    uintptr_t   start;
    uintptr_t   end;
    unsigned    sec_size;
    unsigned    page_size;
} RBOOTArea;

PT_THREAD( rboot_sci_area( RBOOTArea* y, unsigned n ) );



//==============================================================================================================
/** @brief процесс запущенной транзакции обмена.
 *  @return ptOK/ptNOK
 * */
PT_THREAD( rboot_sci_io( unsigned to_ticks ) );

enum {
    // время ответа на простую команду
    RBOOT_CMD_ACK_TO  = 2,
};


/** следующие операции используют примитив rboot_sci_io() для ожидания завершения.
 * */
void rboot_sci_ping();
void rboot_sci_erase( uintptr_t start, uintptr_t end );
void rboot_sci_write( uintptr_t start, uintptr_t end );
void rboot_sci_send( void* srcc, unsigned len );







//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///             BSP claimed API




#endif /* FIRMWARE_SCI_BOOT_H_ */
