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


//
// Helper functions
//
static void initSPIMasterAndUART()
{
    // Initialize SPI in master mode
    App::spi().begin(eCxx::SPI::SPIMode::Master);

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


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

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

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

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

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

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

    // Send the received data from slave 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();
    }
}
