/*******************************************************************************
/ * Copyright (C) 2015 Maxim Integrated Products, Inc., All Rights Reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included
 * in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL MAXIM INTEGRATED BE LIABLE FOR ANY CLAIM, DAMAGES
 * OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 *
 * Except as contained in this notice, the name of Maxim Integrated
 * Products, Inc. shall not be used except as stated in the Maxim Integrated
 * Products, Inc. Branding Policy.
 *
 * The mere transfer of this software does not imply any licenses
 * of trade secrets, proprietary technology, copyrights, patents,
 * trademarks, maskwork rights, or any other form of intellectual
 * property whatsoever. Maxim Integrated Products, Inc. retains all
 * ownership rights.
 *******************************************************************************/
/*
 * max30101.h
 *
 *  Created on: Aug 26, 2015
 *      Author: faisal.tariq
 */

#ifndef _MAX30101_H_
#define _MAX30101_H_

#include "mbed.h"

#define MAX30101_RAW_DATA_SIZE 3 * 4 * 32
#define MAX30101_PROC_DATA_SIZE 4 * 32

#define MAX30101_OXIMETER_DATA 0x10

#define CHUNK_SIZE 252

// MAX30101 Register addresses

#define MAX30101_INT_PORT 4
#define MAX30101_INT_PIN 0
#define MAX30101_MASTER_NUM 2

/**
* Maxim Integrated MAX30101 Oximeter chip
*/
class MAX30101 {
public:
  float max30101_final_temp;                         // Global declaration
  uint32_t max30101_buffer[MAX30101_PROC_DATA_SIZE]; // final Processed data
  char max30101_rawData[MAX30101_RAW_DATA_SIZE];     //  raw data from the chip

  typedef enum { // MAX30101 Register addresses

    /*Status */
    REG_INT_STAT_1 = 0x00,
    REG_INT_STAT_2 = 0x01,
    REG_INT_EN_1   = 0x02,
    REG_INT_EN_2   = 0x03,

    REG_FIFO_W_PTR   = 0x04,
    REG_FIFO_OVF_CNT = 0x05,
    REG_FIFO_R_PTR   = 0x06,
    REG_FIFO_DATA    = 0x07,
    /* Configuration */
    REG_FIFO_CFG  = 0x08,
    REG_MODE_CFG  = 0x09,
    REG_SPO2_CFG  = 0x0A,
    REG_LED1_PA   = 0x0C,
    REG_LED2_PA   = 0x0D,
    REG_LED3_PA   = 0x0E,
    REG_PILOT_PA  = 0x10,
    REG_SLT2_SLT1 = 0x11,
    REG_SLT4_SLT3 = 0x12,
    /* Die Temp    */
    REG_TINT    = 0x1F,
    REG_TFRAC   = 0x20,
    REG_TEMP_EN = 0x21,
    /* Proximity Func */
    REG_PROX_INT_THR = 0x30,
    /* Part ID        */
    REG_REV_ID = 0xFE,
    REG_ID     = 0xFF,
  } MAX30101_REG_map_t;

  /**********/
  /* STATUS */
  /**********/
  /// @brief STATUS1 (0x00)
  union max30101_Interrupt_Status_1_reg {
    char all;
    struct {
      char pwr_rdy  : 1;
      char reserved : 3;
      char prox_int : 1;
      char alc_ovf  : 1;
      char ppg_rdy  : 1;
      char a_full   : 1;
    } bit;
  } max30101_Interrupt_Status_1;

  /// @brief STATUS2 (0x01)
  union max30101_Interrupt_Status_2_reg {
    char all;
    struct {
      char reserved1    : 1;
      char die_temp_rdy : 1;
      char reserved2    : 6;
    } bit;
  } max30101_Interrupt_Status_2;

  /// @brief INTERRUPT_ENABLE1 (0x02)
  volatile union max30101_Interrupt_Enable_1_reg {
    uint8_t all;
    struct {
      uint8_t reserved1   : 4;
      uint8_t prox_int_en : 1;
      uint8_t alc_ovf_en  : 1;
      uint8_t ppg_rdy_en  : 1;
      uint8_t a_full_en   : 1;
    } bit;
  } max30101_Interrupt_Enable_1;

  /// @brief INTERRUPT_ENABLE2 (0x03)
  volatile union max30101_Interrupt_Enable_2_reg {
    uint8_t all;
    struct {
      uint8_t reserved1       : 1;
      uint8_t die_temp_rdy_en : 1;
      uint8_t reserved2       : 6;
    } bit;
  } max30101_Interrupt_Enable_2;

  /*********/
  /* FIFO  */
  /*********/
  // 0x04
  /// @brief FIFO_WR_PTR (0x04)
  volatile union max30101_fifo_wr_ptr_reg {
    uint8_t all;
    struct {
      uint8_t fifo_wr_ptr : 5;
      uint8_t reserved1   : 3;
    } bit;
  } max30101_fifo_wr_ptr;

  /// @brief OVF_COUNTER (0x05)
  volatile union max30101_ovf_counter_reg {
    uint8_t all;
    struct {
      uint8_t fifo_ovf_counter : 5;
      uint8_t reserved1        : 3;
    } bit;
  } max30101_ovf_counter_reg;

  /// @brief FIFO_READ_PTR (0x06)
  volatile union max30101_fifo_rd_ptr_reg {
    uint8_t all;
    struct {
      uint8_t fifo_rd_ptr : 5;
      uint8_t reserved1   : 3;
    } bit;
  } max30101_fifo_rd_ptr;

  // 0x07
  uint8_t max30101_fifo_data;

  /********************/
  /* Configuration    */
  /********************/
  // 0x08
  /// @brief FIFO_CONFIGURATION (0x08)
  volatile union max30101_fifo_configuration_reg {
    uint8_t all;
    struct {
      uint8_t fifo_a_full       : 4;
      uint8_t fifo_roll_over_en : 1;
      uint8_t smp_ave           : 3;
    } bit;
  } max30101_fifo_configuration;

  /// @brief MODE_CONFIGURATION (0x09)
  volatile union max30101_mode_configuration_reg {
    uint8_t all;
    struct {
      uint8_t mode      : 3;
      uint8_t reserved1 : 3;
      uint8_t reset     : 1;
      uint8_t shdn      : 1;
    } bit;
  } max30101_mode_configuration;

  /// @brief SPO2_CONGIGURATION (0x0A)
  volatile union max30101_spo2_configuration_reg {
    uint8_t all;
    struct {
      uint8_t led_pw       : 2;
      uint8_t spo2_sr      : 3;
      uint8_t spo2_adc_rge : 2;
      uint8_t reserved1    : 1;
    } bit;
  } max30101_spo2_configuration;

  /// @brief LED1_PA (0x0C)
  uint8_t max30101_led1_pa;

  /// @brief LED2_PA (0x0D)
  uint8_t max30101_led2_pa;

  /// @brief LED3_PA (0x0E)
  uint8_t max30101_led3_pa;

  /// @brief PILOT_PA (0x10)
  uint8_t max30101_pilot_pa;

  volatile union max30101_multiLED_mode_ctrl_1_reg {
    uint8_t all;
    struct {
      uint8_t slot1     : 3;
      uint8_t reserved  : 1;
      uint8_t slot2     : 3;
      uint8_t reserved1 : 1;
    } bit;
  } max30101_multiLED_mode_ctrl_1;

  volatile union max30101_multiLED_mode_ctrl_2_reg {
    uint8_t all;
    struct {
      uint8_t slot3     : 3;
      uint8_t reserved  : 1;
      uint8_t slot4     : 3;
      uint8_t reserved1 : 1;
    } bit;
  } max30101_multiLED_mode_ctrl_2;

  /********************/
  /* Die Temperature  */
  /********************/

  uint8_t max30101_tinit;

  uint8_t max30101_tfrac;

  volatile union max30101_die_temp_config {
    uint8_t all;
    struct {
      uint8_t temp_en  : 1;
      uint8_t reserved : 7;
    } bit;
  } max30101_die_temp_config;
  /*******************************/
  /***** Function Prototypes *****/
  /*******************************/

  uint8_t max30101_prox_int_thresh;

  /**
  * MAX30101 constructor.
  *
  * @param sda mbed pin to use for SDA line of I2C interface.
  * @param scl mbed pin to use for SCL line of I2C interface.
  */
  MAX30101(PinName sda, PinName scl, int slaveAddress);

  /**
  *  MAX30101 constructor.
  *
  * @param i2c I2C object to use.
  */
  MAX30101(I2C *i2c, int slaveAddress);

  /**
  * MAX30101 destructor.
  */
  ~MAX30101(void);

  /**
       * @brief Allows reading from MAX30101 register
   * @param reg: is the register address, to read from (look at max30101.h and the
   *             data sheet for details)
   * @param value: is the pointer to the value read from the register
   * @returns  0-if no error.  A non-zero value indicates an error.
   */
  int i2c_reg_read(MAX30101_REG_map_t reg, char *value);

  /**
   * @brief Allows writing to MAX30101 register
   * @param reg: is the register address, to read from (look at max30101.h and
   * the
   *        data sheet for details)
   * @param value: is the value to write to the register
   * @returns  0-if if no error.  A non-zero value indicates an error.
   */
  int i2c_reg_write(MAX30101_REG_map_t reg, char value);

  /**
   * @brief This function sets up for the SpO2 mode.  The data is returned in
   * the callback function
   * @brief max30101_int_handler in global array: buffer[].  SP mode handles two LED (Red,IR) data.  Hence it
   * @brief can fill up the FIFO up to a maximum of 3bytes/sample x 32 x 2 = 192bytes.
   * @param fifo_waterlevel_mark: corresponds to FIFO_A_FULL, In FIFO Configuration Register (0x08)
   * @param sample_avg: corresponds to SMP_AVE, in FIFO Configuration Register (0x08)
   * @param sample_rate: corresponds to SPO2_SR, IN SpO2 Configuration Register (0x0A)
   * @param pulse_width: corresponds to LED_PW in SpO2 Configuration register(0x0A)
   * @param red_led_current: corresponds to LED1_PA register (0x0C).  Please see data sheet for values
   * @param ir_led_current: corresponds to LED2_PA register (0x0D).  Please see data sheet for values
   * @returns 0-if everything is good.  A non-zero value indicates an error.
   */
  int SpO2mode_init(uint8_t fifo_waterlevel_mark, uint8_t sample_avg,
                    uint8_t sample_rate, uint8_t pulse_width,
                    uint8_t red_led_current, uint8_t ir_led_current);

  /**
   * @brief This function will stop the SpO2 mode and turn off all operating LEDâs.
   * @return  0-if if no error.  A non-zero value indicates an error.
   */
  int SpO2mode_stop(void);

  /**
   * @brief This function sets up for the HR mode.  The data is returned in thecallback function
   * @brief max30101_int_handler in global array: buffer[].HR mode handles one LED (Red) data.  Hence it can fill
   * @brief up the FIFO up to a maximum of 3bytes/sample x 32 = 96bytes.
   * @brief fifo_waterlevel_mark: corresponds to FIFO_A_FULL, In FIFO Configuration Register (0x08)
   * @param sample_avg: corresponds to SMP_AVE, in FIFO Configuration Register (0x08)
   * @param sample_rate:corresponds to SPO2_SR, IN SpO2 Configuration Register (0x0A)
   * @param pulse_width: corresponds to LED_PW in SpO2 Configuration Register(0x0A)
   * @param red_led_current: corresponds to LED1_PA register (0x0C).  Please see data sheet for values
   * @returns  0-if if no error.  A non-zero value indicates an error.
   */
  int HRmode_init(uint8_t fifo_waterlevel_mark, uint8_t sample_avg,
                  uint8_t sample_rate, uint8_t pulse_width,
                  uint8_t red_led_current);

  /**
   * @brief This function will stop the HR mode and turn off all operating
   * LEDâ€™s.
   * @return  0-if if no error.  A non-zero value indicates an error.
   */
  int HRmode_stop(void);

  /**
   *@brief This function sets up for the Multi-mode.  The data is returned in the callback function max30101_int_handler in global array:
   *@brief buffer[].  Multi-LED mode can handle 1 to 4 LED combinations.  Hence it can fill up the FIFO up to a maximum of
   *@brief 3bytes/sample x 32 x 4 = 384bytes.
   *@param fifo_waterlevel_mark: corresponds to FIFO_A_FULL, In FIFO Configuration Register (0x08)
   *@param sample_avg: corresponds to SMP_AVE, in FIFO Configuration Register (0x08)
   *@param sample_rate:corresponds to SPO2_SR, IN SpO2 Configuration Register (0x0A)
   *@param pulse_width: corresponds to LED_PW in SpO2 Configuration register(0x0A)
   *@param red_led_current: corresponds to LED1_PA register (0x0C).  Please see data sheet for values
   *@param ir_led_current: corresponds to LED2_PA register (0x0D).  Please see data sheet for values
   *@param green_led_current: corresponds to LED3_PA register (0x0E).  Please see data sheet for values
   *@param slot_1,â€¦,slot_4: corresponds to Multi-LED Mode control Registers (0x11-0x12).
   *@returns  0-if if no error.  A non-zero value indicates an error.
   */
  int Multimode_init(uint8_t fifo_waterlevel_mark, uint8_t sample_avg,
                     uint8_t sample_rate, uint8_t pulse_width,
                     uint8_t red_led_current, uint8_t ir_led_current,
                     uint8_t green_led_current, uint8_t slot_1, uint8_t slot_2,
                     uint8_t slot_3, uint8_t slot_4);

  /**
   * @brief This function will stop the Multi-mode and turn off all operating LEDâ€™s.
   * @returns  0-if if no error.  A non-zero value indicates an error.
   */
  int Multimode_stop(void);

  /**
   * @brief This is a function that sets up for temperature read and should be called after one of the mode
   * @brief has been setup.  The data is returned in the callback function max30101_int_handler.  This
   * @brief function needs to be called every time temperature reading is required.
   * @brief Call the temp function after one of the MODES have been started
   * @brief Note that the temp is disabled after one read... also, it is not necessary
   * @brief to read the temp frequently...
   * @returns  0-if if no error.  A non-zero value indicates an error.
   */
  int tempread(void);

  /**
   *@brief This is a callback function which collects the data from the FIFO of the MAX30101 in a 32-bit
   *@brief unsigned global array called max30101_buffer[].  Upon every interrupt from the MAX30101, this
   *@brief function is called to service the FIFO of the MAX30101.  This callback function also services the
   *@brief interrupt for the temp data.  The temp data is collected in a floating point global variable
   *@brief final_temp.
   *@param max30101_buffer[], global uint32_t
   *@returns  0-if everything is good.  A non-zero value indicates an error.
   */
  int int_handler(void);
  /**
  * @brief type definition for data interrupt
  */
  typedef void (*DataCallbackFunction)(uint32_t id, uint32_t *buffer,
                                       uint32_t length);
  /**
  * @brief type definition for general interrupt
  */
  typedef void (*InterruptFunction)();

  /**
  * @brief Used to connect a callback for when interrupt data is available
  */
  void onInterrupt(InterruptFunction _onInterrupt);

  /**
  * @brief Used to connect a callback for when interrupt data is available
  */
  void onDataAvailable(DataCallbackFunction _onDataAvailable);

  static MAX30101 *instance;

private:
  /// called when interrupt data is available
  void dataAvailable(uint32_t id, uint32_t *buffer, uint32_t length);
  /// callback function at the end of the interrupt
  void interruptPostCallback(void);
  /// callback function when interrupt data is available
  DataCallbackFunction onDataAvailableCallback;
  /// callback function when interrupt data is available
  InterruptFunction onInterruptCallback;
  /// Read I2c wrapper method
  int I2CM_Read(int slaveAddress, char *writeData, char writeCount, char *readData, char readCount);
  /// Write I2c wrapper method
  int I2CM_Write(int slaveAddress, char *writeData1, char writeCount1, char *writeData2, char writeCount2);
  /// pointer to I2C object
  I2C *i2c;
  /// flag to track if this object is the owner (created) the I2C object
  bool i2c_owner;
  /// Device slave address
  int slaveAddress;
};

/**
*  @brief Resets the I2C block, when needed
*/
extern void I2CM_Init_Reset(uint8_t index, int speed);

 /**
  * @brief Used for debugging, if needed
  */
void MAX30101MidIntHandler(void);

#endif /* _MAX30101_H_ */
