/*
 * 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 "NodeMCU_Common.h"


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

    // Enable the 74LVC541 buffers on the eCxx NodeMCU development board because
    // the SPI pins are buffered
    App::setPinMode  ( eCxx::NodeMCU::D0, eCxx::Application::PinMode::Output ); // GPIO16
    App::digitalWrite( eCxx::NodeMCU::D0, false                              ); // The buffers are active low

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

    // 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
    App::processEvent();

    // Simply return if there is nothing received from master
    if( !App::spi().canRead() ) return;

    // Receive from master
#ifdef USE_32_BYTES
    eCxx::uint8_t g[32] = { 0 };
#else
    eCxx::uint8_t g[ 4] = { 0 };
#endif
    App::spi().readFromMaster(g);

    // Send to master
#ifdef USE_32_BYTES
    const eCxx::uint8_t d[32] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ' ', 'S', 'l', 'a', 'v', 'e', ' ', 'R', 'e', 'p', 'l', 'y', ' ', '9', '7', '6', '5', '4', '3', '2', '1', '0' };
#else
    const eCxx::uint8_t d[4 ] = { 'S', 'l', 'v', 'e' };
#endif
    App::spi().writeToMaster(d);

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