/*** main.c
 * 
 * Entry point for RGB brooch application
 * 
 * Created December 2010 by James Fowkes
 */

/* Includes */
#include "stm8s.h"
#include "stm8s_it.h"
#include "rgb.h"

/* Defines */
// Map generic port/pin to application functions:
#define USB_CHG_PORT GPIOF
#define USB_CHG_PIN GPIO_PIN_4
#define CGH_STA_PORT GPIOD
#define CGH_STA_PIN GPIO_PIN_0
#define TILT_PORT GPIOB
#define TILT_PIN GPIO_PIN_5

/* Local Function Prototypes */
void ioInit(void);

void main(void) {
	
	ioInit();
	rgbInit(CA); // We are using a common anode LED cluster
	
	while (1) {
		
		wfi(); 
		
		/* We only need to do stuff on interrupt. ISRs should run after
		 * wfi() and then the rest of main will execute */
		
		// Check for charge voltage present
		if ( (GPIO_ReadInputData(USB_CHG_PORT) & USB_CHG_PIN) == USB_CHG_PIN) {
			// USB voltage present, output charge status
			if ( (GPIO_ReadInputData(CGH_STA_PORT) & CGH_STA_PIN) == CGH_STA_PIN) {
				rgbSetColour(  0, 128, 0); // Green = charged
			} else {
				rgbSetColour(128,   0, 0); // Red = charging
			}
		} else {
			/* Output RGB */
			if ( msTimerFlag() ) { 
				// At each millisecond, step the RGB output
				rgbStep();
			}
			
			if ( pulsesFlag() ) { 
				// If we've got enough shakes of the tilt switch, randomise the colour output
				rgbNewCycle();
			}
		}
	}
}

void ioInit(void) {
	
	/* Setup tilt switch input */
	GPIO_Init(GPIOB, TILT_PIN, GPIO_MODE_IN_PU_IT);
	
	/* Setup status input */
	GPIO_Init(CGH_STA_PORT, CGH_STA_PIN, GPIO_MODE_IN_PU_NO_IT);
	
	/* Setup USB voltage detect input */
	GPIO_Init(USB_CHG_PORT, USB_CHG_PIN, GPIO_MODE_IN_FL_NO_IT);
	
	/* Ensure we can set correct interrupt levels */
	ITC_SetSoftwarePriority(ITC_IRQ_PORTB, ITC_PRIORITYLEVEL_3);
	EXTI_SetExtIntSensitivity(EXTI_PORT_GPIOB, EXTI_SENSITIVITY_RISE_FALL);
	
	#ifdef __DEBUG
		/* STM8S Discovery board LED - setup for debugging output */
		GPIO_Init(GPIOD, GPIO_PIN_0, GPIO_MODE_OUT_PP_LOW_FAST);
	#endif
	enableInterrupts();
	
}
