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

    App::setOTAStartUserCallback( []() {
        App::uart().writeString( PGM_STR("\n\nOver-the-air (OTA) programming starts.\n") );
    } );

    App::setOTAEndUserCallback( []() {
        App::uart().writeString( PGM_STR("\nOver-the-air (OTA) programming is complete.\n\n") );
    } );

    App::setOTAErrorUserCallback( [](App::OTAError otaError) {
        App::uart().writeString   ( PGM_STR("\nOver-the-air (OTA) programming failed with OTAError #") );
        App::uart().writeDecString( static_cast<eCxx::uint8_t>(otaError)                               );
        App::uart().writeString   ( PGM_STR(".\n")                                                     );
        App::uart().writeString   ( PGM_STR("Extended OTA updater simplified error string = \"")       );
        App::uart().writeString   ( App::getExtendedOTAUpdaterSimplifiedErrorString()                  );
        App::uart().writeString   ( PGM_STR("\".\n\n")                                                 );
    } );


    // There is no need to enable the 74LVC541 buffers on the eCxx NodeMCU development board because
    // the UART is only used for communication with the host PC

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

    // NOTE : automatic baudrate detection can be done using this code
    //  const eCxx::uint32_t baudrate = App::uart().detectBaudrate(3000);
    //  App::uart().begin(baudrate ? baudrate : 9600);
}


//
// The task function
//
void eCxx_user_task()
{
    // Process event
    App::processEvent();

    // Read from UART and write it back
    auto& uart = App::uart();
    if( uart.canRead() ) {
        eCxx::uint8_t c;
        uart.read(c);

        uart.writeString( PGM_STR("Got: ") );
        uart.write(c);
        uart.write('\n');
    }
}
