/**
 * Author : Anatole SCHRAMM-HENRY
 * Created the : 08/09/2022
 * This classe exposes all the methods necessary to init the MBPeripherals (Mail Box Peripherals) and 
 * to retrieve various data and measurements like battery voltage, Mailbox events etc...
 */
#ifndef MBPERIPHERALS_H
#define MBPERIPHERALS_H

#include <RF24.h>
#include <LowPower.h>
 
#include "BoardConfig.h"

void defaultExtIntIsr(void);

typedef void (*ExtIntIsr)(void);

class MBPeripherals
{
  public:
    enum State {OFF, ON};
  
    MBPeripherals(const BoardConfig &boardConfig, void (*extIntIsr)(void) = nullptr);
    /*
     * Returns 1 if all the external devices are working properly, or an other value if it is not the case.
     */
    uint8_t init(void);
    
    /*
     * After calling this methode , you need to execute initExternalPeripherals() to init the peripherals.
     */
    void externalPeripherals(State state){_3V3PowerRail(state);}

    /*
     * Used to init devices after each LDO powerup, external devices need to be turned one externalPeripherals(ON) before calling this function.
     */
    uint8_t initExternalPeripherals(void);
    
    /*
     * Starts a battery voltage measurement and returns a float value in Volts.
     */
    float batteryVoltage(void);

    /*
     * Before calling this method, externalPeripherals(ON) and initExternalPeripherals() must be called respectively.
     * This methods applies the NRF radio configuration.
     */
    void applyRadioConfig(uint8_t channel = RADIO_CHANNEL, uint8_t paLevel = RADIO_PA_LEVEL, bool enableLNA = ENABLE_LNA, rf24_datarate_e datarate = RADIO_DATARATE);
    
    /*
     * Use this function just after the interrupt wake up retrieve the wake up event.
     * Wake up event can be : MAILBOX_LETTER, MAILBOX_PACKAGE, MAILBOX_COLLECTED or MAILBOX_UNKNOWN.
     */
    MAILBOX_EVENT_e readMailboxEvent(void);

    /*
     * Disables wake up interrupts
     */
    void maskExtInt(void);

    /*
     * Enables wake up interrupts
     */
    void unmaskExtInt(void);
    
    /*
     * Gets the NRF radio object to access it's api.
     */
    const RF24 &getRadio(void);
    
  protected:
  private:
    void _3V3PowerRail(State state);
    const BoardConfig &_boardConfig;
    const RF24 _NRF;
    ExtIntIsr _extIntIsr;
  
};

#endif //MBPERIPHERALS_H
