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


#ifndef ECXX_PLATFORM_NODEMCU_CORE_UTIL_H
#define ECXX_PLATFORM_NODEMCU_CORE_UTIL_H


#include <eCxx/eCxx_Internal.h>
#include <eCxx/Platform/Common/SPI.h>
#include <eCxx/Platform/Common/TWIConstant.h>


//
// Macros
//

// Bit direction
#define LSBFIRST 0
#define MSBFIRST 1


//
// Function prototypes with "C" linkage
//
extern "C" {

    // "NonISOConversion.cpp"
    extern char* ltoa(long value, char* result, int base);
    extern char* ultoa(unsigned long value, char* result, int base);
    extern char* dtostrf(double number, signed char width, unsigned char prec, char* s);
    extern const char* strrstr(const char* __restrict p_pcString, const char* __restrict p_pcPattern);

} // extern "C"


namespace eCxx {

namespace NodeMCU {


//
// HSPI-related data types
//
using HSPISlave_StatusRxCallback = void(*)(void*, uint32_t);
using HSPISlave_DataRxCallback   = void(*)(void*, uint8_t(&)[SPI::HSPI_DATA_BUFFER_SIZE]);


//
// SoftTWI-related data types
//
using SoftTWI_RxCallback = VoidCallback_Size;
using SoftTWI_TxCallback = VoidCallback;


//
// Function prototypes
//

// "HSPIMaster.cpp"
extern void hspiMaster_begin();
extern void hspiMaster_end();
extern void hspiMaster_setConfig(uint32_t freq, uint8_t bitOrder, uint8_t dataMode);
extern uint8_t hspiMaster_transfer(uint8_t data);

// "HSPISlave.cpp"
extern void hspiSlave_begin(uint8_t statusLen, void* arg, HSPISlave_StatusRxCallback srxcb, HSPISlave_DataRxCallback drxcb = nullptr);
extern void hspiSlave_end();

extern void ICACHE_RAM_ATTR hspiSlave_sendStatus(uint32_t status);
extern void ICACHE_RAM_ATTR hspiSlave_sendData(const uint8_t (&data)[SPI::HSPI_DATA_BUFFER_SIZE]);

// "SoftTWI.cpp"
extern void stwi_begin();
extern void stwi_begin(uint8_t address, SoftTWI_RxCallback rxcb, SoftTWI_TxCallback txcb);

extern void stwi_setFrequency(uint32_t freq);

extern void stwi_beginTransmission(uint8_t address);
extern TWIResultCode stwi_endTransmission(bool sendStop);

extern size_t stwi_write(uint8_t data);
extern size_t stwi_write(const uint8_t *data, size_t quantity);

extern size_t stwi_requestFrom(uint8_t address, size_t size, bool sendStop);

extern int32_t stwi_available();
extern int32_t stwi_read();
extern int32_t stwi_peek();


} // namespace NodeMCU

} // namespace eCxx


#endif
