/*
 * 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"


//
// Check the MCU
//
#ifndef __AVR_ARCH_X__
#error "this test application is meant for AVRX platform only"
#endif


//
// For convenience
//
using eCxx::Logic;


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

    // Initialize SPI in master mode
    App::spi().begin(eCxx::SPI::SPIMode::Master);

    //
    // ===== Manchester encoder test using CCL =====
    //
    auto& logic = App::logic();

    // ----- Create a Manchester encoder using SPI0 and LUT2 (XOR between MOSI and SCK) -----
    // Inp Out
    // 210
    // 000 0
    // 001 0 (disabled)
    // 010 1
    // 011 0 (disabled)
    // 100 1
    // 101 0 (disabled)
    // 110 0
    // 111 0 (disabled)
    logic.lut[2].enabled    = true;
    logic.lut[2].input[0]   = Logic::Input::Disabled;
    logic.lut[2].input[1]   = Logic::Input::SPI0_Output; // SPI0 MOSI
    logic.lut[2].input[2]   = Logic::Input::SPI0_Output; // SPI0 SCK
    logic.lut[2].output     = Logic::Output::Alternate;
    logic.lut[2].truthTable = 0b00010100;

    // ----- Start the CCL -----
    logic.begin();
}


//
// The task function
//
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 SPI data so that it will generate the Manchester-encoded output
    App::spi().beginTransaction(125000UL);
    for(uint8_t i = 0; i < 128; ++i) App::spi().write(0x00);
    for(uint8_t i = 0; i < 128; ++i) App::spi().write(0xFF);
    App::spi().endTransaction();
}
