#include "tools.h"


char* uuid(){
    static char uuid_str[9];
    u32 time_stamp = HAL_GetTick();
    u32 random_part = rand();
    snprintf(uuid_str, 9,  // 16 位 UUID（8 个字符 + 空终止符）
             "%04lX%04lX",
             (unsigned long)(time_stamp & 0xFFFF),
             (unsigned long)(random_part & 0xFFFF));

    return uuid_str;
}


void send_blocks(float* arr, char* uuid_str){
    // 按块处理 每个块的最大字符数（最多存储1000个浮点数的字符串）
    char* block = (char*) mymalloc(SRAMEX,sizeof(char)*100*100);
    memset(block, 0 ,sizeof(char)*100*100);
    int block_index = 0;
    int _total_len = 0;
    int total_len = 0;

    for (int i = 0; i < 100; ++i) {
        for (int j = 0; j < 100; ++j) {
            int n = snprintf(block + block_index, 100 * 100 - block_index, "%.6f|", arr[i * 100 + j]);
            block_index += n;
            if (block_index >= 7000) {
                block_index = 0;  // 重置块
                _total_len++;
            }
        }
    }
    if (!block_index)_total_len--;

    block_index = 0;
    for (int i = 0; i < 100; ++i) {
        for (int j = 0; j < 100; ++j) {
            int n = snprintf(block + block_index, 100*100 - block_index, "%.6f|", arr[i*100+j]);
            block_index += n;
            if (block_index >= 7000) {
                char* _block = (char*) mymalloc(SRAMEX,sizeof(char)*100*100);
                memset(_block, 0 ,sizeof(char)*100*100);
                block_index = 0;  // 重置块
                sprintf(_block, "{\\\"uuid\\\":\\\"%s\\\",\\\"Bid\\\":\\\"%d\\\",\\\"Eid\\\":\\\"%d\\\",\\\"Block\\\":\\\"%s\\\"}\n", uuid_str, total_len++, _total_len, block);
                //DEBUG_PRINTF("%s", _block);
							
                CSTX_4G_ALiYunIOTSenddata_string(_block,"data_string");
				myfree(SRAMEX,_block);
                _block = NULL;
            }
        }
    }

    // 输出最后一个块
    if (block_index > 0) {
        char* _block = (char*) mymalloc(SRAMEX,sizeof(char)*100*100);
        memset(_block, 0 ,sizeof(char)*100*100);
        block_index = 0;
				sprintf(_block, "{\\\"uuid\\\":\\\"%s\\\",\\\"Bid\\\":\\\"%d\\\",\\\"Eid\\\":\\\"%d\\\",\\\"Block\\\":\\\"%s\\\"}\n", uuid_str, total_len, _total_len, block);
        //DEBUG_PRINTF("%s", _block);
        CSTX_4G_ALiYunIOTSenddata_string(_block,"data_string");
		myfree(SRAMEX,_block);
        _block = NULL;
    }

    myfree(SRAMEX,block);
    block = NULL;
}
