Monday, May 09, 2016

Using POSIX time related functions shows PTP time

One major different: The PTP time counts from 1990. POSIX function count from 1970.

The POSIX struct tm is
int tm_year
int tm_month
int tm_day
int tm_min
int tm_sec

Because I do not find function, I create the easy one to fill tm_xxx below.

/*
Copyright (C) 2016 YKLin

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

typedef struct _TIMESTAMP_S{
    uint16        epoch_number;
    uint32        seconds;
    uint32        nanoseconds;
} timestamp_t;
void _converttime(struct tm *mytime, uint64 epoch){
    int years=0, months=0,days=0,hours=0,minutes=0;
    if(!mytime){
        return;
    }
    if(epoch >= 31556926UL){
        years = epoch/31556926UL;
        epoch -= years*31556926UL;
    }
    if(epoch >= 2629743UL){
        months = epoch/2629743UL;
        epoch -= months*2629743UL;
    }
    if(epoch >= 86400UL){
        days = epoch/86400UL;
        epoch -= days*86400UL;
    }
    if(epoch >= 3600UL){
        hours = epoch/3600UL;
        epoch -= hours*3600UL;
    }
    if(epoch >= 60){
        minutes = epoch/60;
        epoch -= minutes*60;
    }
    mytime->tm_sec = (int)epoch;
    mytime->tm_year += years;
    mytime->tm_mon += months;
    mytime->tm_mday += days;
    mytime->tm_hour += hours;
    mytime->tm_min += minutes;
}
int _convertTimestapTotm(struct tm *mytime, timestamp_t *ts){
    if(!mytime || !ts){
        return FAILED;
    }
   _converttime(mytime, (uint64)ts->epoch_number<<32);
   _converttime(mytime, (uint64)ts->seconds);
    _converttime(mytime, (uint64)0x83aa7e80);
    return SUCCESS;
}