
#include "tc_system.h"

int64_t systime_ms(void)
{
    struct timeval tv;
    gettimeofday(&tv, NULL);
    return (int64_t) tv.tv_sec * 1000 + tv.tv_usec / 1000;
}

char* format_local_time(char* buff, int bsize)
{
    time_t now = time(NULL);

    struct tm *ptm = localtime(&now);

    strftime(buff, bsize, "%Y-%m-%d %H:%M:%S", ptm);

    return buff;
}

char* format_utc_time(char* buff, int bsize)
{
    time_t now = time(NULL);

    struct tm *ptm = gmtime(&now);

    strftime(buff, bsize, "%Y-%m-%d %H:%M:%S", ptm);

    return buff;
}

int printline(const char* title, uint8_t* buff, int len)
{
    int i;
    printf("%s(%2d):", title, len);
    for (i=0; i<len; i++)
    {
        printf("%02x ", buff[i]);
    }
    printf("\r\n");
    return len;
}

void msleep(int timeout)
{
    int err;
    struct timeval tv;
    tv.tv_sec = timeout/1000;
    tv.tv_usec = (timeout%1000) * 1000;
    do{ err=select(0,NULL,NULL,NULL,&tv); }while(err<0 && errno==EINTR);
}

void dumpReg2String(uint8_t *dst, uint16_t *src, int N)
{
    int i;
    for (i=0; i<N; i++)
    {
        dst[2*i+0] = (src[i]>>8)&0xFF;
        dst[2*i+1] = (src[i]>>0)&0xFF;
    }
}

void dumpString2Reg(uint16_t *dst, uint8_t *src, int N)
{
    int i;
    for (i=0; i<N; i+=2)
    {
        dst[i/2] = (src[i+0]<<8)|src[i+1];
    }
}