/* Copyright (c) 2011 Daniel Thiele
   All rights reserved.

   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions
   are met:

   * Redistributions of source code must retain the above copyright
     notice, this list of conditions and the following disclaimer.
   * Redistributions in binary form must reproduce the above copyright
     notice, this list of conditions and the following disclaimer in the
     documentation and/or other materials provided with the distribution.
   * Neither the name of the authors nor the names of its contributors
     may be used to endorse or promote products derived from this software
     without specific prior written permission.

   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
   AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
   LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
   CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
   SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
   INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
   CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
   ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
   POSSIBILITY OF SUCH DAMAGE. */

/* $Id$ */
/**
 * @file
 * @brief ....
 * @_addtogroup grpApp...
 */

#include <avr/interrupt.h>
#include <avr/sleep.h>
#include <util/delay.h>

/* uracoli inclusions */
#include <board.h>
#include <timer.h>

/* project inclusions */
#include "i2c.h"
#include "sensors.h"

#if defined(rose231)
#include "reg_hmc5883l.h"
#include "reg_lis331hh.h"
#include "reg_bmp085.h"
#endif

#if defined(rose231)
static const uint8_t acc_fullscale = 2;	/* FS bits of CTRL_REG_4 0..2 */
static const uint8_t press_osrs = 1;	/* OSRS */
#endif

static volatile uint8_t adcfinished = 0;

/*
 * \brief Wrapper function to simplify call to single byte write accesses
 */
static inline void sensors_regwr(uint8_t devaddr, uint8_t regaddr, uint8_t val)
{
	uint8_t buf[1] = {val};
	i2c_write(devaddr, regaddr, buf, 1);
}

static inline uint8_t sensors_regrd(uint8_t devaddr, uint8_t regaddr)
{
	uint8_t buf[1];
	i2c_read(devaddr, regaddr, buf, 1);
	return buf[1];
}

/*
 * \brief Initialize Sensors
 *
 */
void sensors_init(void)
{
	/* configure interrupts of LIS331 */
	sensors_regwr(SENSORS_I2CADDR_LIS3331, RG_LIS331HH_CTRL_REG3, 0x06);
	sensors_regwr(SENSORS_I2CADDR_LIS3331, RG_LIS331HH_CTRL_REG4, 0x80 | ((acc_fullscale << 4) & 0x30));	/* BDU=1 */
}

/*
 * \brief Trigger a measurement
 * Common for pressure and temperature measurement
 *
 * @param mode 0x2E: temperature, 0x34: pressure (osrs=0), ...
 */
static inline void sensors_bmp085_trigger(uint8_t mode)
{
	sensors_regwr(SENSORS_I2CADDR_BMP085, 0xF4, mode);
}

/*
 * \brief Read result depending on what was triggered
 *
 * @return The 16-bit result, 19-bit results (ultra high resolution) not supported yet
 */
uint16_t sensors_bmp085_readresult(void)
{
	uint8_t tmp[2];
	uint16_t ret;

	i2c_read(SENSORS_I2CADDR_BMP085, 0xF6, tmp, 2);
	ret = (tmp[0] <<8) | tmp[1];
	return ret;
}

/*
 * \brief Read internal calibration EEPROM
 *
 * @param *buf Pointer to buffer to read into, must be of size 22
 */
void sensors_bmp085_readee(uint8_t *buf)
{
	i2c_read(SENSORS_I2CADDR_BMP085, RG_BMP085_PROM_START, buf, BMP085_PROM_DATA_LEN);
}

/*
 * \brief Trigger temperature measurement
 */
void sensors_bmp085_ut_trigger(void)
{
	sensors_bmp085_trigger(BMP085_MODE_T);
}

/*
 * \brief Trigger pressure measurement
 */
void sensors_bmp085_up_trigger(void)
{
	sensors_bmp085_trigger(BMP085_MODE_P + (press_osrs << 6));
}

void sensors_lis331_trigger(void)
{
	/* Mode: 400 Hz, all axes enabled */
	sensors_regwr(SENSORS_I2CADDR_LIS3331, RG_LIS331HH_CTRL_REG1, 0x2F);
}

void sensors_lis331_powerdown(void)
{
	sensors_regwr(SENSORS_I2CADDR_LIS3331, RG_LIS331HH_CTRL_REG1, 0x00);
}

void sensors_lis331hh_readresult(sensors_xyz_result_t *result)
{
	uint8_t buf[6];

	/* Block read of LIS331 requires MSB to be set to 1 */
	i2c_read(SENSORS_I2CADDR_LIS3331, RG_LIS331HH_OUT_X_L | 0x80, buf, 6);

	/* 3mg per digit/fullscale */
	result->x = (int16_t)((buf[1] << 8) | buf[0]);
	result->y = (int16_t)((buf[3] << 8) | buf[2]);
	result->z = (int16_t)((buf[5] << 8) | buf[4]);
}

/*
 * \brief Read HMC5883L identification registers
 * @param buf Buffer to keep identification code, must be size of 3
 */
void sensors_hmc5883l_identification(uint8_t *buf)
{
	i2c_read(SENSORS_I2CADDR_HMC5883, RG_HMC5883L_IDENT_A, buf, 3);
}

/*
 * \brief Trigger measurement
 */
void sensors_hmc5883l_trigger(void)
{
	sensors_regwr(SENSORS_I2CADDR_HMC5883, RG_HMC5883L_MODE, 0x01);	/* single measurement mode */
}

/*
 * \brief Read measurement
 */
void sensors_hmc5883l_readresult(sensors_xyz_result_t *result)
{
	uint8_t buf[6];
	
	i2c_read(SENSORS_I2CADDR_HMC5883, RG_HMC5883L_DATA_X, buf, 6);

	result->x = (buf[0] << 8) | buf[1];
	result->y = (buf[2] << 8) | buf[3];
	result->z = (buf[4] << 8) | buf[5];
}


ISR(ADC_vect)
{
	adcfinished = 1;
}

/*
 * \brief Trigger sleep based ADC measurement
 * Function is blocking until flag "adcfinished" is set by ISR
 *
 * @return ADC register value
 */
static inline uint16_t adc_measure(void)
{
	set_sleep_mode(SLEEP_MODE_ADC);
	/* dummy cycle */
	adcfinished = 0;
	do{
		sleep_mode();
		/* sleep, wake up by ADC IRQ */

		/* check here for ADC IRQ because sleep mode could wake up from
		 * another source too
		 */
	}while (0 == adcfinished);	/* set by ISR */
	return ADC;
}

/**
  * \brief Supply voltage measurement
  * Method: set 1.1V reference as input and AVCC as reference
  * 	this returns a negative result: AVCC = 1.1V - result
  *
  * \return The MCU internal voltage in [mV]
  *
  * \author Daniel Thiele
  */
uint16_t measure_vmcu(void)
{
	uint16_t val;

	PRR &= ~_BV(PRADC);
	ADCSRA = _BV(ADEN) | _BV(ADPS2) | _BV(ADPS1);	/* PS 64 */

	ADMUX  = _BV(REFS0) | (0x0E); /* reference: AVCC, input Bandgap 1.1V */
	_delay_us(200);			/* some time to settle */

	ADCSRA |= _BV(ADIF);		/* clear flag */
	ADCSRA |= _BV(ADIE);

	/* dummy cycle after REF change (suggested by datasheet) */
	adc_measure();

	_delay_us(100);			/* some time to settle */

	val = adc_measure();

	ADCSRA &= ~(_BV(ADEN) | _BV(ADIE));
	PRR |= _BV(PRADC);

	return ( (1100UL*1023UL) / val );
}

/* EOF */
