/*
 * Copyright (C) 2020-2021 Aloysius Indrayanto
 *
 * This file is part of the eCxx library, see LICENSE file for the license details.
 */


#include <eCxx/eCxx.h>

#include "AVR_Common.h"


//
// The init function
//
void eCxx_user_init()
{
    // Initialize application
    initBasicAVRApp();

    // Initialize SPI in slave mode
    App::spi().begin(eCxx::SPI::SPIMode::Slave);

    // Initialize UART
    App::uart().begin(9600);
}


//
// The task function
//
void eCxx_user_task()
{
    // Process event
    App::processEvent();

    // Rx buffer
    static eCxx::RingBuffer<eCxx::uint8_t, 16> rxBuff;

    // Begin SPI transaction
    App::spi().beginTransaction();

    // Receive from master
    eCxx::uint8_t g = 0;
    for(;;) {
        if( !App::spi().transfer(g, 0) ) break;
        if( !g ) break;
        rxBuff.put(g);
    }

    // Do not send back to master if no data has been received
    if( rxBuff.empty() ) return;

    // Send to master
    App::spi().writeString( PGM_STR("! From Slave !") );
    App::spi().write(0);
    App::delayMS(5);

    // End SPI transaction
    App::spi().endTransaction();

    // Send the received data from master to UART
    if( !rxBuff.empty() ) {
        App::uart().writeStringln(
            reinterpret_cast<const char*>( rxBuff.data() ),
            reinterpret_cast<const char*>( rxBuff.data() ) + rxBuff.size()
        );
        App::uart().flush();
        rxBuff.clear();
    }
}
