#include "gy49.h"

// MAX44009 I2C address is 0x4A/0x4B
#define GY49_ADDR 0x4A

/* Private variables */ 
static bool isPresent;
static Timer dataTimer;
static uint32_t Luminance;

/* Private Fuctions */ 
void _read_data(void);

/**
 * @brief Initialization
 */
void GY49_Init(void) {
  // Start I2C Transmission
  Wire.beginTransmission(GY49_ADDR);
  // Select configuration register
  Wire.write(0x02);
  // Continuous mode, Integration time = 800 ms
  Wire.write(0x40);
  // Stop I2C transmission
  if (Wire.endTransmission()) {
    Serial.println("GY-49: Sensor not respond!");
    isPresent = false;
    return;
  }
  isPresent = true;

  // start polling sensors - once per two seconds
  dataTimer.initializeMs(1000, _read_data).start();
}

void _read_data(void) {
  if (!isPresent) { return; }

  unsigned int data[2] = {0};

  // Start I2C Transmission
  Wire.beginTransmission(GY49_ADDR);
  // Select data register
  Wire.write(0x03);
  // Stop I2C transmission
  Wire.endTransmission();

  // Request 2 bytes of data
  Wire.requestFrom(GY49_ADDR, 2);

  // Read 2 bytes of data
  // luminance msb, luminance lsb
  if (Wire.available() == 2) {
    data[0] = Wire.read();
    data[1] = Wire.read();
  } else {
    Serial.println("GY-49: No data from sensor.");
    return;
  }

  // Convert the data to microLux
  uint32_t exponent = 1 << ((data[0] & 0xF0) >> 4);
  uint32_t mantissa = ((data[0] & 0x0F) << 4) | (data[1] & 0x0F);
  Luminance = exponent * mantissa * 45;

  // Output data to serial monitor
  Serial.print("Ambient Light luminance :");
  Serial.print(Luminance/1000);
  Serial.print(",");
  Serial.print(Luminance%1000);
  Serial.println(" lux");
}

uint32_t GY49_GetData(void) {
  return Luminance;
}
