/*
 * Copyright (C) 2020-2021 Aloysius Indrayanto
 *
 * This file is part of the eCxx library, see LICENSE file for the license details.
 */


//
// Helper functions
//
static void initTWIMasterAndUART(bool lowSpeed)
{
    // Initialize TWI in master mode
    if(lowSpeed) App::twiMaster().begin(25000); // Use slow speed for NodeMCU TWI slave
    else         App::twiMaster().begin();      // Use the default speed

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


static void eCxx_user_task_TWIMasterTxRx()
{
    // 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 to slave
    static char c = 'a';

    App::twiMaster().beginTransmission(twiSlaveAddress);
    App::twiMaster().write('\'');
    App::twiMaster().write(c);
    App::twiMaster().write('\'');
    App::twiMaster().endTransmission();

    ++c;
    if(c > 'z') c = 'a';

    App::delayMS(500);

    // Receive from slave - send the received data to UART
    App::twiMaster().requestFrom(twiSlaveAddress, 10);

    eCxx::uint8_t g;
    while( App::twiMaster().read(g) ) {
        App::uart().write(g);
    }
    if(g) App::uart().write('\n');
}
