/******************************************************************************
 * file    lib/management/common.c 
 * author  YuLiang
 * version 1.0.0
 * date    14-Sep-2021
 * brief   This file provides all the common operation functions.
 *
 ******************************************************************************
 * Attention
 *
 * <h2><center>&copy; COPYRIGHT(c) 2021 LandPower</center></h2>
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *   1. Redistributions of source code must retain the above copyright notice,
 *      this list of conditions and the following disclaimer.
 *   2. Redistributions in binary form must reproduce the above copyright notice,
 *      this list of conditions and the following disclaimer in the documentation
 *      and/or other materials provided with the distribution.
 *   3. Neither the name of LandPower nor the names of its contributors may be used to 
 *      endorse or promote products derived from this software without specific
 *      prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 ******************************************************************************/

/* Includes ------------------------------------------------------------------*/
//#ifdef HAVE_CONFIG_H
#include "config.h"
//#endif

/* 标准C库头文件. */
#include <sys/time.h>
#include <ctype.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

/* 用户代码头文件. */
#include "vty.h"

/* Private define ------------------------------------------------------------*/

/* Private macro -------------------------------------------------------------*/

/* Private typedef -----------------------------------------------------------*/
/* 时间缓存结构体. */
typedef struct _time_cache
{
    time_t last;                /* 最后一次时间缓存数据. */
    size_t len;                 /* buf中数据的长度. */
    char buf[TIME_STR_LEN];     /* 时间数据转化的字符串. */
} time_cache_t;

/* Private variables ---------------------------------------------------------*/
static struct timeval sd_start, sd_end;
static unsigned long Crc32Table[256] =
{
    0x00000000L, 0x77073096L, 0xee0e612cL, 0x990951baL, 0x076dc419L,
    0x706af48fL, 0xe963a535L, 0x9e6495a3L, 0x0edb8832L, 0x79dcb8a4L,
    0xe0d5e91eL, 0x97d2d988L, 0x09b64c2bL, 0x7eb17cbdL, 0xe7b82d07L,
    0x90bf1d91L, 0x1db71064L, 0x6ab020f2L, 0xf3b97148L, 0x84be41deL,
    0x1adad47dL, 0x6ddde4ebL, 0xf4d4b551L, 0x83d385c7L, 0x136c9856L,
    0x646ba8c0L, 0xfd62f97aL, 0x8a65c9ecL, 0x14015c4fL, 0x63066cd9L,
    0xfa0f3d63L, 0x8d080df5L, 0x3b6e20c8L, 0x4c69105eL, 0xd56041e4L,
    0xa2677172L, 0x3c03e4d1L, 0x4b04d447L, 0xd20d85fdL, 0xa50ab56bL,
    0x35b5a8faL, 0x42b2986cL, 0xdbbbc9d6L, 0xacbcf940L, 0x32d86ce3L,
    0x45df5c75L, 0xdcd60dcfL, 0xabd13d59L, 0x26d930acL, 0x51de003aL,
    0xc8d75180L, 0xbfd06116L, 0x21b4f4b5L, 0x56b3c423L, 0xcfba9599L,
    0xb8bda50fL, 0x2802b89eL, 0x5f058808L, 0xc60cd9b2L, 0xb10be924L,
    0x2f6f7c87L, 0x58684c11L, 0xc1611dabL, 0xb6662d3dL, 0x76dc4190L,
    0x01db7106L, 0x98d220bcL, 0xefd5102aL, 0x71b18589L, 0x06b6b51fL,
    0x9fbfe4a5L, 0xe8b8d433L, 0x7807c9a2L, 0x0f00f934L, 0x9609a88eL,
    0xe10e9818L, 0x7f6a0dbbL, 0x086d3d2dL, 0x91646c97L, 0xe6635c01L,
    0x6b6b51f4L, 0x1c6c6162L, 0x856530d8L, 0xf262004eL, 0x6c0695edL,
    0x1b01a57bL, 0x8208f4c1L, 0xf50fc457L, 0x65b0d9c6L, 0x12b7e950L,
    0x8bbeb8eaL, 0xfcb9887cL, 0x62dd1ddfL, 0x15da2d49L, 0x8cd37cf3L,
    0xfbd44c65L, 0x4db26158L, 0x3ab551ceL, 0xa3bc0074L, 0xd4bb30e2L,
    0x4adfa541L, 0x3dd895d7L, 0xa4d1c46dL, 0xd3d6f4fbL, 0x4369e96aL,
    0x346ed9fcL, 0xad678846L, 0xda60b8d0L, 0x44042d73L, 0x33031de5L,
    0xaa0a4c5fL, 0xdd0d7cc9L, 0x5005713cL, 0x270241aaL, 0xbe0b1010L,
    0xc90c2086L, 0x5768b525L, 0x206f85b3L, 0xb966d409L, 0xce61e49fL,
    0x5edef90eL, 0x29d9c998L, 0xb0d09822L, 0xc7d7a8b4L, 0x59b33d17L,
    0x2eb40d81L, 0xb7bd5c3bL, 0xc0ba6cadL, 0xedb88320L, 0x9abfb3b6L,
    0x03b6e20cL, 0x74b1d29aL, 0xead54739L, 0x9dd277afL, 0x04db2615L,
    0x73dc1683L, 0xe3630b12L, 0x94643b84L, 0x0d6d6a3eL, 0x7a6a5aa8L,
    0xe40ecf0bL, 0x9309ff9dL, 0x0a00ae27L, 0x7d079eb1L, 0xf00f9344L,
    0x8708a3d2L, 0x1e01f268L, 0x6906c2feL, 0xf762575dL, 0x806567cbL,
    0x196c3671L, 0x6e6b06e7L, 0xfed41b76L, 0x89d32be0L, 0x10da7a5aL,
    0x67dd4accL, 0xf9b9df6fL, 0x8ebeeff9L, 0x17b7be43L, 0x60b08ed5L,
    0xd6d6a3e8L, 0xa1d1937eL, 0x38d8c2c4L, 0x4fdff252L, 0xd1bb67f1L,
    0xa6bc5767L, 0x3fb506ddL, 0x48b2364bL, 0xd80d2bdaL, 0xaf0a1b4cL,
    0x36034af6L, 0x41047a60L, 0xdf60efc3L, 0xa867df55L, 0x316e8eefL,
    0x4669be79L, 0xcb61b38cL, 0xbc66831aL, 0x256fd2a0L, 0x5268e236L,
    0xcc0c7795L, 0xbb0b4703L, 0x220216b9L, 0x5505262fL, 0xc5ba3bbeL,
    0xb2bd0b28L, 0x2bb45a92L, 0x5cb36a04L, 0xc2d7ffa7L, 0xb5d0cf31L,
    0x2cd99e8bL, 0x5bdeae1dL, 0x9b64c2b0L, 0xec63f226L, 0x756aa39cL,
    0x026d930aL, 0x9c0906a9L, 0xeb0e363fL, 0x72076785L, 0x05005713L,
    0x95bf4a82L, 0xe2b87a14L, 0x7bb12baeL, 0x0cb61b38L, 0x92d28e9bL,
    0xe5d5be0dL, 0x7cdcefb7L, 0x0bdbdf21L, 0x86d3d2d4L, 0xf1d4e242L,
    0x68ddb3f8L, 0x1fda836eL, 0x81be16cdL, 0xf6b9265bL, 0x6fb077e1L,
    0x18b74777L, 0x88085ae6L, 0xff0f6a70L, 0x66063bcaL, 0x11010b5cL,
    0x8f659effL, 0xf862ae69L, 0x616bffd3L, 0x166ccf45L, 0xa00ae278L,
    0xd70dd2eeL, 0x4e048354L, 0x3903b3c2L, 0xa7672661L, 0xd06016f7L,
    0x4969474dL, 0x3e6e77dbL, 0xaed16a4aL, 0xd9d65adcL, 0x40df0b66L,
    0x37d83bf0L, 0xa9bcae53L, 0xdebb9ec5L, 0x47b2cf7fL, 0x30b5ffe9L,
    0xbdbdf21cL, 0xcabac28aL, 0x53b39330L, 0x24b4a3a6L, 0xbad03605L,
    0xcdd70693L, 0x54de5729L, 0x23d967bfL, 0xb3667a2eL, 0xc4614ab8L,
    0x5d681b02L, 0x2a6f2b94L, 0xb40bbe37L, 0xc30c8ea1L, 0x5a05df1bL,
    0x2d02ef8dL
};

/* Private function prototypes -----------------------------------------------*/

/* Internal functions --------------------------------------------------------*/
/* 在时间后面根据precision长度,添加更加精确的时间字符串. */
static size_t _time_string_prec_add(char *buf, size_t len, int32_t precision, struct timeval *clock)
{
    static const int divisor[] = {0, 100000, 10000, 1000, 100, 10, 1};
    char *p = NULL;

    /* 最多统计到us */
    if (precision > 6)
        precision = 6;

    p = buf + len + 1 + precision;
    *p-- = '\0';
    
    clock->tv_usec /= divisor[precision];
    do
    {
        *p-- = '0' + (clock->tv_usec % 10);
        clock->tv_usec /= 10;
    }
    while(--precision > 0);
    
    *p = '.';
    return len + 1 + precision;
}

/* Interface functions -------------------------------------------------------*/
/* description: 将字符串转为小写.
   param:   str --  需要转换的字符转
   return: 转换后的字符串 */
char *str_to_lower(char *str)
{
    uint32_t i = 0;

    if (str != NULL)
    {
        for(i = 0; str[i] != '\0'; i++)
        {
            str[i] = tolower(str[i]);
        }
    }
    
    return str;
}

/* description: 去掉字符串中的多余空格.
   param:   str         --  需要转换操作的字符转
            omit_end    --  omit_end(TRUE)表示会将字符串尾部的空格全部消除
                            omit_end(FALSE)表示如果尾部有空格，允许保留1个空格
   return: 操作后的字符串 */
char *str_omit_space(char *str, bool omit_end)
{
    char *front = str;
    char *last = str;
    
    if (NULL == str)
    {
        return NULL;
    }

    while(' ' == *front)
        front++;
    
    while((*front) != '\0')
    {
        if (' ' == *front)
        {
            while((*++front) == ' ');

            if ('\0' == *front && omit_end)
                ;
            else
            {
                *last = ' ';
                last++;
            }
        }
        else
        {
            *last = *front;
            front++;
            last++;
        }
    }
    
    *last = '\0';
    return str;
}

/* description: 根据传入的精度precision,将时间字符串填到buf.
   param:   precision   --  精度,几位小数
            buf         --  存储转换后字符串的buffer
            buflen      --  buf的大小
   return: 返回字符串长度,如果失败,返回0 */
size_t time_string(int32_t precision, char *buf, size_t buflen)
{
    static time_cache_t cache;
    struct timeval clock;

    /* 获取时间数据clock. */
    gettimeofday(&clock, NULL);

    /* 更新时间到字符串,cache是静态的,如果两次time_string调用在1秒之内,将沿用上次的cache. */
    if (cache.last != clock.tv_sec)
    {
        struct tm *tm = NULL;
        cache.last = clock.tv_sec;
        tm = localtime(&cache.last);
        cache.len = strftime(cache.buf, sizeof(cache.buf), "%Y/%m/%d %H:%M:%S", tm);
    }

    if (buflen > cache.len)
    {
        memcpy(buf, cache.buf, cache.len);

        /* 计算秒之后的精度. */
        if ((precision > 0) && (buflen > cache.len + 1 + precision))
            return _time_string_prec_add(buf, cache.len, precision, &clock);

        buf[cache.len] = '\0';
        return cache.len;
    }

    /* buf太小,无法生成字符串. */
    if (buflen > 0)
        buf[0] = '\0';

    return 0;
}

/* description: 获取错误代码字符串.
   param:   errnum  --  错误代码
   return: 获取的字符串 */
const char *safe_strerror(int errnum)
{
    const char *s = strerror(errnum);
    return (s != NULL) ? s : "Unknown error";
}

/* description: 按16进制打印buf数据.
   param:   buf --  数据
            len --  数据长度
   return: */
void buf_print(char *buf, int32_t len)
{
    int32_t i = 0;
    
    for(i = 0; i < len;)
    {
        printh("%02x ", (uint8_t)buf[i++]);
        if(0 == i % 32)
        {
            printh("\r\n");
        }
    }
    if(i % 32 != 0)
    {
        printh("\r\n");
    }

    return;
}

/* description: 按16进制打印buf数据.
   param:   buf --  数据
            len --  数据长度
   return: */
void buf_print_16(uint16_t *buf, int32_t len)
{
    int32_t i = 0;
    
    for(i = 0; i < len;)
    {
        printh("%04x ", buf[i++]);
        if(0 == i % 32)
        {
            printh("\r\n");
        }
    }
    if(i % 32 != 0)
    {
        printh("\r\n");
    }

    return;
}

/* description: 通过 ip 生成 mac 地址.
   param:   ip_str  --  输入 ip 地址
            mac     --  输出 mac 地址
   return: E_XXXX */
int32_t mac_generate_from_ip(uint32_t ip, uint8_t *mac)
{
    uint32_t temp = 0;

    if (NULL == mac)
    {
        return E_BAD_PARAM;
    }
    usleep(10000);
    /* 产生 mac. */
    srand(time(NULL));
    temp = rand();
    mac[0] = 0x68;
    mac[1] = temp & 0xff;
    mac[2] = (temp >> 8) & 0xff;
    mac[3] = (ip >> 8) & 0xff;
    mac[4] = (ip >> 16) & 0xff;
    mac[5] = (ip >> 24) & 0xff;

    return E_NONE;
}

/* description: 计算CRC16/MODBUS.
   param:   data    --  数据
            size    --  数据长度
   return: 计算的crc值 */
uint16_t crc16(uint8_t *data, uint16_t size)
{
    uint16_t crc = 0xFFFF;
    uint8_t i = 0;
    
    while(size--)
    {
        crc = crc ^ *data++;
        for(i = 0; i < 8; i++)
        {
            if ((crc & 0x0001) > 0)
            {
                crc = crc >> 1;
                crc = crc ^ 0xa001;
            }
            else
                crc = crc >> 1;
        }
    }
    
    return crc;
}

void invert_uint8(unsigned char *dest_buf, unsigned char *src_buf)
{
    int i;
    unsigned char tmp[4];
    tmp[0] = 0;
    
    for (i = 0; i < 8; i++)
    {
        if (src_buf[0] & (1 << i))
            tmp[0] |= 1 << (7 - i);
    }
    dest_buf[0] = tmp[0];
}

void invert_uint16(unsigned short *dest_buf, unsigned short *src_buf)
{
    int i;
    unsigned short tmp[4];
    tmp[0] = 0;
    
    for (i = 0; i < 16; i++)
    {
        if (src_buf[0] & (1 << i))
            tmp[0] |= 1 << (15 - i);
    }
    dest_buf[0] = tmp[0];
}

uint16_t crc16_modbus(uint8_t *data, uint16_t size)
{
    unsigned short wCRCin = 0xFFFF;
    unsigned short wCPoly = 0x8005;
    unsigned char wChar = 0;

    while (size--)
    {
        wChar = *(data++);
        invert_uint8(&wChar, &wChar);
        wCRCin ^= (wChar << 8);
        int i = 0;
        for (i = 0; i < 8; i++)
        {
            if (wCRCin & 0x8000)
                wCRCin = (wCRCin << 1) ^ wCPoly;
            else
                wCRCin = wCRCin << 1;
        }
    }
    invert_uint16(&wCRCin, &wCRCin);
    return (wCRCin);
}

/* description: 计算 CRC32
   param: crc   -- 前一次 CRC32
          buf   -- 数据
          len   -- 数据长度
   return: 计算的crc值 */
unsigned int crc32(unsigned int crc, char *buf, unsigned long len)
{
    const char *s = (const char *)buf;

    while (len)
    {
        crc = Crc32Table[(crc ^ *s++) & 0xff] ^ (crc >> 8);
        len --;
    }
    return crc;
}

/* description: 时间统计开始.
   param:
   return: */
void speed_detection_stat(void)
{
    gettimeofday(&sd_start, NULL);
}

/* description: 时间统计结束.
   param:
   return: */
void speed_detection_end(void)
{
    float timeuse;

    gettimeofday(&sd_end, NULL);

    timeuse = 1000000 * (sd_end.tv_sec - sd_start.tv_sec) + sd_end.tv_usec - sd_start.tv_usec;
    timeuse /= 1000000;
    printh("Used Time:%f\r\n", timeuse);
}

/* description: 通用打印函数.
   param:
   return: */
int printh(const char *format, ...)
{
    va_list args;

    va_start(args, format);
    vty_print(format, args);
    va_end(args);

    return 0;
}

/* description: 获取int16_t类型的版本号.
   param:
   return: int16_t类型的版本号 */
uint16_t sofrware_version_get(void)
{
    char version_str[16];
    char *str = NULL;
    char *p = NULL;
    uint16_t version = 0;

    snprintf(version_str, 16, "%s", version_get());
    str = strtok_r(version_str, ".", &p);
    while(str != NULL)
    {
        version = version << 8;
        version |= (uint8_t)(atoi(str));
        str = strtok_r(NULL, ".", &p);
    }
    
    return version;
}

/* description: 根据传入的字符串转换成mac地址.
   param:
   return: */
int32_t str_to_mac(char *mac_str, OUT uint8_t *mac)
{
    char *str = NULL;
    char *p = NULL;
    uint8_t len = 0;
    uint8_t i = 0;

    /* 按:分词 */
    str = strtok_r(mac_str, ":", &p);
    while(str != NULL)
    {
        /* 检查mac长度 */
        if (len >= 6)
        {
            return E_BAD_PARAM;
        }
    
        /* 检查字符串 */
        for(i = 0; str[i] && str[i] != '\0'; i++)
        {
            if (!((str[i] >= '0' && str[i] <= '9')
                || (str[i] >= 'a' && str[i] <= 'f')
                || (str[i] >= 'A' && str[i] <= 'F')))
            {
                return E_BAD_PARAM;
            }
        }

        /* 检查数据长度 */
        if (i != 2)
        {
            return E_BAD_PARAM;
        }
        mac[len++] = strtol(str, NULL, 16);

        /* 获取下个数据 */
        str = strtok_r(NULL, ":", &p);
    }

    return E_NONE;
}

/* description: 根据传入的字符串转换成设备id.
   param:
   return: */
int32_t str_to_id(char *id_str, OUT uint32_t *id)
{
    char *str = NULL;
    char *p = NULL;
    uint8_t len = 0;
    uint8_t i = 0;

    /* 按 . 分词 */
    str = strtok_r(id_str, ".", &p);
    while(str != NULL && len < 2)
    {
        /* 检查id长度 */
        if (len >= 2)
        {
            return E_BAD_PARAM;
        }
        
        /* 检查字符串 */
        for(i = 0; str[i] && str[i] != '\0'; i++)
        {
            if (!(str[i] >= '0' && str[i] <= '9'))
            {
                return E_BAD_PARAM;
            }
        }

        id[len++] = strtol(str, NULL, 10);

        /* 获取下个数据 */
        str = strtok_r(NULL, ".", &p);
    }

    return E_NONE;
}

int32_t bitmap_set(uint8_t *buf, int32_t nbit, int32_t buf_len)
{
    if ((NULL == buf) || (nbit >= buf_len * 8))
    {
        return E_BAD_PARAM;
    }

    buf[nbit / 8] |= 1 << (nbit % 8);

    return E_NONE;
}

int32_t bitmap_reset(uint8_t *buf, int32_t nbit, int32_t buf_len)
{
    if ((NULL == buf) || (nbit >= buf_len * 8))
    {
        return E_BAD_PARAM;
    }

    buf[nbit / 8] &= ~(1 << (nbit % 8));

    return E_NONE;
}

int32_t is_bitmap_set(uint8_t *buf, int32_t nbit, int32_t buf_len)
{
    if ((NULL == buf) || (nbit >= buf_len * 8))
    {
        return FALSE;
    }

    return buf[nbit / 8] & (1 << (nbit % 8));
}

int32_t time_str_to_long(char *date, char *time, uint32_t *t)
{
    struct tm stm;
    int32_t year, month, day, hour, minute,second;
    
    if (sscanf(date, "%d-%d-%d", &year, &month, &day) != 3)
    {
        return E_BAD_PARAM;
    }
    if (sscanf(time, "%d:%d:%d", &hour, &minute, &second) != 3)
    {
        return E_BAD_PARAM;
    }    

    stm.tm_year = year - 1900;
    stm.tm_mon = month - 1;
    stm.tm_mday = day;
    stm.tm_hour = hour;
    stm.tm_min = minute;
    stm.tm_sec = second;
    stm.tm_isdst = 0;
    *t = mktime(&stm);

    return E_NONE;
}

uint16_t version_str_to_int(void)
{
    uint32_t version_m = 0;
    uint32_t version_s = 0;
    uint32_t version_hm = 0;
    uint32_t version_hs = 0;
    uint32_t n = 0;

    n = sscanf(version_get(), "%d.%d.%d.%d", &version_hm, &version_hs, &version_m, &version_s);
    if (n != 4)
    {
        return 0xffff;
    }

    return (version_m << 8 | (version_s & 0xff)) & 0xffff;
}

void time_set(time_t timestamp)
{
    struct tm *p =localtime(&timestamp); 
    struct tm tptr = {0};
    struct timeval tv = {0};

    tptr.tm_year = p->tm_year;
    tptr.tm_mon = p->tm_mon;
    tptr.tm_mday = p->tm_mday;
    tptr.tm_hour = p->tm_hour;
    tptr.tm_min = p->tm_min;
    tptr.tm_sec = p->tm_sec;

    tv.tv_sec = mktime(&tptr);
    tv.tv_usec = 0;
    settimeofday(&tv, NULL);
}

int32_t create_thread(thread_func_t func, thread_param_t *pParam)
{
    pthread_attr_t attr;
    struct sched_param param;
    pthread_t pid;
    int32_t rv = 0;
    
    /* 配置线程RR调度, 优先级40 */
    pthread_attr_init(&attr);
    param.sched_priority = pParam->priority;
    pthread_attr_setschedpolicy(&attr, SCHED_RR);
    pthread_attr_setschedparam(&attr, &param);
    pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED);
    rv = pthread_create(&pid, &attr, func, pParam->arg);
    if (rv != 0)
    {
        log_err(pParam->log_module, "PD can't create %s pthread %d!", pParam->thread_name, rv);
        return E_SYS_CALL;
    }
    else
    {
        thread_m_add(pParam->thread_name, pid);
    }
    pthread_attr_destroy(&attr);
    return E_NONE;
}

/************************ (C) COPYRIGHT LandPower ***** END OF FILE ****************/
