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


#ifndef INCLUDE_ECXX_PLATFORM_SPECIFIC_TWISLAVE_H
#error "this file cannot be included directly"
#endif
#undef INCLUDE_ECXX_PLATFORM_SPECIFIC_TWISLAVE_H


#ifndef ECXX_PLATFORM_NODEMCU_TWISLAVE_H
#define ECXX_PLATFORM_NODEMCU_TWISLAVE_H


namespace eCxx {


//
// A simple NodeMCU TWI-slave wrapper
//
// WARNING : All functions derived from BasicOutputWriter<T> that accept parameters with data types
//           'PGMCharPointer' and 'PGMCharPointerFar' expect the pointers to come from program
//           memory exclusively!
//
// NOTE    : Whenever possible, use the versions that accept near program pointers because those that
//           accept the far program pointers may have more overhead and restrictions.
//
/*
 * NodeMCU has software TWI implementation.
 *
 * In slave mode it has even higher latency than in master mode.
 *
 * TWI clock frequency of 25 kHz or less is recommended for slave mode (higher clock frequency may or
 * may not work).
 */
class TWISlave : public BasicOutputWriter<TWISlave> {
    public:
        using TWIResultCode = eCxx::TWIResultCode;

        using RxCallbackF   = eCxx::FunctionalVoidCallback_UInt8;
        using TxCallbackF   = eCxx::FunctionalVoidCallback;

    public:
        inline ~TWISlave() = default;

    public:
        void begin(uint8_t slaveAddress, RxCallbackF rxcb, TxCallbackF txcb);
        void end();

        bool canRead() const;
        bool read(uint8_t& value);
        bool peek(uint8_t& value) const;

        TWIResultCode write(uint8_t value);
        TWIResultCode write(const void* data, uint8_t len);

    private:
        inline TWISlave() = default;

        friend inline TWISlave& twiSlave_instance();
};


} // namespace eCxx


#endif
