Setting and Updating Absolute Time in Zephyr Application Using time_t Epoch

I am trying to configure the absolute time in my application, which at some point receives the time_t epoch value from an external source and should update it internally so that at any time I can retrieve the actual epoch to use in my application. I have tried to update the epoch using the function

void Set_Time( time_t epochTime )
{
    int ret;
    struct timespec ts;

    ts.tv_sec = epochTime;
    ts.tv_nsec = 0;
    ret = clock_settime( CLOCK_REALTIME, &ts );

    if ( ret < 0 )
    {
        LOG_WRN( "clock_settime returned error" );
    }
}

and then read it through the function time(NULL), but the latter always returns the value -1. Does anyone have any suggestions for implementing what I want?

Parents
  • Does time(NULL) return -1 even if you do not call your function Set_Time()? 

    I was thinking that it is better to maintain an epoch offset rather than trying to set the time itself, something like below

    void Set_Time(time_t epochTime)
    {
        epoch_offset = epochTime - (k_uptime_get() / 1000);
        LOG_INF("Time set to: %d (offset: %d)", epochTime, epoch_offset);
    }
    
    
    time_t Get_Time(void)
    {
        return epoch_offset + (k_uptime_get() / 1000);
    }
    

Reply
  • Does time(NULL) return -1 even if you do not call your function Set_Time()? 

    I was thinking that it is better to maintain an epoch offset rather than trying to set the time itself, something like below

    void Set_Time(time_t epochTime)
    {
        epoch_offset = epochTime - (k_uptime_get() / 1000);
        LOG_INF("Time set to: %d (offset: %d)", epochTime, epoch_offset);
    }
    
    
    time_t Get_Time(void)
    {
        return epoch_offset + (k_uptime_get() / 1000);
    }
    

Children
Related