#include <stdio.h>
#include <unistd.h>

#include "udp_t.h"
#include "time_utils.hpp"

void *thread_udprcv(void *args)
{
    thread_udpsvr_arg* para = (thread_udpsvr_arg*)args;
    
    int     nr = 0;
    udp_t   *udp = NULL;
    char    msg[UDPBUFSIZE] = { 0 };
    unsigned char buff[UDPBUFSIZE]={0};
    int     flag = 1;
    long    seq;
    int     week = 0, sow = 0, usec = 0;
    int     hour, min, sod;
    double  sec;
    
    while(1)
    {
        udp = openudpsvr(para->path, msg);
        if (udp == NULL)
        {
            printf(" udp server open failed, path = %s, msg = %s\n", para->path, msg);        
        }
        
        while((nr = readudpsvr(udp, buff, UDPBUFSIZE, msg)) != -1)
        {
            flag = 1;

            printf("nr = %d, %s\n", nr, buff);
            
            if (para->handle)   para->handle(buff, nr);
            
            // 输出时间  
            flag = flag & sscanf((char *)&buff[5], "%ld", &seq);
            flag = flag & sscanf((char *)&buff[15], "%d", &week);
            flag = flag & sscanf((char *)&buff[22], "%d", &sow);
            if (flag != 1)
                continue;
            
            if (0)
            {
                sow -= 8*3600;
                if (sow < 0)
                {
                    week -= 1;
                    sow += 604800;
                }
            }
                
            
            sod = sow%86400;
            hour = (int)(sod/3600);
            min  = int((sod - hour*3600)/60);
            sec  = sod - hour*3600 - min*60 + usec/1000000;
            printf(" %04d %07d %02d %02d %.2lf\n", week, sow, hour, min, sec);
        }
        
        closeudpsvr(udp);
    }
    
    return NULL;
}

int main(int argc, char *argv[])
{
    const char *udppath = "192.168.2.180:4001";
    
    pthread_t           thread_id;
    thread_udpsvr_arg   thread_arg;
    
    
    strcpy(thread_arg.path, udppath);
    
    
    if (pthread_create(&thread_id, NULL, thread_udprcv, (void*)&thread_arg))
    {
        printf(" thread create error\n");
        return 0;
    }

    pthread_join(thread_id, NULL);
    return 0;
}
