/*
 * 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();
}


//
// The task function
//
void eCxx_user_task()
{
#if 1

    // Process event
    eCxx::Application::processEvent();

#else

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

    // Initialize UART as needed
    static bool uartInitialized = false;

    if(!uartInitialized) {
        uartInitialized = true;
        App::uart().begin(9600);
    }

    // Test aligned memory allocation and deallocation
    auto testAlloc = [](size_t alignment, size_t size, char borderChar) -> char* {
        char* ptr = reinterpret_cast<char*>( aligned_malloc(alignment, size) );
        ptr[0       ] = borderChar;
        ptr[size - 1] = borderChar;
        return ptr;
    };

    char* pa = testAlloc( 4, 17, 'a');
    char* pb = testAlloc( 8, 17, 'b');
    char* pc = testAlloc(16, 17, 'c');

    App::uart().write('\n'  );
    App::uart().write('\n'  );

    App::uart().write(pa[ 0]);
    App::uart().write(' '   );
    App::uart().write(pa[16]);
    App::uart().write('\n'  );

    App::uart().write(pb[ 0]);
    App::uart().write(' '   );
    App::uart().write(pb[16]);
    App::uart().write('\n'  );

    App::uart().write(pc[ 0]);
    App::uart().write(' '   );
    App::uart().write(pc[16]);
    App::uart().write('\n'  );

    App::uart().write('\n'  );

    aligned_free(pa);
    aligned_free(pb);
    aligned_free(pc);

#endif
}
