/*
 * 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( []() {
        // Turn off BuiltinLED2 here (BuiltinLED1 will be handled by the system)
        App::setPinMode  ( eCxx::NodeMCU::BuiltinLED2, eCxx::Application::PinMode::Output );
        App::digitalWrite( eCxx::NodeMCU::BuiltinLED2, true                               ); // The LED is active low
    } );

    // There is no need to enable the 74LVC541 buffers on the eCxx NodeMCU development board because
    // the built-in LEDs are used for the PWM outputs

    // Initialize both built-in LEDs for PWM output
    App::setPinMode( eCxx::NodeMCU::BuiltinLED1, eCxx::Application::PinMode::Output );
    App::setPinMode( eCxx::NodeMCU::BuiltinLED2, eCxx::Application::PinMode::Output );
}


//
// 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 < 2) return;
    else                          prvMillis = curMillis;

    // Output PWM values
    static eCxx::uint8_t curVal = 0;
    static eCxx::uint8_t curDir = 1;

    if(curDir > 0) {
        if(curVal < 255) ++curVal;
        else             curDir = 0;
    }
    else {
        if(curVal > 0) --curVal;
        else           curDir = 1;
    }

    App::analogWrite( eCxx::NodeMCU::BuiltinLED1, 255 -        curVal  ); // The LED is active low
    App::analogWrite( eCxx::NodeMCU::BuiltinLED2, 255 - (255 - curVal) ); // The LED is active low
}
