/****************************************************************************
** File name    :  HTPublic.cpp
** Description  :  common member function 
** Create date  :  2018.09.01
** Auther by    :  Liuyx
** Version info :  V1.0.01
** Copyrigth By:  xi'an huatek, Inc Co., Ltd
** Update record:  
** DATE         AUTHER   DESC 
** -------------------------------------------------------------------------               
** 2018.09.01   Liuyx    first build
****************************************************************************/
//#include "StdAfx.h"
#include "HTPublic.h"
#include "HTType.h"
#include "HTGlobal.h"

void vSetPid()
{
    FILE *fp = fopen(DEF_PID_FILE, "w+");
    if (fp == NULL) {
        printf("--> open file %s faile.\n", DEF_PID_FILE);
        return;
    }
    fprintf(fp, "%d", GETPID());
    fflush(fp);
    fclose(fp);
}

int  iGetPid()
{
    char szPid[20] = { 0 };
    FILE *fp = fopen(DEF_PID_FILE, "r");
    fgets(szPid, sizeof(szPid), fp);
    fclose(fp);
    return atoi(szPid);
}

/****************************************************************
** Description : 检查文件/目录是否存在
** param in    : pszName         -- 要检查的文件/目录,FileName / PathName
**             : 
** param out   : None
** return code : 0               -- exist
**             : <0              -- not exist
****************************************************************/
int iDirOrFileExist(const char *pszName)
{
#ifdef _WIN32
    return _access(pszName, 0) ;
#else
    return access(pszName, 0) ;
#endif
}

char* getBaseName(char* path,char *basename)
{
    char* lastSep = NULL;

    int len = strlen(path);
    int i = 0;

    while (i < len) {
        if (path[i] == '/' || path[i] == ':' || path[i] == '\\')
            lastSep = path + i;

        i++;
    }

    if (lastSep)
        strcpy(basename, lastSep + 1);
    else
        strcpy(basename, path);

    return basename;
}
char* getDirName(char* path,  char *dirname)
{
    char* lastSep = NULL;

    int len = strlen(path);
    int i = 0;

    while (i < len) {
        if (path[i] == '/' || path[i] == ':' || path[i] == '\\')
            lastSep = path + i;

        i++;
    }

    if (lastSep) {
        strcpy(dirname, path);
        dirname[lastSep - path] = 0;
    }
    else
        strcpy(dirname, "");

    return dirname;
}
/****************************************************************
** Description : 创建目录
** param in    : pNmae           -- 要创建的目录名称
**             : 
** param out   : None
** return code : <0              -- failed
****************************************************************/
int iBuildDirent(const char *pName)
{
    int iRet = -1;
    char szCmd[256];
    memset(szCmd, 0x00, sizeof(szCmd));
#ifdef _WIN32
    char szTmp[256] = { 0 };
    strcpy(szTmp, pName);
    Unix2WindowPath((char*)szTmp);
    sprintf(szCmd,"mkdir %s", szTmp);
    //iRet = _mkdir(pName);
#else
    sprintf(szCmd,"mkdir -p %s", pName);    
#endif
    iRet = system(szCmd);
    return iRet;
}

// 移动文件到指定目录（备份文件）
bool bMoveFile(char *filename, char *pBakPath)
{
    char *p = NULL, *s = NULL, *t = NULL;
    char szCmd[1024] = { 0 };
    // 文件名格式：sersorID_time.jpg 或 ../img/sersorid_time.jpg
    if (filename && pBakPath)
    {
        if (iDirOrFileExist(pBakPath))
            iBuildDirent(pBakPath);
#ifdef _WIN32
        _snprintf(szCmd, sizeof(szCmd), "move %s %s", filename, pBakPath);
#else
        snprintf(szCmd, sizeof(szCmd), "mv %s %s", filename, pBakPath);
#endif
        //printf("sour=%s to dest=%s\n", filename, pBakPath);
        system(szCmd);

        return true;
    }
    return false;
}
/****************************************************************
** Description : 获取文件大小
** param in    : pNmae           -- 文件名称
**             : 
** param out   : None
** return code : <0              -- failed
****************************************************************/
int get_file_size(const char *path)  
{  
    unsigned long filesize = -1;      
    struct stat statbuff;  
    if(stat(path, &statbuff) < 0){  
        return filesize;  
    }else{  
        filesize = statbuff.st_size;  
    }  
    return filesize;  
}
/****************************************************************
** Description : 获取文件创建时间
** param in    : pNmae           -- 文件名称
**             :
** param out   : pCreateTime     -- YYYY-MM-DD HH24:MI:SS
** return code : <=0             -- failed
**             : >0              -- file size(byte) 
****************************************************************/
int getFileCreateTime(const char *path, char *pCreateTime)
{
    unsigned long filesize = -1;
    char *p = (char*)path, *s = (char*)path;
    struct stat statbuff;
    if (stat(path, &statbuff) < 0){
        vGetHostTime(pCreateTime);
        return 0;
    }
    //vTranHostTimeFmt(statbuff.st_ctime, pCreateTime);
    while (*p != '_') {
        p++; s++;
    }
    while (*s != '.') s++;
    strncpy(pCreateTime, p + 1, s - p - 1);
    return (int)statbuff.st_size ;
}
/****************************************************************
** Description : 从文件全路径中截取文件父目录、文件名及文件扩展名称
** param in    : pFullPath       -- 路径名称
**             :
** param out   : pFilename       -- 文件名
**             ：pExt            -- 扩展名
** return code : <0              -- failed
****************************************************************/
bool bSplitFilenameByFullPath(char *pFullPath, char *pPrantPath, char *pFilename, char *pExt)
{
    char *p, *s;
    // 文件名格式：sersorID_time.jpg 或 ../img/sersorid_time.jpg
    if (pFullPath && strlen(pFullPath) > 1) {
        p = pFullPath + strlen((const char*)pFullPath);

        while (*p != '\\' && *p != '/'  && p != pFullPath) p--;
        strncpy(pPrantPath, pFullPath, p - pFullPath + 1);  // 父目录名称
        s = p + 1;
        while (*s != '.') s++;
        if (*s != '.') strcpy(pFilename, p + 1);
        else {
            strncpy(pFilename, p + 1, s - p - 1);
            strcpy(pExt, s + 1);
        }
        return true;
    }
    return false;
}

/****************************************************************
** Description : 从文件全路径中截取文件父目录、文件名
** param in    : pFullPath       -- 路径名称
**             :
** param out   : pFilename       -- 文件名
**             ：pExt            -- 扩展名
** return code : <0              -- failed
****************************************************************/
bool bSplitFilenameByPath(char *pFullPath, char *pPrantPath, char *pFilename)
{
    char *p, *s;
    // 文件名格式：sersorID_time.jpg 或 ../img/sersorid_time.jpg
    if (pFullPath && strlen(pFullPath) > 1) {
        p = pFullPath + strlen((const char*)pFullPath);

        while (*p != '\\' && *p != '/'  && p != pFullPath) p--;
        strncpy(pPrantPath, pFullPath, p - pFullPath + 1);  // 父目录名称
        pPrantPath[p - pFullPath + 1] = 0x00;

        s = p + 1;
        strncpy(pFilename, s, strlen((const char*)pFullPath) - (p - pFullPath + 1));
        pFilename[strlen((const char*)pFullPath) - (p - pFullPath + 1)] = 0x00;
        return true;
    }
    return false;
}
/***********************************************************************
** Description  : 前导字符串
** param  in    : pstr            -- source string end=0x00
**              : node            -- split char
**              : no              -- index filed
** param out    : pFiled          -- index filed string
** return code  : index on filed val length
** call eg: len = iSplitStringFiled("qwwa1.ddee.fwe.3.4.322.fffgsd", '.', 0, retval);
***********************************************************************/
int iGetFileBeforString(char *pinstr, int pstrlen, char *poutstr)
{   //0312B12000042A383000022_001_01_20190906123640.dat
    
    char *p = NULL, *s = pinstr;
    // 文件名称的时间之前最小长度0312B12000042A383000022_001_01_
    if (pinstr && pstrlen > 1) {
        p = pinstr + strlen((const char*)pinstr);
        while (*p != '_' && p != pinstr) p--;
        strncpy(poutstr, pinstr, p - pinstr + 1);  // 父目录名称
        poutstr[p - pinstr + 1] = 0x00;
    }
    return (p - pinstr + 1);
}

/***********************************************************************
** Description  : 获取主机时间
** param  in    : None
** param out    : pszTime         -- string time(yyyymmddhhmmss)
** return code  : None
***********************************************************************/
void vGetHostTimeOnMillsecond(char *pszTime)
{
#ifdef _WIN32
    SYSTEMTIME  t;
    ::GetLocalTime(&t);
    sprintf(pszTime, "%04d%02d%02d%02d%02d%02d+%04d",
        t.wYear, t.wMonth, t.wDay,
        t.wHour, t.wMinute, t.wSecond, t.wMilliseconds);
#else
    struct timeval tv;
    gettimeofday(&tv, NULL);

    struct tm tms;
    memcpy(&tms, localtime((const time_t *)&tv.tv_sec), sizeof(struct tm));

    sprintf(pszTime, "%04d%02d%02d%02d%02d%02d+%04ld",
        tms.tm_year + 1900, tms.tm_mon + 1, tms.tm_mday,
        tms.tm_hour, tms.tm_min, tms.tm_sec, tv.tv_usec / 1000);
#endif
    return;
}
/***********************************************************************
** Description  : 获取主机时间
** param  in    : None
** param out    : pszTime         -- string time(yyyy-mm-dd hh:mm:ss+xxxx)
** return code  : None
***********************************************************************/
time_t vGetHostTimeFmtOnMillsecond(char *pszTime)
{
#ifdef _WIN32
    SYSTEMTIME  t;
    ::GetLocalTime(&t);
    sprintf(pszTime, "%04d-%02d-%02d %02d:%02d:%02d+%04d",
        t.wYear, t.wMonth, t.wDay,
        t.wHour, t.wMinute, t.wSecond, t.wMilliseconds);
#else
    struct timeval tv;
    gettimeofday(&tv, NULL);

    struct tm tms;
    memcpy(&tms, localtime((const time_t *)&tv.tv_sec), sizeof(struct tm));

    sprintf(pszTime, "%04d-%02d-%02d %02d:%02d:%02d+%04ld",
        tms.tm_year + 1900, tms.tm_mon + 1, tms.tm_mday,
        tms.tm_hour, tms.tm_min, tms.tm_sec, tv.tv_usec / 1000);
#endif
    return time(NULL);
}

/***********************************************************************
** Description  : 获取主机时间
** param  in    : None
** param out    : pszTime         -- string time(yyyymmddhhmmss)
** return code  : None
***********************************************************************/
void vGetHostTime (char *pszTime) 
{
   time_t t;
   struct tm tm;

   t= time( NULL );
   memcpy(&tm, localtime(&t), sizeof(struct tm));
   sprintf(pszTime, "%04d%02d%02d%02d%02d%02d",
       tm.tm_year+1900, tm.tm_mon+1, tm.tm_mday,
       tm.tm_hour, tm.tm_min, tm.tm_sec);
   return ;
}
/***********************************************************************
** Description  : 将int时间转为已经消失的时间格式串
** param  in    : c               -- 时间差(s)
** param out    : pszTime         -- string time(DD(day) hh:mm:ss)
** return code  : None
***********************************************************************/
void diffTimes(unsigned int c, char *pszTime)
{
    int day =0,hour =0 , min = 0, sec = 0;
    day = c / 86400;
    hour = (c%86400) / 3600;
    min = (c%86400%3600) / 60 ;
    sec = (c%86400%3600) % 60;
    sprintf(pszTime, "%02d(day) %02d:%02d:%02d",day, hour, min, sec);
}
/***********************************************************************
** Description  : 计算与当前时间之差
** param  in    : bcd_t           -- BCD编码(YYMMDDHHMISS)
** param out    : none
** return code  : 差值
***********************************************************************/
int getCurrTimeDiff(unsigned char *bcd_t) 
{
    unsigned char szTime[16] = {0} ;
    memcpy(szTime,"20", 2) ;
    bcd_to_asc(bcd_t, 6, szTime+2);
    
    return int(time(NULL)- strTime2int((char*)szTime));
}
/***********************************************************************
** Description  : 获取主机时间
** param  in    : None
** param out    : pszTime         -- string time(yyyy-mm-dd hh:mm:ss)
** return code  : None
***********************************************************************/
time_t vGetHostTimeFmt (char *pszTime) 
{
   time_t t;
   struct tm tm;

   t= time( NULL );
   memcpy(&tm, localtime((const time_t *)&t), sizeof(struct tm));
   sprintf(pszTime, "%04d-%02d-%02d %02d:%02d:%02d",
       tm.tm_year+1900, tm.tm_mon+1, tm.tm_mday,
       tm.tm_hour, tm.tm_min, tm.tm_sec);
   return t;
}
/***********************************************************************
** Description  : 获取主机时间
** param  in    : None
** param out    : pszTime         -- string time(yyyy-mm-dd hh:mm:ss)
** return code  : None
***********************************************************************/
time_t vGetHostTimeFmtBeforBay(char *pszTime, int beforbay)
{
    time_t t;
    struct tm tm;

    t = time(NULL) - (beforbay * 24 * 60 * 60);
    memcpy(&tm, localtime((const time_t *)&t), sizeof(struct tm));
    sprintf(pszTime, "%04d-%02d-%02d %02d:%02d:%02d",
        tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday,
        tm.tm_hour, tm.tm_min, tm.tm_sec);
    return t;
}

/***********************************************************************
** Description  : 获取当天的起始和结束时间
** param  in    : None
** param out    : pszTime         -- string time(yyyy-mm-dd hh:mm:ss)
** return code  : None
***********************************************************************/
time_t vGeOneDayTimeFmt(char *pSTime, char *pETime)
{
    time_t t;
    struct tm tm;

    t = time(NULL);
    memcpy(&tm, localtime((const time_t *)&t), sizeof(struct tm));
    sprintf(pSTime, "%04d-%02d-%02d 00:00:00",
        tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday);
    sprintf(pETime, "%04d-%02d-%02d 23:59:59",
        tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday);
    return t;
}

/***********************************************************************
** Description  : 获取主机时间
** param  in    : None
** param out    : pszTime         -- string time(yyyy-mm-dd hh:mm:ss)
** return code  : None
***********************************************************************/
unsigned int uiTime (void) 
{
    time_t t;
    t= time( NULL );
    return (unsigned int)(t & 0xFFFFFFFF);
}

/***********************************************************************
** Description  : 转换time_t的时间
** param  in    : t
** param out    : pszTime         -- string time(yyyy-mm-dd hh:mm:ss)
** return code  : None
***********************************************************************/
void vTranHostTimeFmt (time_t t, char *pszTime) 
{
   struct tm tms;
   memcpy(&tms, localtime((const time_t *)&t), sizeof(struct tm));
   sprintf(pszTime, "%04d-%02d-%02d %02d:%02d:%02d",
       tms.tm_year+1900, tms.tm_mon+1, tms.tm_mday,
       tms.tm_hour, tms.tm_min, tms.tm_sec);
}
/*****************************************************************
** Description: 时间串转整数
** param  in  : pszTime      -- 时间串(yyyy-mm-dd 24hh:mm:ss)
** param out  : None
** return code: uintTime
*****************************************************************/
time_t strTimeFmt2int(char *pszTime)
{
    struct tm stTm;
    time_t t1 = 0;
    char szTmp[20 + 1];

    memset(szTmp, 0x00, sizeof(szTmp));
    memcpy(szTmp, pszTime, 20);
    
    stTm.tm_sec = atoi((char *)(szTmp + 17));
    szTmp[16] = '\0';
    stTm.tm_min = atoi((char *)(szTmp + 14));
    szTmp[13] = '\0';
    stTm.tm_hour = atoi((char *)(szTmp + 11));   /*hour since midnight[0, 23]*/
    szTmp[10] = '\0';
    stTm.tm_mday = atoi((char *)(szTmp + 8));   /* day of the month [1, 31] */
    szTmp[7] = '\0';
    stTm.tm_mon = atoi((char *)(szTmp + 5)) - 1;/*months since January[0,11]*/
    szTmp[4] = '\0';
    stTm.tm_year = atoi((char *)(szTmp)) - 1900; /* years since 1900 */
    t1 = mktime(&stTm);
    return t1;
}
/***********************************************************************
** Description  : 获取当前时间点到之前360小时的时间段
** param  in    : t
** param out    : pSTime         -- string time(yyyymmddhh24mmss)
** param out    : pETime         -- string time(yyyymmddhh24mmss)
** return code  : None
***********************************************************************/
void getCurrentBefor360Hour(char *pstime, char *petime)
{
    struct tm tm;

    if(pstime == NULL || petime == NULL) return ;
    time_t  curTime = time(NULL);

    memcpy(&tm, localtime((const time_t *)&curTime), sizeof(struct tm));
    sprintf(petime, "%04d%02d%02d%02d%02d%02d",
        tm.tm_year+1900, tm.tm_mon+1, tm.tm_mday,
        tm.tm_hour, tm.tm_min, tm.tm_sec);

    curTime = curTime - (360 * 60 * 60);  // 360小时之前的时间
    memcpy(&tm, localtime((const time_t *)&curTime), sizeof(struct tm));
    sprintf(pstime, "%04d%02d%02d%02d%02d%02d",
        tm.tm_year+1900, tm.tm_mon+1, tm.tm_mday,
        tm.tm_hour, tm.tm_min, tm.tm_sec);
}
/*****************************************************************
** Description: 时间串转整数
** param  in  : pszTime      -- 时间串(yyyymmddhhmmss)
** param out  : None
** return code: uintTime
*****************************************************************/
time_t strTime2int(char *pszTime)
{
    struct tm stTm ;
    time_t t1 = 0;
    char szTmp[14+1];
    
    memset(szTmp, 0x00, sizeof(szTmp)) ;
    memcpy(szTmp, pszTime, 14) ;

    stTm.tm_sec = atoi((char *)(szTmp + 12));
    szTmp[12]='\0';
    stTm.tm_min = atoi((char *)(szTmp + 10));
    szTmp[10]='\0';
    stTm.tm_hour = atoi((char *)(szTmp + 8));   /*hour since midnight[0, 23]*/
    szTmp[8]='\0';
    stTm.tm_mday = atoi((char *)(szTmp + 6));   /* day of the month [1, 31] */
    szTmp[6]='\0';
    stTm.tm_mon  = atoi((char *)(szTmp + 4)) -1;/*months since January[0,11]*/
    szTmp[4]='\0';
    stTm.tm_year = atoi((char *)(szTmp)) - 1900; /* years since 1900 */
    t1 = mktime(&stTm);
    return t1 ;
}
#if 0
// 日月年(dmyy), 年的表示是先将年转换为2位十六进制数
void setPostionDate(unsigned char *pDate, unsigned char *pTime)
{
    unsigned char szDate[5]={0};
    unsigned short usNo = 0;

    // 20130109
    memcpy(szDate, pDate+6, 2);          // 日
    memcpy(szDate+2, pDate+4, 2);        // 月
    asc_to_bcd(szDate, 4, pTime);

    memcpy(szDate, pDate, 4);    
    usNo = htons(atoi((char*)szDate));
    memcpy(pTime+2, &usNo, sizeof(short));  // 年
}
// pDate = HH24MMSS
void setPostionTime(unsigned char *pDate, unsigned char *pTime)
{
    unsigned char szTmp[4] = {0};
    asc_to_bcd(pDate, 6, szTmp);
    memcpy(pTime, szTmp, 3);
}
#else
// 日月年(dmyy), 年的表示是先将年转换为2位十六进制数
void setPostionDate(unsigned char *pDate, unsigned char *pTime)
{
    char szDate[5]={0};
    unsigned short usNo = 0;

    // 20130109
    memcpy(szDate, pDate+6, 2);          // 日
    pTime[0] = (char)atoi(szDate);

    memcpy(szDate, pDate+4, 2);          // 月
    pTime[1] = (char)atoi(szDate);

    memcpy(szDate, pDate, 4);    
    usNo = htons(atoi((char*)szDate));
    memcpy(pTime+2, &usNo, sizeof(short));  // 年
}

// pDate = HH24MMSS
void setPostionTime(unsigned char *pDate, unsigned char *pTime)
{
    char szTmp[4] = {0};
    
    memcpy(szTmp, pDate, 2);          // 时
    pTime[0] = (char)atoi(szTmp);
    
    memcpy(szTmp, pDate+2, 2);        // 分
    pTime[1] = (char)atoi(szTmp);
    
    memcpy(szTmp, pDate+4, 2);        // 秒
    pTime[2] = (char)atoi(szTmp);
}
#endif

void getGnssData(unsigned char * p_date)
{
    time_t t;
    struct tm tm;
    char day,month,year[2];
    short years;

    t= time( NULL );
    memcpy(&tm, localtime(&t), sizeof(struct tm));
    day = (char)tm.tm_mday;
    month = (char)tm.tm_mon+1;
    years = (short)tm.tm_year+1900;
    memcpy(&year,(char*)&years,2);

    memcpy(p_date,&day,1);
	memcpy(p_date+1,&month,1);
	memcpy(p_date+2,year,2); 

	return;
}

void getGnssTime(unsigned char *p_time)
{
    time_t t;
    struct tm tm;
    char hour,minute,second;

    t = time(NULL);
    memcpy(&tm, localtime(&t), sizeof(struct tm));
    hour = (char)tm.tm_hour;
    minute = (char)tm.tm_min;
    second = (char)tm.tm_sec;

    memcpy(p_time,&hour,1);
    memcpy(p_time+1,&minute,1);
    memcpy(p_time+2,&second,1);

    return;
}

/***********************************************************************
** Description  : 获取主机UTC时间
** param  in    : None
** param out    : pszTime         -- string time(yyyy-mm-dd hh:mm:ss)
** return code  : None
***********************************************************************/
void getUTCFmtTime (char *pszTime) 
{
   time_t t;
   struct tm tm;

   t= time( NULL );
   memcpy(&tm, gmtime(&t), sizeof(struct tm));
   sprintf(pszTime, "%04d-%02d-%02d %02d:%02d:%02d",
       tm.tm_year+1900, tm.tm_mon+1, tm.tm_mday,
       tm.tm_hour, tm.tm_min, tm.tm_sec);
   return ;
}
/***********************************************************************
** Description  : 获取主机UTC时间
** param  in    : None
** param out    : pszTime         -- string time(yyyy-mm-dd hh:mm:ss)
** return code  : None
***********************************************************************/
time_t getUTCLongTime (void) 
{
   time_t t,t1=0;
   struct tm tm={0};

   t= time( NULL );
   memcpy(&tm, gmtime(&t), sizeof(struct tm));
   t1 = mktime(&tm);
   return t1 ;
}
/***********************************************************************
** Description  : 将UTC时间转为格式串
** param  in    : None
** param out    : pszTime         -- string time(yyyy-mm-dd hh:mm:ss)
** return code  : None
***********************************************************************/
void UTC2FmtTime (time_t utc, char *pszTime) 
{
    time_t lutc= utc+(8*60*60);
    struct tm tm={0};

    memcpy(&tm, gmtime(&lutc), sizeof(struct tm));
    sprintf(pszTime, "%04d-%02d-%02d %02d:%02d:%02d",
        tm.tm_year+1900, tm.tm_mon+1, tm.tm_mday,
        tm.tm_hour, tm.tm_min, tm.tm_sec);
    return ;
}
/***********************************************************************
** Description  : UTC时间转为本地时间
** param  in    : None
** param out    : pszTime         -- string time(yyyy-mm-dd hh:mm:ss)
** return code  : None
***********************************************************************/
void UTC2LocalTime (time_t utc, char *pszTime) 
{
    time_t lutc= utc+(8*60*60);
    struct tm tm = {0};
    memcpy(&tm, localtime(&lutc), sizeof(struct tm));
    sprintf(pszTime, "%04d-%02d-%02d %02d:%02d:%02d",
        tm.tm_year+1900, tm.tm_mon+1, tm.tm_mday,
        tm.tm_hour, tm.tm_min, tm.tm_sec);
    return ;
}
// 本地时间转UTC时间, pTime: YYMMDDHH24MISS
time_t local2Utc(unsigned char *pTime, int iLen)
{
    unsigned char szTime[20] = {0};
    time_t utc = 0 ,t1 = 0 ;
    struct tm tm = {0};

    bcd_to_asc(pTime, iLen, szTime+2);
    memcpy(szTime, "20", 2);
    utc = strTime2int((char*)szTime);
    t1 = utc ;
    memcpy(&tm, gmtime((const time_t*)&t1), sizeof(struct tm));
    t1 = mktime(&tm) ;
    return  t1 ;
}

// 本地时间转UTC整型时间
time_t local2UtcTime(time_t localTime)
{
    struct tm tm = {0};
    time_t t = localTime ;
    memcpy(&tm, gmtime((const time_t*)&t), sizeof(struct tm));
    t = mktime(&tm);
    return t;
}

// 根据BCD编码时间转报警ID
// param_in: pTime  -- YYMMDDHHMISS,  \x13\x10\12\x09\x14\x11
unsigned int getWarnID(unsigned char *pTime, int iLen, unsigned int id)
{
    unsigned char szTime[20] = {0}, szSub[20] = {0}, szTmp[8]={0};
    time_t utc = 0 ;
    if(pTime == NULL || iLen <= 0) return (unsigned int)utc;
    bcd_to_asc(pTime, iLen, szTime+2);  // xx131012091411
    memcpy(szTime, "20", 2);            // 20131012091411
    memcpy(szTmp, szTime, 4);           // 2013
    sprintf((char*)szSub, "%4d0101000000", atoi((char*)szTmp)-1);
    utc = strTime2int((char*)szTime) - strTime2int((char*)szSub);  // 20131012091411-20121012091411
    utc = (id << 26 )| utc;
    return (utc & 0xFFFFFFFF);
}
/***********************************************************************
** Description  : 获取源串中的第no个域,数字串,eg: 1923.122.3.4
** param  in    : pstr            -- source string end=0x00
**              : node            -- split char
**              : no              -- index filed
** param out    : None
** return code  : index on filed val
***********************************************************************/
int   iSplitNumberFiled(char *pstr, char node, int no)
{
    // 192.168.3.13
    int i=0,j=0;
    char *p = NULL, *s = pstr;
    char szTmp[128];
    for(i =0, j=0; i<(int)strlen((const char*)pstr) && j < no; i++) {
        if(pstr[i] == node) {
            s = pstr+i+1;
            j++;
            continue;
        }
    }
    if(s==NULL) return 0;
    if(j == no ) {
        while(pstr[i] != node && i<(int)strlen((const char*)pstr)) i++;
        p = pstr+i;
        strncpy(szTmp, s, p-s);
        szTmp[p-s] = 0x00;
        return atoi((const char*)szTmp);
    }
    return 0;
}
// 去除版本号首部字符,保留数字版本号
// eg: Ver1.2.34  ==> 1.2.34
int  iTrimVersionHeadChar(char *strver)
{
    int i = 0 ;
    if(strver == NULL) return 0 ;
    if((int)strlen(strver) <= 0) return 0 ;
    while(strver[i] != '.' && i < (int)strlen(strver)) {
        if(!(strver[i] >= 0x30 && strver[i] <= 0x39)) 
            i++;
        else break;
    }
    if(i >= (int)strlen(strver)) return 0 ;
    strcpy(strver, strver+i);
    return strlen(strver);
}
/***********************************************************************
** Description  : 获取源串中的第no个域, 字符串
** param  in    : pstr            -- source string end=0x00
**              : node            -- split char
**              : no              -- index filed
** param out    : pFiled          -- index filed string
** return code  : index on filed val length
** call eg: len = iSplitStringFiled("qwwa1.ddee.fwe.3.4.322.fffgsd", '.', 0, retval);
***********************************************************************/
int   iSplitStringFiled(char *pstr, char node, char no, char *pFiled)
{
    char *p = NULL, *s = pstr;
    int i=0,j=0;
    for(i =0, j=0; i<(int)strlen((const char*)pstr) && j < no; i++) {
        if(pstr[i] == node) {
            s = pstr+i+1;
            j++;
            continue;
        }
    }
    if(s==NULL) return 0;
    if(j == no ) {
        while(pstr[i] != node && i<(int)strlen((const char*)pstr)) i++;
        p = pstr+i;
        strncpy(pFiled, s, p-s);
        pFiled[p-s] = 0x00;
        return p-s;
    }
    return 0;
}

/***********************************************************************
** Description  : getDateFromTime 从时间字符串获取Date信息
** param  in    : p_time           -- 时间字符串
***********************************************************************/
void getDateFromTime(char* p_time,char* p_date)
{
    short m_year;
    char m_month,m_day;
    char year[5]  = {0};
	char month[3] = {0};
	char day[3]   = {0};
	
	memcpy(year,p_time,4);
    m_year = atoi(year);
	m_year = htons(m_year);

	memcpy(month,p_time+5,2);
	m_month = atoi(month);
	memcpy(day,p_time+8,2);
	m_day = atoi(day);

	memcpy(p_date,&m_day,1);
	memcpy(p_date+1,&m_month,1);
	memcpy(p_date+2,&m_year,2);
}

/**************************************************************
** Description: trim string rigth space
** param in   :
**            : *str        -- sources string
** param out  :
**            : *str        -- trim string
** return code:
**            : trim string current length
**************************************************************/
int RigthTrim(unsigned char *str)
{
    if ( strlen((char *)str) == 0 ) return 0;
    char *p = (char*)str + strlen((char*)str) - 1;
    while ( p >= (char*)str && *p == ' ' ) p--;
    *( ++p ) = '\0';
    return strlen( (char*)str );
}

 /**************************************************************
** Description: trim string left space
** param in   :
**            : *str         -- sources string(source)
** param out  :
**            : *str         -- trim string(dest)
** return code:
**            :trim string current length
**************************************************************/
int LeftTrim(unsigned char *str)
{
    char *p = (char*)str;
    while ( *p == ' ' ) p++;
    strcpy( (char*)str, p );
    return strlen( (char*)str );
}

/**************************************************************
** Description: trim char string left and rigth space
** param in   :
**            : *str             -- sources string
** param out  :
**            : *str             -- dest string
** return code: None
**************************************************************/
void LRTrim(unsigned char *str)
{
    LeftTrim(str) ;
    RigthTrim(str) ;
}
/**************************************************************
** Description: trim char string middle space,仅保留一个空格
** param in   :
**            : *str             -- sources string
** param out  :
**            : *str             -- dest string
** return code: None
**************************************************************/
void MiddleTrim(unsigned char *str)
{
    char *front = (char*)str;
    char *last = (char*)str;
    if(str == NULL) return;
    while((*front) == ' ') {++front;} 
    while((*front) != '\0') {
        if((*front) == ' ' ) {
            *last = ' ';
            while((*front) == ' ') ++front;
        }
        else {
            *last = *front; 
            ++front;
        }
        ++last;
    }
    *last = '\0';
}
/**************************************************************
** Description: trim char string middle space,仅保留一个空格
** param in   :
**            : *str             -- sources string
** param out  :
**            : *str             -- dest string
** return code: None
**************************************************************/
void strMiddleTrim(unsigned char *str)
{
    char *front = (char*)str;
    char *last = (char*)str;
    if (str == NULL) return;
    while ((*front) == '-') { ++front; }
    while ((*front) != '\0') {
        if ((*front) == '-') {
            ++front;
            continue;
        }
        else {
            *last = *front;
            ++front;
        }
        ++last;
    }
    *last = '\0';
}
/**************************************************************
** Description: check string all char is digit(number '0'--'9')
** param in   : 是否为纯数字的字符串
**            : *str        -- sources string
** param out  :
**            : *str        -- trim string
** return code:
**            : true        all char is digit
**            : false       not digit 
**************************************************************/
bool isStringDigit(char *pstr)
{
    int i = 0;
    while (i < (int)strlen(pstr)) {
        if(!((pstr[i] & 0xff) >= 0x30 && (pstr[i] & 0xff) <= 0x39)) return false;
        else i++;
    }
    return true;
}

void getTimeFromTime(char* p_time,char* p_times)
{
    char m_hour,m_minute,m_second;
    char hour[3]   = {0};
	char minute[3] = {0};
	char second[3] = {0};

    memcpy(hour,p_time+11,2);
    m_hour = atoi(hour);

    memcpy(minute,p_time+14,2);
    m_minute = atoi(minute);

    memcpy(second,p_time+17,2);
    m_second = atoi(second);

    memcpy(p_times,&m_hour,1);
    memcpy(p_times+1,&m_minute,1);
    memcpy(p_times+2,&m_second,1);
}

/*************************************************************************
Function     : two bytes change to one bytes
Param in     :
   pusFrom   : source strings
   uiFromLen : bytes of source strings
Param out    :
   pusTo     : object strings.
Return Code  : none
*************************************************************************/
void asc_to_bcd(unsigned char *pusFrom, unsigned int uiFromLen, unsigned char *pusTo)
{
    unsigned char ucTmp;
    unsigned int i;

    for(i=0; i<uiFromLen; i+=2) {
        ucTmp= pusFrom[i];
        if (ucTmp==0x00)   ucTmp= 0x00;
        else if (ucTmp<'A') ucTmp= ucTmp - '0';
        else ucTmp= tolower(ucTmp) - 'a' + 0x0a;

        ucTmp<<= 4;
        pusTo[i/2]= ucTmp;

        ucTmp= pusFrom[i+1];
        if(ucTmp == 0x00)   ucTmp= 0x00;
        else if (ucTmp<'A') ucTmp= ucTmp - '0';
        else  ucTmp= tolower((int)ucTmp) - 'a' + 0x0a;

        pusTo[i/2]= pusTo[i/2] + ucTmp;
    }
    pusTo[i/2] = 0x00;
}

/*************************************************************************
Function     : one byte change to two bytes
Param in     :
   pusFrom   : source strings
   uiFromLen : bytes of source strings
Param out    :
   pusTo     : object strings.
Return Code  : none
*************************************************************************/
void bcd_to_asc(unsigned char *pusFrom, unsigned int uiFromLen,unsigned char *pusTo)
{
   static unsigned char usHexToChar[16+1]= "0123456789ABCDEF";
   unsigned int i;

   for(i=0; i<uiFromLen; i++) {
      pusTo[2*i]= usHexToChar[(pusFrom[i] >> 4)];
      pusTo[2*i+1]= usHexToChar[(pusFrom[i] & 0x0F)];
   }
   pusTo[2*uiFromLen] = 0x00;
   return;
}
/*************************************************************************
Function     : by host byte order int change to network byte order,size(int)=4
Param in     :
   pusFrom   : source host unsigend int
Param out    : none
Return Code  : network byte order
*************************************************************************/
unsigned int htoni(unsigned int us)
{
    unsigned int i;
    i=((us&0xffff)<<24)|(((us&0xffff)<<8)&0x00ff0000)|
        ((us>>8)&0x0000ff00)|((us>>24)&0xffff);
    return i;
}
/*************************************************************************
Function     : by network byte order int change to host byte order,size(int)=4
Param in     :
   pusFrom   : source network unsigend int
Param out    : none
Return Code  : host byte order
*************************************************************************/
unsigned int ntohi(unsigned int us)
{
    unsigned int i;
    i=((us&0xffff)<<24)|(((us&0xffff)<<8)&0x00ff0000)|
        ((us>>8)&0x0000ff00)|((us>>24)&0xffff);
    return i;
}
/*************************************************************************
Function     : by network byte order int change to host byte order,size(int)=4
Param in     :
pusFrom   : source network unsigend int
Param out    : none
Return Code  : host byte order
*************************************************************************/
float n2hf(float value)
{
    FLOAT_CONV d1, d2;
    d1.f = value;
    d2.c[0] = d1.c[3];
    d2.c[1] = d1.c[2];
    d2.c[2] = d1.c[1];
    d2.c[3] = d1.c[0];
    return d2.f;
}
/*************************************************************************
Function     : by host byte order int64 change to network byte order,size(int64)=8
Param in     :
   pusFrom   : source host unsigend int64
Param out    : none
Return Code  : network byte order
*************************************************************************/
#ifdef htonll
utint64 htonll(utint64  u64)
{
    unsigned int hi = (unsigned int)( u64 >> 32);
    unsigned int lo = (unsigned int)(u64  & 0xFFFFFFFF);
    utint64 fhi = htoni(hi);
    utint64 flo = htoni(lo);
    flo <<= 32;
    return (utint64)(flo | fhi);
}
#endif
/*************************************************************************
Function     : by network byte order int64 change to host byte order,size(int64)=8
Param in     :
   pusFrom   : source network unsigend int64
Param out    : none
Return Code  : host byte order
*************************************************************************/
#ifdef ntohll
utint64 ntohll(utint64  u64)
{
    unsigned int hi = (unsigned int)( u64 >> 32);
    unsigned int lo = (unsigned int)(u64  & 0xFFFFFFFF);
    utint64 fhi = ntohi(hi);
    utint64 flo = ntohi(lo);
    flo <<= 32;
    return (utint64)(flo | fhi);
}
#endif
/*************************************************************************
Function     : one byte change to two bytes
Param in     :
   pusFrom   : source strings
   uiFromLen : bytes of source strings
Param out    :
   pusTo     : object strings.
Return Code  : none
Note :        本函数入参为网络字节序列
*************************************************************************/
unsigned int int64To32(utint64  u64)
{
    unsigned int hi = (unsigned int)(( u64 >> 32) & 0xFFFFFFFF);
    return hi;
}

// YYYY-MM-DD HH:MI:SS
void LocalTime2Bcd(char *pLocalTime, char *pBcd)
{
    char szDate[5]={0};
    char tmpTime[13] = {0};

    if(pLocalTime == NULL || pBcd == NULL)
		return;
    memcpy(tmpTime, pLocalTime+2, 2);
	memcpy(tmpTime+2, pLocalTime+5, 2);
	memcpy(tmpTime+4, pLocalTime+8, 2);
	memcpy(tmpTime+6, pLocalTime+11, 2);
	memcpy(tmpTime+8, pLocalTime+14, 2);
	memcpy(tmpTime+10, pLocalTime+17, 2);

    asc_to_bcd((unsigned char*)tmpTime, 12, (unsigned char*)pBcd);
    return;
}

/*************************************************************************
Function     : 检查字符串结束符
Param in     :
       psz   : source string
    length   : input string length, max 128(Byte)
Param out    : none      
Return Code  : valid string length
*************************************************************************/
int getStringLen(unsigned char *pstr, int length)
{
    unsigned char szTmp[128+1] = {0} ;
    int i = 0;
    memcpy(szTmp, pstr, length);
    while(i < length) {
        if((szTmp[i] & 0xff) != 0x00) {
            length -= i;
            memcpy(pstr, szTmp+i, length);
            break;
        }
        i++;
    }
    pstr[length] = 0x00;
    while(--length) {
        if((pstr[length] & 0xff) != 0x00 ) return length+1;
    }
    return length;
}
int getHexString(unsigned char *str, int length, unsigned char *pstr)
{
	int iLen = 0, iOff = 0;
    char *p = (char*)str;
    while ( *p == 0x00 ) {
        p++;
        length--;
    }
    memcpy( (char*)str, p,length );
    str[length] = 0x00;
    while(iLen < length) {
        iOff = (iLen * 2);
        sprintf((char*)pstr+iOff, "%.2X", (str[iLen] & 0xff));
        iLen++;
    }
    return (length * 2);
}
/*************************************************************************
Function     : 32位整数转二进制字符串
Param in     :
       num   : source uint
Param out    :
      pBin   : object strings.(min length = 32)
Return Code  : none
*************************************************************************/
void uint32_binstr(unsigned int num, char* pBin)
{
    int i;
    if(pBin == NULL) return ;
    for( i=0; i < (int)(sizeof(int)*8); i++)
    {
        pBin[(sizeof(int)*8-1)-i]  = (char)(((num >> i) & 1) + '0');
    }
    pBin[(sizeof(int)*8)] = 0x00;   // 结束符
    return;
}

/*************************************************************************
Function     : 64位整数转二进制字符串
Param in     :
       num   : source uint
Param out    :
      pBin   : object strings.(min length = 64)
Return Code  : none
*************************************************************************/
void uint64_binstr(utint64 num, char* pBin)
{
    int i;
    if(pBin == NULL) return ;
    for(i=0; i < (int)(sizeof(utint64)*8); i++)
    {
        pBin[(sizeof(utint64)*8-1)-i]  = (char)(((num >> i) & 1) + '0');
    }
    pBin[(sizeof(utint64)*8)] = 0x00;  // 结束符
    return;
}
/*************************************************************************
Function     : 二进制字符串转32位整数
Param in     :
       pBin  : source bin string(eg. 1010101001111), need '\0' end.
Param out    :
             : none
Return Code  : uint32 interger
*************************************************************************/
unsigned int binstr_uint32(char *pBin)
{
    unsigned int n = 0;
    int i, len = 0 ;

    if(pBin == NULL)  return 0 ;
    len = strlen(pBin) ;
    if(len > (int)(sizeof(int)*8)) 
        len = (int)(sizeof(int)*8) ;
    for(i=0; i < len; i++) {
        n = n * 2 + (pBin[i] - '0'); 
    }
    return n;
}

//从低位到高位,取n的第m位,m=1...32
int getBit(int n, int m)
{
    if (m == 0) return (n >> (1 - 1)) & 1;
    return (n >> (m - 1)) & 1;
}
//从低位到高位.将n的第m位置1, m=1...32
int setBitToOne(int n, int m)
{
    if (m == 0) return n | (1 << (1 - 1));
    return n | (1 << (m - 1));
    /*将1左移m-1位找到第m位，得到000...1...000
    n在和这个数做或运算*/
}

//从低位到高位, 将n的第m位置0,m=1...32
int setBitToZero(int n, int m)
{
    if (m == 0) return n & ~(1 << (1 - 1));
    return n & ~(1 << (m - 1));
    /* 将1左移m-1位找到第m位，取反后变成111...0...1111
    n再和这个数做与运算*/
}

/*************************************************************************
Function     : 字符串反转
Param in     :
       str   : source string(eg. 1010101001111), need '\0' end.
       len   : source length
Param out    :
             : str
Return Code  : str, null is faild
*************************************************************************/
char* strSwap(char* str,int len) 
{ 
    if(len <= 1)  return str;
    char temp = *str;
    *str = *(str+len-1);
    *(str+len-1) = temp;
    return (strSwap( str+1, len-2)-1);
}
/*************************************************************************
Function     : 二进制字符串转64位整数
Param in     :
       pBin  : source bin string(eg. 1010101001111), need '\0' end.
Param out    :
             : none
Return Code  : utint64 interger
*************************************************************************/
utint64 binstr_uint64(char *pBin)
{
    utint64 n = 0;
    int i, len = 0 ;

    if(pBin == NULL) return 0 ;
    len = strlen(pBin) ;
    if(len > (int)(sizeof(utint64)*8))  
        len = (int)(sizeof(utint64)*8);
    for(i=0; i < len; i++) {
        n = n * 2 + (pBin[i] - '0'); 
    }
    return n;
}

/*************************************************************************
Function     : 将Linux文件路径转为Windows的路径格式, 仅测试用
Param in     :
      pszPath: source path
Param out    :
             : pszBootPath 
Return Code  : none
*************************************************************************/
void Unix2WindowPath(char *pszPath)
{
    // /mnt/fileserver/gathergps/10122045/p_gathergps_20130703123031.dat
    char *p = NULL;
    int i = 0;
    if (pszPath == NULL) return;
    p = pszPath;
    while(p[i] != 0x00) 
    {
        if( p[i] == '/')  p[i] = '\\';
        i++;
    }
    p[i] = 0x00;
}
/*************************************************************************
Function     : 将Windows文件路径转为Linux的路径格式, 仅测试用
Param in     : pszPath  -- source path
Param out    :
             : pszPath
Return Code  : none
*************************************************************************/
void Window2UnixPath(char *pszPath)
{
    char *p = NULL;
    int  i = 0;
    if (pszPath == NULL) return;
    p = pszPath;
    while (p[i] != 0x00)  {
        if (p[i] == '\\') p[i] = '/';
        i++;
    }
    p[i] = 0x00;
}

int stringcasecmp(const char *ps1, const char *ps2)
{
#ifdef _WIN32
    //return strcmpi(ps1, ps2);
    return _strcmpi(ps1,ps2);
#else
    return strcasecmp(ps1,ps2);
#endif
}

int stringncasecmp(const char *ps1, const char *ps2, int length)
{
#ifdef _WIN32
    //return strnicmp(ps1,ps2,length);
    return _strnicmp(ps1,ps2,length);
#else
    return strncasecmp(ps1,ps2,length);
#endif
}

/*************************************************************************
Function     : 获取uuid
Param in     : 
Param out    :
: pszPath
Return Code  : none
*************************************************************************/
int getuuid(char *str, int inlen )
{
    memset(str, 0x00, inlen);
#if defined(WIN32)||defined(WINCE)||defined(WIN64)
    GUID guid;
    if (!CoCreateGuid(&guid))
    {
        _snprintf(str,inlen,
            "%08x%04x%04x%02x%02x%02x%02x%02x%02x%02x%02x",        //小写
            guid.Data1, guid.Data2, guid.Data3,
            guid.Data4[0], guid.Data4[1], guid.Data4[2],
            guid.Data4[3], guid.Data4[4], guid.Data4[5], 
            guid.Data4[6], guid.Data4[7]);
    }
#else
    uuid_t uu;
    uuid_generate(uu);
    //uuid_generate_time(uu);
    //uuid_generate_tims_safe(uu);
    uuid_unparse(uu, str);
    strMiddleTrim((unsigned char*)str);
    //printf("uuuuuu=%s\n", str);
    str[32] = 0x00;

#endif
    return strlen(str);
}


/*************************************************************************
Function     : 获取1-100内的随机数
Param in     :
Param out    :
Return Code  : none
*************************************************************************/
double getRandByTime()
{
    srand((unsigned int)time(NULL));
    return (double)((double)(rand()%100 + 1) / (double)(RAND_MAX / rand()));
}

/*************************************************************************
Function     : 字符串转小写
Param in     :
Param out    :
             : pszPath
Return Code  : none
*************************************************************************/
char *str2lower(char *s)
{
    char *p = s;
    if (!s || s == NULL ) return NULL;
    int len = strlen(s);
    for (int i = 0; i < len; i++)
    {
        if (s[i] >= 'A' && s[i] <= 'Z'){
            s[i] += 32;//+32转换为小写
            //s[i]=s[i]-'A'+'a';
        }
    }
    return p;
}
/*************************************************************************
Function     : 获取1-100内的随机数
Param in     :
Param out    :
: pszPath
Return Code  : none
*************************************************************************/
char *str2upper(char *s)
{
    char *p = s;
    if (!s || s == NULL) return NULL;
    int len = strlen(s);
    for (int i = 0; i < len; i++)
    {
        if (s[i] >= 'a' && s[i] <= 'z'){
            s[i] -= 32;//+32转换为小写
            //s[i]=s[i]-'a'+'A';
        }
    }
    return p;
}

