/*
Diplomova prace : Palubni pocitac

pwrctrl.c - sprava napajeni

Atmega128A 10 MHz XTAL

Autor: Ondrej Lutera

2011/2012

*/

#include "pwrctrl.h"

/* makra pro zjednoduseni zapisu portu */
#define _PORT(C) PORT ## C
#define PORT(C) _PORT(C)
#define _PIN(C) PIN ## C
#define PIN(C) _PIN(C)
#define _DDR(C) DDR ## C
#define DDR(C)  _DDR(C)

uint8_t EEMEM sleep_flag;
volatile uint8_t reboot = 0;

void pwrInit(void)
{


    PWR_DDR|=1<<PWR_PIN;


}

void SetSleep(void)
{

    /* casovac zakazan kvuli interruptu */
    DisTimer();

    pca_t pca;

    memset(&pca,0,sizeof(pca_t));
    setPCA(&pca);

    EIMSK = 0;
    TIMSK = 0;
    EICRA = 0;
    EICRB = 0;
    TCCR0 = 0;
    TCCR1A = 0;
    TCCR1B = 0;
    TCCR2 = 0;
    TCCR3A = 0;
    TCCR3B = 0;

    DDRA = 0;
    DDRB = 0;
    DDRC = 0;
    DDRD = 0;
    DDRE = 0;
    DDRF = 0;
    DDRG = 0;

    PORTA =0;
    PORTB =0;
    PORTC =0;
    PORTD =0;
    PORTE =0;
    PORTF =0;
    PORTG =0;

    PORT(GEN_PORT) = (1<<GEN_PIN); /* pullup na generator */

    ADCSRA=0;           /* vypneme adc prevodnik */
    ACSR |=1 << ACD;    /* vypneme komparator */

    MCUCSR =1<<JTD;
    MCUCSR =1<<JTD;

    INJ_EICR |= INJ_EICR_INIT;
    INJ_INT_EIMSK |=(1<<INJ_INT);

    eeprom_update_byte(&sleep_flag,1);

    /* nastavime tlacitkum pullupy */

    KEY_PULL|=1<<KEY_MENU|1<<KEY_ESC|ROT_A|ROT_B;

    /* nastavime pullup na probouzeci interrupt od tlacitek */

    ROT_INT_PULL|=1<<ROT_INT_PIN;

    /* interrupt na log0 - jinak se neprobudi */

    INT_EDGE_MODE_REG &=~(INT_EDGE_MODE_INIT|INT_CHNG_MODE_INIT);
    INT_ISR_INIT_REG |=INT_ISR_INIT ;

}

void CheckWakeUp(void)
{
    uint8_t i=0;

    while(bit_is_set(INJ_INT_PIN,INJ_INT_BIT) && bit_is_set(KEY_PIN,KEY_MENU) && (i < 200)  )
    {
        _delay_us(111);
        i++;

    }

    if(i<200)
    {

        INJ_EICR &=~(INJ_EICR_INIT);

        INJ_INT_EIMSK &=~(1<<INJ_INT);

        DisSleep();

        SetReboot();

    }

}

INJ_INT_ISR()
{

    CheckWakeUp();
}

inline uint8_t isSleep(void)
{

    return eeprom_read_byte(&sleep_flag);
}

inline void SleepPoll(void)
{

    while(isSleep())
    {

        set_sleep_mode(SLEEP_MODE_PWR_DOWN);
        sleep_enable();
        sleep_cpu();

        /* zde se probudime a musime se bud zase uspat nebo odejit ze sleep */
        if(isSleep()==0)
        {

            MCUCR=0;
            MCUCR=0;

        }

    };

}

inline void DisSleep(void)
{

    sleep_disable();
    eeprom_update_byte(&sleep_flag,0);

}

inline void SetReboot(void)
{

    reboot = 1 ;

}

inline uint8_t CheckReboot(void)
{

    if(reboot)
    {

        reboot = 0;

        return 1;
    }

    return 0;
}
