//#DOC Main, program entry and main loop
#include "main.h"
#include <otRTC.h>
#include <otSerial.h>
#include <otTimer.h>
#include <otPrintfLite.h>

// All functions called by interrupt handler must be located in fast RAM!
FAST_CODE_1 void rtcCallBack(void)
{
    printf("Yawn ... uhm, uhm, sleep over ...\n");
}

void setup()
{
    UartEnableSignals(UART0);
    UartSetBaud(UART0, 115200);
    setStdout(UART0); // printf output is now directed on UART0
    RtcOn();
    RtcSetInterruptService(rtcCallBack);
    
    // This test has been written in this date
    RtcSetDate(2020, 2, 19);
    RtcSetTime(0, 0, 0);
}

void loop()
{
    U16     val, loopCnt = 0;
    U8      h, m, s;
    int     yy, mm, dd, min = 1;
    
    
    // Forever loop
    while(1)
    {
        RtcGetTime(&h, &m, &s);
        RtcGetDate(&yy, &mm, &dd);
        printf("[%5d][%4d/%02d/%02d :: %02d:%02d:%02d] Countdown example:\n", loopCnt, yy, mm, dd, h, m, s);
        RtcSetCountDown(10);
        // Check countdown in polling mode
        while(val = RtcGetCountDown())
        {
            printf("%5u\r", val);
            DelayMs(500);
        }
        
        // Wake from sleep test
        RtcSetCountDown(10);
        RtcInterruptEnable(Rtc_Stopwatch, true);
        RtcGetTime(&h, &m, &s);
        printf("[%5d][%4d/%02d/%02d :: %02d:%02d:%02d] Now I do a little sleep but in 10 seconds I wake up .... ", loopCnt, yy, mm, dd, h, m, s);
        // Wait something for complete serial flush out
        DelayMs(5);
        // Go in sleep mode
        SLEEP;
        // Disable stopwatch interrupt
        RtcInterruptEnable(Rtc_Stopwatch, false);
        
        RtcGetTime(&h, &m, &s);
        printf("[%5d][%4d/%02d/%02d :: %02d:%02d:%02d] I'll take a little longer sleep, but I'll be back soon ... ", loopCnt, yy, mm, dd, h, m, s);
        RtcInterruptEnable(Rtc_Alarm, true);
        // Set the alarm at a minute ...
        RtcSetAlarm(0, min, 0);
        min++;
        SLEEP;
        // Disable alarm interrupt
        RtcInterruptEnable(Rtc_Alarm, false);
        loopCnt++;
    }
}