/*
 * rtc_adjust_clock.h
 *
 *  Created on: 12/04/2021
 *      Author: alexrayne <alexraynepe196@gmail.com>
 * ------------------------------------------------------------------------------
 *  internal clock adjusting to RTC reference clock
 *  reference RTC should capture RTC stamps with period  RTC_SYNC_STAMP_CLOCK
 *  ( possibly 1sec signal), and pass it's time [rtimer_clock_t] passes to rtc_adjust_sync(now)
 *  clock/rtimer can use evaluated clock-speed correction from rtc_adjust_1sec_correction()
 *
 *  (ru) Это корректор скорости хода внутренних часов, по опоре от внешнего прецизионного RTC.
 *  сигнал с периодом RTC_SYNC_STAMP_CLOCK [clock_time_t], должен захватывать реальное-время [rtimer_t]
 *      и передавать его в rtc_adjust_sync(now)
 *  Корректор вычисляет погрешность реальных часов относительно RTIMER_ARCH_SECOND
 *      и предоставляет результат измерения демону реальных часов из rtc_adjust_1sec_correction()
 *  часы могут использовать эту поправку для коррекции скорости хода.
 *
 *  [ precise RTC ] --> IRQ -> ISR[ now=RTIMER_NOW() ] -> rtc_adjust_sync( now )
 *                                                          eval: diff[rtimer_t]
 *  [ rtimer / clock] --<- rtc_adjust_1sec_correction() --<-|
 *
 *  Корректор накапливающий - усредняет RTC_SYNC_AVG_WINDOW измерений.
 */

#ifndef RTC_ADJUST_CLOCK_H_
#define RTC_ADJUST_CLOCK_H_

#include <project-conf.h>
#include <sys/clock.h>
#include <sys/rtimer.h>


#ifndef RTC_SYNC_STAMP_CLOCK
// suppose that RTC provide clock-stamps 1sec rate
#define RTC_SYNC_STAMP_CLOCK CLOCK_SECOND
#endif

#ifndef RTC_SYNC_CLOCK_TOL
// tolerance for clock sync. if stamps go out this border, hot resync used
#define RTC_SYNC_CLOCK_TOL (CLOCK_SECOND/64)
#endif

#ifndef RTC_SYNC_AVG_WINDOW
// RTC sync corrections averaging, to provide auto-adjusted constant clock rate correction
#define RTC_SYNC_AVG_WINDOW  8
#endif



///////////////////////////////////////////////////////////////////////////////////


void rtc_adjust_reset(void);


/// @brief event handle for time-stamp event from RTC
///     it must be invoked by App BSP on time-regular event/IRQ from RTC
/// @arg   a delta RTC stamp - internalclock [rtimer]
void rtc_adjust_sync(rtimer_clock_t stamp_1sec );



/// @brief platform stimer (secs timer) invoke this function to get 1sec-to-RTC
///         correction, measured by internal [rtimer]
int rtc_adjust_1sec_correction( void );

/// @brief clock method supports adjust clock rate with provided
//void rtimer_adjust( int delta_correction );



#endif /* RTC_ADJUST_CLOCK_H_ */
