/*
 * @Author: mbw
 * @Date: 2024-10-10 15:50:39
 * @LastEditors: mbw && 1600520629@qq.com
 * @LastEditTime: 2025-01-10 11:43:48
 * @FilePath: \JT-DT-YD4N02A_RTT_MRS-NT26K\applications\user_sys.c
 * @Description:
 *
 * Copyright (c) 2024 by ${git_name_email}, All Rights Reserved.
 */
#include "user_sys.h"
#include "board.h"
#include "ctype.h"
#include "rtthread.h"
#include "stdlib.h"
#include "bsp_adc.h"
#include "bsp_beep.h"
#include "bsp_led.h"
#include"bsp_button.h"
#include "bsp_emv.h"
#include "bsp_rtc.h"
#include "bsp_flash.h"
#include "bsp_h308.h"
#include "bsp_hr.h"
#include "bsp_nt26k.h"
#include "bsp_relay.h"
#include "bsp_vin_detection.h"
#include "bsp_wdg.h"
#include "rtdef.h"
#include "bsp_rng.h"
#include "at_device_nt26k.h"
#include <stdlib.h> // 包含stdlib.h以使用rand()和srand()

#define LOG_TAG "user_sys"
#define LOG_LVL LOG_LVL_DBG
#include <ulog.h>


#define K 3 * 1000

volatile rt_uint16_t work_duration    = 1; // 工作时长
volatile rt_uint8_t device_life_check = 0;
volatile rt_uint8_t device_state_flag = 0; // 设备失效标志

//CRC16-xmode校验
unsigned short crc1021(const char *data, unsigned int length)
{
    uint16_t crc = 0;
    for( ; length > 0; length--)
    {
    	crc = crc ^ (*data++ << 8);
    	for(int i=0; i < 8; i++)
    	{
    		if(crc & 0x8000)
    			crc = (crc << 1) ^ 0x1021;
    		else
    			crc <<= 1;
    	}
    	crc &= 0xFFFF;
    }
    return crc;

}
void HexStrToBytes(const char *hexString, unsigned char *byteArray, size_t byteCount)
{
    size_t length = byteCount / 2;

    for (size_t i = 0; i < length; i++)
    {
        unsigned char high = hexString[2 * i];     // 高位字符
        unsigned char low  = hexString[2 * i + 1]; // 低位字符

        // 将高位和低位字符转换为对应的字节
        if (high >= '0' && high <= '9')
        {
            high = high - '0';
        }
        else if (high >= 'A' && high <= 'F')
        {
            high = high - 'A' + 10;
        }
        else if (high >= 'a' && high <= 'f')
        {
            high = high - 'a' + 10;
        }
        else
        {
            rt_kprintf("无效的十六进制字符: %c\n", high);
        }

        if (low >= '0' && low <= '9')
        {
            low = low - '0';
        }
        else if (low >= 'A' && low <= 'F')
        {
            low = low - 'A' + 10;
        }
        else if (low >= 'a' && low <= 'f')
        {
            low = low - 'a' + 10;
        }
        else
        {
            rt_kprintf("无效的十六进制字符: %c\n", low);
        }

        byteArray[i] = (high << 4) | low; // 将高位和低位合并为一个字节
    }
}

// Convert strings to hexadecimal strings and store them in hex_arry
void String2Hex(char *hex_arry, char *str)
{
    rt_memset(hex_arry, 0, 2 * (rt_strlen(str) + 1));
    for (int i = 0; i < rt_strlen(str); i++)
    {
        rt_sprintf(hex_arry + (i * 2), "%02X", str[i]);
    }
}

unsigned int ExtractVer(const char **version_ptr)
{
    unsigned int value = 0;
    while (isdigit(**version_ptr))
    {
        value = value * 10 + (**version_ptr - '0');
        (*version_ptr)++;
    }
    return value;
}

// 分割字符串为行
// 提取特定键的值
int Extract_Value(const char *str, const char *key)
{
    const char *start = rt_strstr(str, key);
    if (start == NULL)
    {
        return -1;
    }
    start += rt_strlen(key);
    const char *end = start;

    while (*end != '\n' && *end != '\0')
    {
        end++;
    }
    char value_str[end - start + 1];
    rt_strncpy(value_str, start, end - start);
    value_str[end - start] = '\0';

    return atoi(value_str); // 将字符串转换为整数
}

unsigned int VerToHex(const char *version)
{
    // 确保字符串以 'V' 或 'v' 开头
    if (version == NULL || (version[0] != 'V' && version[0] != 'v'))
    {
        return 0; // 错误处理
    }

    const char *ptr = version + 1; // 跳过 'V' 或 'v'

    // 提取主版本号
    unsigned int major = ExtractVer(&ptr);
    if (*ptr != '.')
    {
        return 0; // 错误处理，缺少点号
    }
    ptr++; // 跳过点号

    // 提取次版本号
    unsigned int minor = ExtractVer(&ptr);

    // 计算最终的十六进制值
    unsigned int result = (major << 4) | minor; // 使用位运算左移

    return result;
}

uint32_t ip_to_uint32(const char *ip_str)
{
    uint32_t ip = 0;
    int octet   = 0; // 0-3
    int part    = 0; // 0-3

    while (*ip_str)
    {
        if (*ip_str == '.')
        {
            if (octet > 3 || part > 255)
            {
                return 0; // 无效的 IP 地址
            }
            ip |= (part << (24 - octet * 8));
            octet++;
            part = 0;
        }
        else
        {
            part = part * 10 + (*ip_str - '0');
        }
        ip_str++;
    }

    if (octet != 3 || part > 255)
    {
        return 0; // 无效的 IP 地址
    }

    ip |= (part << (24 - octet * 8));
    return ip;
}

int Convert_To_Hex(const struct flash_sever_info *sever_info, uint8_t *hex_array)
{
    // 将 IP 地址转换为字节数组
    uint32_t ip_addr = ip_to_uint32(sever_info->server_url);
    if (ip_addr == 0)
    {
        rt_kprintf("Invalid IP address\n");
        return -RT_ERROR;
    }

    // 将 IP 地址的 4 个字节复制到 hex_array
    rt_memcpy(hex_array, &ip_addr, 4);

    uint16_t port = strtol(sever_info->server_port, NULL, 10);
    rt_memcpy(hex_array + 4, &port, 2);

    return RT_EOK;
}

// 利用IMEI号进行错峰延时计算
rt_uint32_t IMEI_Delay(void)
{
    char imei_str[16];
    char randon_char[6] = {0}; // 调整数组大小为6
    rt_uint32_t random_number = 0;

    Get_IotImei(imei_str, FLASH_IOT_IMEI_LEN);
    // 提取 IMEI 的最后 5 位作为种子
    rt_strncpy(randon_char, &imei_str[FLASH_IOT_IMEI_LEN - 5], 5);
    random_number = atoi(randon_char);
    // 生成随机数
    rt_uint32_t  imei_delay = (random_number  + Get_RandomNumber()) % K;
    LOG_I("imei_delay: %d", imei_delay);
    return imei_delay;
}


int BSP_SYS_Init(void)
{
    BSP_RTC_Init();
    BSP_Rng_Init();
    BSP_WDG_Init();
    BSP_LED_Init();
    BSP_RELAY_Init();
    BSP_BEEP_Init();
    BSP_EMV_Init();
    BSP_BUTTON_Init();
    BSP_HR_Init();
    BSP_Nt26k_Thread_Init();
    return 0;
}
// INIT_ENV_EXPORT(BSP_SYS_Init);

