//#DOC Main, program entry and main loop
#include "main.h"
#include <otI2cBus.h>
#include <otSerial.h>
#include <otTimer.h>
#include <otMalloc.h>
#include <otPrintf.h>
#include <otBME280.h>

// Number of milliseconds that have elapsed since the system was started, up to 49.7 days.
U32         _ticker = 0;

otBME280 env;

// Timer 1 callback
FAST_CODE_2 void _timer1CallBack()
{
    _ticker++;
}

void setup()
{
    UartEnableSignals(UART0);
    UartSetBaud(UART0, 115200);
    
    I2cBusReset();
    I2cBusFrequency(100, 30);
    
    // Set system tick for every 1ms
    TimerSetInterruptService(TIMER1, _timer1CallBack, TimerRateMs(1));
    TimerEnable(TIMER1, true);
    
    setStdout(4096, UART0); // printf output is now directed on UART0
    
    DelayMs(1000);          // Wait terminal start
    if(!env.init())
    {
        printf("Can't find BME280\n");
        IDLE;
    }
}

void loop()
{
    if(env.read())
    {
        printf("[%6u] Temperature = %.2lf C\n",   _ticker, env.temperature());
        printf("[%6u] Pressure    = %.2lf hPa\n", _ticker, env.pressure());
        printf("[%6u] Humidity    = %.2lf %%\n",  _ticker, env.humidity());
        printf("[%6u] Dew point   = %.2lf C\n",   _ticker, env.dewPoint());
        printf("[%6u] Altitude    = %.2lf m\n",   _ticker, env.altitude());
        DelayMs(500); // Inserted this delay for a better readability, if too fast the numbers are not seen blessed!
    }
}