/*
 * S9705 is conneceted to CAP3[0]. We use counter mode.
 */
#include <t_services.h>
#include <lpc23xx.h>
#include "lpc2388def.h"

static UW blightness;

typedef struct {
  UW blight;
  UH duty;
} t_blmap;

/*
 * blmap[] is the table to map S9705 output frequency into PWM duty of LCD.
 */
t_blmap blmap[] = {
   {     10, 900 },
   {    100, 800 },
   {   1000, 700 },
   {  10000, 600 },
   {  20000, 500 },
   {  40000, 400 },
   {  60000, 300 },
   { 100000, 200 },
   { 200000, 100 },
   { 300000,   0 },
};

void s9705_init()
{
    PCONP |= PCTIM3;	/* Power on Timer 3 */
    /* Configure P0.23 as CAP3[0] */
    PINSEL1 |= (0x3 << 14);
    T3TCR = 2;      /* Reset timer */
    T3TCR = 0;      /* Stop timer */
    T3PR = 0;       /* No prescale */

    /* Counter mode, incremented on rising edges of CAP3[0] */
    T3CTCR = 0x01;
}

/*
 * s9705_restart is called every one second.
 * We determine six levels of LCD blightness from S9705 output freq.
 */
void s9705_restart()
{
    UW bl;
    t_blmap *pmap;

    T3TCR = 0;      /* Stop timer */
    bl = blightness = (UW) T3TC;
    T3TC = 0;       /* Clear counter */
    T3TCR = 1;      /* Start counting */
    /* Determine PWM duty value from our blmap table */
    for (pmap = blmap; pmap->duty > 0; pmap++) {
        if (pmap->blight > bl) {
            break;
        }
    }
    set_pwm_duty(pmap->duty);
}

void blight_command(int argc, char **argv)
{
    t_blmap *pmap;
    int bl = blightness;

    for (pmap = blmap; pmap->duty > 0; pmap++) {
        if (pmap->blight > bl) {
            break;
        }
    }
    syslog(LOG_NOTICE, "Blightness: %d --> %d", bl, pmap->duty);
}
