/*
 * 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_TWIMASTER_H
#error "this file cannot be included directly"
#endif
#undef INCLUDE_ECXX_PLATFORM_SPECIFIC_TWIMASTER_H


#ifndef ECXX_PLATFORM_AVR_COMMON_TWIMASTER_H
#define ECXX_PLATFORM_AVR_COMMON_TWIMASTER_H


namespace eCxx {


//
// A simple AVR TWI-master 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.
//
/*
 * TWIMaster always seems to get the number of bytes it requested, even if TWISlave does not send
 * as many (the additional bytes are garbage).
 */
class TWIMaster : public BasicOutputWriter<TWIMaster> {
    public:
        using TWIResultCode = eCxx::TWIResultCode;

        static constexpr decltype(eCxx::DefaultTWIFrequency) DefaultTWIFrequency = eCxx::DefaultTWIFrequency;

    private:
        inline TWIMaster() = default;

    public:
        inline ~TWIMaster() = default;

        static inline TWIMaster& instance() __ECXX_ATTR_ALWAYS_INLINE
        {
            static TWIMaster twiMaster;
            return twiMaster;
        }

    public:
        void begin(uint32_t frequency = DefaultTWIFrequency);
        void end();

        void beginTransmission(uint8_t slaveAddress);
        bool write(uint8_t value);
        bool write(const void* data, uint8_t len);
        TWIResultCode endTransmission();

        uint8_t requestFrom(uint8_t slaveAddress, uint8_t len);
        bool canRead() const;
        bool read(uint8_t& value);
        bool peek(uint8_t& value) const;

    private:
        uint8_t                                              _slaveAddress;
        RingBuffer<uint8_t, Application_Base::TWIBufferSize> _buff;
};


} // namespace eCxx


#endif
