/*
 * 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 master mode
    App::spi().begin(eCxx::SPI::SPIMode::Master);

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


//
// The task function
//

// Comment this to use the four bytes variant
#define USE_32_BYTES

void eCxx_user_task()
{
    // Process event and delay
    static eCxx::uint32_t prvMillis = 0;
           eCxx::uint32_t curMillis = App::processEvent();
    if(curMillis - prvMillis < 500) return;
    else                            prvMillis = curMillis;

    // Send to slave
    App::spi().beginTransaction();
#ifdef USE_32_BYTES
    const eCxx::uint8_t d[32 + 2] = { 0x02, 0x00, '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ' ', 'F', 'r', 'o', 'm', ' ', 'M', 'a', 's', 't', 'e', 'r', ' ', '9', '7', '6', '5', '4', '3', '2', '1', '0' };
#else
    const eCxx::uint8_t d[ 4 + 1] = { 0x01, 'M', 's', 't', 'r' };
#endif
    App::spi().writeBytes( d, sizeof(d) );
    App::spi().endTransaction();

    // Delay for a while to give the slave time to send data
    App::delayMS(50);

    // Receive from slave
#ifdef USE_32_BYTES
    eCxx::uint8_t g[32] = { 0 };
#else
    eCxx::uint8_t g[ 4] = { 0 };
#endif

    App::spi().beginTransaction();
#ifdef USE_32_BYTES
    App::spi().write(0x03);
    App::spi().write(0x00);
#else
    App::spi().write(0x04);
#endif
    App::spi().transfer(g, sizeof(g) );
    App::spi().endTransaction();

    // Send the received data from slave to UART
    App::uart().writeBytesln(g, sizeof(g) );
    App::uart().flush();
}
