/* this file deals with power management */
#include "common.h"
#include "power.h"
#include "output.h"
#include <i2c.h>
#include <delays.h>

#define DS2764_W 0b01101000
#define DS2764_R 0b01101001

void initialise_power() {
/* I2C interface gets initialised in initialise_input */
	/* set PMOD to 1 */
}

/* private */
int get_ds2764_value(unsigned char address) {
	unsigned int temp;
	signed int result = 0;
	if (!EESequentialRead(DS2764_W,address,(unsigned char*) &temp, 2)) {
		result = ((temp & 0x00ff) << 8) | ((temp & 0xff00) >> 8);
	}
	return result;
}

/* not yet clear what to put in here */
int get_temperature(void) {
	return (get_ds2764_value(0x18)/256);
}

int get_current(void) {
	// return milliamps
	return (get_ds2764_value(0x0E) * 2);
}

int get_voltage(void) {
	float V = get_ds2764_value(0x0C);
	V = V / 32;
	V = V * 4.88;
	return (int)V;
}

int get_charge(void) {
	// return mAh
	return (get_ds2764_value(0x10)/4);
}


char power_pressed(void) {
	EEByteWrite(DS2764_W,0x08,0x80);
	Delay100TCYx(2);
	if (EERandomRead(DS2764_W,0x08) & 0x80) {
		return 0;
	}
	return 1;
}
	

void shutdown(void) {
	/* turn off LED and laser */
	conf.laser = 0;
	conf.display = 0;
	set_laser_brightness();
	set_display_brightness();
	
	EEByteWrite(DS2764_W,0x31, 0b00100000);
	EEByteWrite(DS2764_W,0xFE,0x44);
	Delay10KTCYx(200);
	EEByteWrite(DS2764_W,0xFE,0xB4);
	CloseI2C();
	TRISBbits.TRISB0 = 0;
	TRISBbits.TRISB1 = 0;
	LATBbits.LATB0 = 0;
	LATBbits.LATB1 = 0;
	while (1); /* sleep while waiting for power to die */
}
