#include "cJSON.h"
#include "stdint.h"
#include "stddef.h"
#include "dbug.h"
#include "djyos.h"
#include <math.h>
#include "Iboot_info.h"
#include "Modbus_PCS.h"
#include "mb.h"
#include "mb_m.h"
#include "OtherMessage.h"
#include "project_config.h"
#include <main.h>

static bool_t DTU_Reset = false; 
enum eRetMessageSet PCS_ErrCode = DTU_RET_SUCCESS;

static const char *QMqtt_group[] = 
{
    "reg",                              //注册
    "event_faultReport",                //故障上报指令
    "query_reg",                        //查询注册信息
    "query_DTU_Status",                 //查询状态
    "query_PCS_productInfo",            //查询产品信息
    "query_PCS_ControllerData",         //查询控制器数据
    "query_PCS_InverterData",           //查询逆变器数据
    "query_PCS_Recent7DayStatData",     //逆变器历史一周统计数据查询指令
    "query_PCS_TodayStatData",          //当天统计数据查询指令
    "query_PCS_TotalStatData",          //统计历史总数据查询指令
    "query_PCS_FaultData",              //查询历史故障数据
    "query_PCS_PackParam",              //查询电池参数设定
    "query_PCS_InverterParam",          //查询逆变器参数设定
    "ctrl_PCS_Switch",                  //开关机
    "ctrl_PCS_Reset",                   //复位
    "ctrl_PCS_FactoryResetControl",     //恢复出厂设置
    "ctrl_PCS_ClearHistory",            //清楚历史数据
    "ctrl_PCS_EqualizeCharge",          //立即均衡充电控制指令
    "ctrl_PCS_PackParam",               //电池参数设定指令
    "ctrl_PCS_InverterParam",           //逆变器参数设定指令
    "ctrl_setTime",                     //修改设备时间指令
    "ctrl_dtu_restart"                  //重启控制
};

u16 Fault_code[4];
u8 errlog_PCSBTS[CFG_OTHER_ERROR_MESSAGE_MAX_LENGTH] = {0};

// 获取PCS错误日志
u8 *GetPCS_ErrorLog()
{
    // 只有错误代码为DTU_RET_OTHER_ERR或DTU_RET_MODBUS,错误日志才有效
    return errlog_PCSBTS;
}

// 获取PCS错误代码
enum eRetMessageSet GetPCS_ErrorCode()
{
    return PCS_ErrCode;
}

bool_t GetDTU_ResetFlag(void)
{
    return DTU_Reset;
}

cJSON *CreateRetJson(u8 cmd, bool_t data, bool_t DevID)
{
    cJSON *json = NULL;
    cJSON *json_payload = NULL;
    cJSON *json_data = NULL;

    if (cmd >= sizeof(QMqtt_group))
    {
        error_printf("PCS", "cmd is %d , error\r\n", cmd);
        return NULL;
    }

    json = cJSON_CreateObject();
    if (NULL == json)
    {
        error_printf("PCS", "json is NULL\r\n");
        strncpy(errlog_PCSBTS, "json creat fail", sizeof(errlog_PCSBTS));
        PCS_ErrCode = DTU_RET_OTHER_ERR;
    }
    else
    {
        json_payload = cJSON_CreateObject();
        if (json_payload == NULL)
        {
            error_printf("PCS", "json_payload is NULL\r\n");
            strncpy(errlog_PCSBTS, "json creat fail", sizeof(errlog_PCSBTS));
            PCS_ErrCode = DTU_RET_OTHER_ERR;
            cJSON_Delete(json);
            json = NULL;
        }
        else
        {
            cJSON_AddItemToObject(json, "payload", json_payload);
            cJSON_AddStringToObject(json, "cmd", QMqtt_group[cmd]);
            cJSON_AddNumberToObject(json, "msgId", GetServerMessageID());
            cJSON_AddNumberToObject(json_payload, "code", 0);
            cJSON_AddStringToObject(json_payload, "message", "success");
            if (DevID)
            {
                cJSON_AddStringToObject(json_payload, "deviceId", GetServerDevID());
            }

            if (data)
            {
                json_data = cJSON_CreateObject();
                if (json_data == NULL)
                {
                    error_printf("PCS", "json_payload is NULL\r\n");
                    strncpy(errlog_PCSBTS, "json creat fail", sizeof(errlog_PCSBTS));
                    PCS_ErrCode = DTU_RET_OTHER_ERR;
                    cJSON_Delete(json);
                    json = NULL;
                }
                else
                {
                    cJSON_AddItemToObject(json_payload, "data", json_data);

                }
            }
        }
    }
    return json;
}

#define CFG_SOFT_HARD_VERSION_MAX_LENGTH        6       //软硬件版本最长6字节  
#define CFG_MODBUS_ERR_MESSAGE_MAX_LENGTH       32       //modbus错误消息最大长度
bool_t Magnification(u16 num, char *arr, u32 arr_len, int Several)//num是原始数据，arr是装载的容器，Several是保留小数点后几位
{
    u8 Temp[128];
    u8 i = 0;
    u8 j = 0;
    memset(arr, 0, arr_len);
    if (0 != Several)
    {
        while (num)
        {
            Temp[i ++] = num % 10 + '0';
            num /= 10;
            if (i == Several)
            {
                break;
            }
        }

        while (i != Several)
        {
            Temp[i ++] = '0';
        }

        Temp[i ++] = '.';
        if(num == 0)
        {
            Temp[i++] = '0';
        }
    }
    while (num)
    {
        Temp[i ++] = num % 10 + '0';
        num /= 10;
    }

    if (i <= arr_len)
    {
        for (j = 0; j < i; j++)
        {
            arr[j] = Temp[i - j - 1];
        }
        return true;
    }

    return false;
}

// 处理modbus执行结果,有问题的话设置好错误代码和错误日志
enum eRetMessageSet GetModbusErrMessage(eMBMasterReqErrCode e1, eMBErrorCode e2)
{
    enum eRetMessageSet Ret = DTU_RET_MODBUS;
    if (e1 == MB_MRE_NO_ERR && e2 == MB_MRE_NO_ERR)
    {
        // strncpy(MessageBuf, "success", BufLen);
        Ret = DTU_RET_SUCCESS;
    }
    else if (e1 == MB_MRE_NO_REG||e2 == MB_MRE_NO_REG)
    {
        strncpy(errlog_PCSBTS, "NoReg", sizeof(errlog_PCSBTS));
        error_printf("PCS", "modbus error message . NoReg\r\n");
    }
    else if (e1 == MB_MRE_ILL_ARG||e2 == MB_MRE_ILL_ARG)
    {
        strncpy(errlog_PCSBTS, "IllArg", sizeof(errlog_PCSBTS));
        error_printf("PCS", "modbus error message . IllArg\r\n");
    }
    else if (e1 == MB_MRE_REV_DATA||e2 == MB_MRE_REV_DATA)
    {
        strncpy(errlog_PCSBTS, "RevData", sizeof(errlog_PCSBTS));
        error_printf("PCS", "modbus error message . RevData\r\n");
    }
    else if (e1 == MB_MRE_TIMEDOUT||e2 == MB_MRE_TIMEDOUT)
    {
        // strncpy(MessageBuf, "Timeout", BufLen);
        Ret = DTU_RET_TIMEOUT;
        error_printf("PCS", "modbus error message . Timeout\r\n");
    }
    else if (e1 == MB_MRE_EXE_FUN||e2 == MB_MRE_EXE_FUN)
    {
        strncpy(errlog_PCSBTS, "ExeFun", sizeof(errlog_PCSBTS));
        error_printf("PCS", "modbus error message . ExeFun\r\n");
    }
    else
    {
        strncpy(errlog_PCSBTS, "unknown", sizeof(errlog_PCSBTS));
        error_printf("PCS", "modbus error message . unknown\r\n");
    }
    return Ret;
}

enum eRetMessageSet ModbusSlaveAddressIsValid(u32 Addr)
{
    enum eRetMessageSet Ret = 0;
    if ((Addr > 0) && (Addr <= CFG_MB_MASTER_TOTAL_SLAVE_NUM))
    {
        Ret = 0;
    }
    else
    {
        //设备不存在
        Ret = DTU_RET_DEV_NOT_EXIST;
        error_printf("PCS", "dev addr(%d) is not exist\r\n", Addr);
    }

    return Ret;
}




/* char *Wrong_instruction(char *json_data, int code) //指令不存在或者参数不对
{
    cJSON *json = cJSON_Parse(json_data);

    cJSON *msgId = cJSON_GetObjectItem(json, "msgId");
    cJSON *payload_1 = cJSON_GetObjectItem(json, "payload");
    cJSON *deviceId = cJSON_GetObjectItem(payload_1, "deviceId");

    cJSON *QProduct_information = cJSON_CreateObject();
    char *message;
    if (msgId->valueint != NULL)
    {
        cJSON_AddNumberToObject(QProduct_information, "msgId", msgId->valueint);
    }
    if (code == 5)
    {
        message = "device not support cmd";
    }
    else if (code == 2)
    {
        message = "param error";
    }
    cJSON *payload = cJSON_CreateObject();
    cJSON_AddNumberToObject(payload, "code", code);
    cJSON_AddStringToObject(payload, "message", message);
    cJSON_AddStringToObject(payload, "deviceId", deviceId->valuestring);
    cJSON *data = cJSON_CreateObject();
    cJSON_AddItemToObject(payload, "data", data);
    cJSON_AddItemToObject(QProduct_information, "payload", payload);
    json_data = cJSON_Print(QProduct_information);
    cJSON_Delete(QProduct_information);
    cJSON_Delete(json);
    return json_data;
} */
char *Registration_Instructions(char *json_data) //注册指令
{
    // char convert[20];
    // char* hardwareVersion[40];
    // char* softwareVersion[40];
    // eMBMasterReqErrCode e1,e3,e5;
    // eMBErrorCode e2,e4,e6;
    // e2=MB_ENOERR;
    // u16 product_ID[20],buf[9],Device_status[0];//产品序列号字符串
    // char productID[21];
    // /* for(int i=0;i<5;i++ )
    // { */
    //     DJY_EventDelay(10*1000);
    //     e1=eMBMasterReqReadHoldingRegister(1,53,20,-1);
    //     e2=eMBMasterRegHoldingCBGet(1,product_ID,53,20);
    //     if(e1==MB_MRE_NO_ERR&&e2==MB_MRE_NO_ERR)
    //     {
    //         break;
    //     }
    // /* } */
    //  uint8_t low_bits[20] = {0};
    //  for (int i = 0; i < 20; i++) {
    //      low_bits[i] = product_ID[i]& 0xFF;
    //      sprintf(productID + i, "%d", low_bits[i]);
    //  }

    // for(int i=0;i<5;i++ )
    // {
    //     e3=eMBMasterReqReadHoldingRegister(1,26,9,-1);
    //     e4=eMBMasterRegHoldingCBGet(1,buf,26,9);
    //     e5=eMBMasterReqReadHoldingRegister(1,528,1,-1);
    //     e6=eMBMasterRegHoldingCBGet(1,Device_status,528,1);
    //     if(e3==MB_MRE_NO_ERR&&e4==MB_MRE_NO_ERR&&e5==MB_MRE_NO_ERR&&e6==MB_MRE_NO_ERR)
    //     {
    //         break;
    //     }
    // }
    // int address_pcs=buf[5];//逆变器地址
    // double softwareVersion_1=1.0*buf[0]/100;//软件版本
    // double softwareVersion_2=1.0*buf[1]/100;//软件版本
    // double hardwareVersion_1=1.0*buf[2]/100;//硬件版本
    // double hardwareVersion_2=1.0*buf[3]/100;//硬件版本
    // double RS485_protocol_version=buf[7];//RS485协议版本
    // int devicestatus_pcs=Device_status[0];//逆变器设备状态

    // char softVersion[10];//DTU当前软件版本
    // Iboot_GetProductInfo(APP_HEAD_VERSION_NUM,softVersion,10);

    // char dtuMode[10];//DTU的型号
    // Iboot_GetProductInfo(APP_HEAD_TYPE,dtuMode,10);

    // char deviceSN[7];//DTU的序列号
    // Iboot_GetProductInfo(APP_HEAD_TYPE_CODE,deviceSN,7);
    // deviceSN[6]='\0';

    // char prefix[] = "1_1_";
    // char str[10] = "";
    // strcat(str, prefix);
    // sprintf(str + strlen(str), "%d", address_pcs);

    // cJSON *Registration_Instructions = cJSON_CreateObject();
    // cJSON_AddStringToObject(Registration_Instructions,"cmd","reg");

    // cJSON *payload  = cJSON_CreateObject();
    // cJSON_AddStringToObject(payload,"softVersion",softVersion);

    //  cJSON *gps  = cJSON_CreateObject();             //创建一个对象
    // cJSON_AddNumberToObject(gps,"longitude",111); //添加字符串
    // cJSON_AddNumberToObject(gps,"latitude",123456); //添加整型数字
    // cJSON_AddItemToObject(payload,"gps",gps);

    // cJSON_AddStringToObject(payload,"deviceSN",deviceSN);
    // cJSON_AddStringToObject(payload,"dtuMode",dtuMode);
    // cJSON_AddNumberToObject(payload,"dtuStatus",1);

    // cJSON *device  = cJSON_CreateObject();

    // cJSON *bms_1  = cJSON_CreateArray();
    // cJSON *bms  = cJSON_CreateObject();
    // cJSON_AddStringToObject(bms,"deviceSN",productID);
    // cJSON_AddStringToObject(bms,"deviceId",24);
    // cJSON_AddStringToObject(bms,"protocolVersion",24);
    // cJSON_AddNumberToObject(bms,"deviceManufacturer",2);
    // cJSON_AddNumberToObject(bms,"softwareVersion",0);
    // cJSON_AddStringToObject(bms,"hardwareVersion",24);
    // cJSON_AddNumberToObject(bms,"deviceStatus",24);
    // cJSON_AddItemToArray(bms_1,bms);
    // cJSON_AddItemToObject(device,"bms",bms_1);

    // cJSON *pcs_1  = cJSON_CreateArray();
    // cJSON *pcs  = cJSON_CreateObject();
    // cJSON_AddStringToObject(pcs,"deviceSN","B");
    // cJSON_AddStringToObject(pcs,"deviceId",str);

    // sprintf(convert, "%.2f", RS485_protocol_version);
    // cJSON_AddStringToObject(pcs,"protocolVersion",convert);

    // cJSON_AddNumberToObject(pcs,"deviceManufacturer",4);

    // strcpy(softwareVersion, "cpu1:V");
    // sprintf(convert, "%.2f", softwareVersion_1);
    // strcat(softwareVersion, convert);

    // strcat(softwareVersion, ",cpu2:V");
    // sprintf(convert, "%.2f", softwareVersion_2);
    // strcat(softwareVersion, convert);

    // cJSON_AddStringToObject(pcs,"softwareVersion",softwareVersion);

    // strcpy(hardwareVersion, "control:V");
    // sprintf(convert, "%.2f", hardwareVersion_1);
    // strcat(hardwareVersion, convert);

    // strcat(hardwareVersion, ",power:V");
    // sprintf(convert, "%.2f", hardwareVersion_2);
    // strcat(hardwareVersion, convert);

    // cJSON_AddStringToObject(pcs,"hardwareVersion",hardwareVersion);

    // cJSON_AddNumberToObject(pcs,"deviceStatus",devicestatus_pcs);
    // cJSON_AddItemToArray(pcs_1,pcs);               //添加对象到数组中

    // cJSON_AddItemToObject(device,"pcs",pcs_1);   //添加数组到对象中

    // cJSON_AddItemToObject(payload,"device",device);
    // cJSON_AddNumberToObject(payload,"regTime",1);
    // cJSON_AddItemToObject(Registration_Instructions,"payload",payload);
    // json_data= cJSON_Print(Registration_Instructions);

    // cJSON_Delete(Registration_Instructions);
    return json_data;
}

// 暂时不用,先不处理
char *Fault_reporting(void) //故障上报指令
{
    u8 *Ret = NULL;
    // u32 Addr = 0;
    // cJSON *json = NULL;
    // cJSON *json_payload = NULL;
    // eMBMasterReqErrCode e1;
    // eMBErrorCode e2;

    // Addr = GetServerAddr();
    // // code = ModbusSlaveAddressIsValid(Addr, message, sizeof(message));

    // // int record_1=0,record_2=0,record_3=0,record_4=0;
    // int failurefrequency = 0;
    // u16 Fault_code[4];

    // DJY_EventDelay(100 * 1000);
    // e1 = eMBMasterReqReadHoldingRegister(Addr, 516, 4, -1);
    // e2 = eMBMasterRegHoldingCBGet(Addr, Fault_code, 516, 4);

    // if (Fault_code[0] != 0 || Fault_code[1] != 0 || Fault_code[2] != 0 || Fault_code[3] != 0)                                   //不等于0说明有有故障
    // {
    //     json = cJSON_CreateObject();
    //     if (json == NULL)
    //     {
    //         error_printf("PCS", "json is NULL\r\n");
    //         strncpy(errlog_PCSBTS, "Fault json is  NULL", sizeof(errlog_PCSBTS));
    //     }
    //     else
    //     {
    //         json_payload = cJSON_CreateObject();
    //         if (json_payload == NULL)
    //         {
    //             error_printf("PCS", "json_payload is NULL\r\n");
    //             strncpy(errlog_PCSBTS, "Fault json_payload is NULL", sizeof(errlog_PCSBTS));
    //         }
    //         else
    //         {                
    //             cJSON_AddItemToObject(json, "payload", json_payload);

    //             cJSON_AddStringToObject(json, "cmd", QMqtt_group[1]);
    //             cJSON_AddNumberToObject(json, "msgId", GetServerMessageID());
    //             // cJSON *DTU = cJSON_CreateObject();
    //             // if (DTU == NULL)
    //             // {
    //             //     printf("------- json DTU  NULL -------\r\n");
    //             //     strncpy(errlog_PCSBTS, " json DTU  NULL", sizeof(errlog_PCSBTS));
    //             //     return json_data;
    //             // }
    //             // cJSON_AddNumberToObject(DTU, "faultStatus", 0);
    //             // cJSON_AddItemToObject(json_payload, "DTU", DTU);
    //             // cJSON *device = cJSON_CreateObject();
    //             // if (device == NULL)
    //             // {
    //             //     printf("------- json device  NULL -------\r\n");
    //             //     strncpy(errlog_PCSBTS, " json device  NULL", sizeof(errlog_PCSBTS));
    //             //     return json_data;
    //             // }

    //             // TODO:这里的1_1_1后续要改掉，不能这么写死在这里
    //             cJSON_AddStringToObject(json_payload, "deviceId", "1_1_1");
    //             cJSON_AddNumberToObject(json_payload, "faultStatus", 1);

    //             cJSON *currentFault = cJSON_CreateArray();
    //             if (currentFault == NULL)
    //             {
    //                 printf("------- json currentFault  NULL -------\r\n");
    //                 strncpy(errlog_PCSBTS, " json currentFault  NULL", sizeof(errlog_PCSBTS));
    //                 return json_data;
    //             }
    //             if (Fault_code_1 != 0)
    //             {
    //                 cJSON *currentFault_1 = cJSON_CreateObject();
    //                 if (currentFault_1 == NULL)
    //                 {
    //                     printf("------- json currentFault_1  NULL -------\r\n");
    //                     strncpy(errlog_PCSBTS, " json currentFault_1  NULL", sizeof(errlog_PCSBTS));
    //                     return json_data;
    //                 }
    //                 cJSON_AddNumberToObject(currentFault_1, "faultCode", Fault_code_1);
    //                 // cJSON_AddNumberToObject(currentFault_1,"time",24);
    //                 cJSON_AddItemToArray(currentFault, currentFault_1);
    //             }
    //             if (Fault_code_2 != 0)
    //             {
    //                 cJSON *currentFault_2 = cJSON_CreateObject();
    //                 if (currentFault_2 == NULL)
    //                 {
    //                     printf("------- json currentFault_2  NULL -------\r\n");
    //                     strncpy(errlog_PCSBTS, " json currentFault_2  NULL", sizeof(errlog_PCSBTS));
    //                     return json_data;
    //                 }
    //                 cJSON_AddNumberToObject(currentFault_2, "faultCode", Fault_code_2);
    //                 // cJSON_AddNumberToObject(currentFault_2,"time",24);
    //                 cJSON_AddItemToArray(currentFault, currentFault_2);
    //             }
    //             if (Fault_code_3 != 0)
    //             {
    //                 cJSON *currentFault_3 = cJSON_CreateObject();
    //                 if (currentFault_3 == NULL)
    //                 {
    //                     printf("------- json currentFault_3  NULL -------\r\n");
    //                     strncpy(errlog_PCSBTS, " json currentFault_3  NULL", sizeof(errlog_PCSBTS));
    //                     return json_data;
    //                 }
    //                 cJSON_AddNumberToObject(currentFault_3, "faultCode", Fault_code_3);
    //                 // cJSON_AddNumberToObject(currentFault_3,"time",24);
    //                 cJSON_AddItemToArray(currentFault, currentFault_3);
    //             }
    //             if (Fault_code_4 != 0)
    //             {
    //                 cJSON *currentFault_4 = cJSON_CreateObject();
    //                 if (currentFault_4 == NULL)
    //                 {
    //                     printf("------- json currentFault_4  NULL -------\r\n");
    //                     strncpy(errlog_PCSBTS, " json currentFault_4  NULL", sizeof(errlog_PCSBTS));
    //                     return json_data;
    //                 }
    //                 cJSON_AddNumberToObject(currentFault_4, "faultCode", Fault_code_4);
    //                 // cJSON_AddNumberToObject(currentFault_4,"time",24);
    //                 cJSON_AddItemToArray(currentFault, currentFault_4);
    //             }

    //             cJSON_AddItemToObject(device, "currentFault", currentFault);

    //             cJSON_AddItemToObject(json_payload, "device", device);
    //             json_data = cJSON_Print(json);
    //             if (json_data == NULL)
    //             {
    //                 printf("------- json cJSON_Print json_data  NULL -------\r\n");
    //                 strncpy(errlog_PCSBTS, " json cJSON_Print json_data  NULL", sizeof(errlog_PCSBTS));
    //                 return json_data;
    //             }
    //             return json_data;
    //         }
    //     }
    // }

    return Ret;
}

char *QDTU_registration_information(char *json_data) //查询DTU注册信息
{
    /*     char convert[20];
        char* hardwareVersion[40];
        char* softwareVersion[40];
        eMBMasterReqErrCode e1,e3,e5;
        eMBErrorCode e2,e4,e6;
        e2=MB_ENOERR;
        u16 product_ID[20],buf[9],Device_status[20];//产品序列号字符串
        char productID[21];
        for(int i=0;i<5;i++ )
        {
            DJY_EventDelay(10*1000);
            e1=eMBMasterReqReadHoldingRegister(1,53,20,-1);
            e2=eMBMasterRegHoldingCBGet(1,product_ID,53,20);
            if(e1==MB_MRE_NO_ERR&&e2==MB_MRE_NO_ERR)
            {
                break;
            }
        }
         uint8_t low_bits[20] = {0};
         for (int i = 0; i < 20; i++) {
             low_bits[i] = product_ID[i]& 0xFF;
             sprintf(productID + i, "%d", low_bits[i]);
         }
        for(int i=0;i<5;i++ )
        {
            DJY_EventDelay(10*1000);
            e3=eMBMasterReqReadHoldingRegister(1,26,9,-1);
            e4=eMBMasterRegHoldingCBGet(1,buf,26,9);
            e5=eMBMasterReqReadHoldingRegister(1,528,1,-1);
            e6=eMBMasterRegHoldingCBGet(1,Device_status,528,1);
            if(e3==MB_MRE_NO_ERR&&e4==MB_MRE_NO_ERR&&e5==MB_MRE_NO_ERR&&e6==MB_MRE_NO_ERR)
            {
                break;
            }
        }
        double softwareVersion_1=1.0*buf[0]/100;//软件版本
        double softwareVersion_2=1.0*buf[1]/100;//软件版本
        double hardwareVersion_1=1.0*buf[2]/100;//硬件版本
        double hardwareVersion_2=1.0*buf[3]/100;//硬件版本
        double RS485_protocol_version=buf[7];//RS485协议版本
        int devicestatus_pcs=Device_status[0];//逆变器设备状态

        char softVersion[10];//DTU当前软件版本
        Iboot_GetProductInfo(APP_HEAD_VERSION_NUM,softVersion,10);

        char dtuMode[10];//DTU的型号
        Iboot_GetProductInfo(APP_HEAD_TYPE,dtuMode,10);

        char deviceSN[7];//DTU的序列号
        Iboot_GetProductInfo(APP_HEAD_TYPE_CODE,deviceSN,6);
        deviceSN[6]='\0';

        char* message;
        int code;
        if(e1==MB_MRE_NO_ERR||e3==MB_MRE_NO_ERR||e5==MB_MRE_NO_ERR)
        {
            message="NoErr";
            code=0;
        }else if(e1==MB_MRE_NO_REG||e3==MB_MRE_NO_REG||e5==MB_MRE_NO_REG)
        {
            message="NoReg";
            code=8;
        }else if(e1==MB_MRE_ILL_ARG||e3==MB_MRE_ILL_ARG||e5==MB_MRE_ILL_ARG)
        {
            message="IllArg";
            code=8;
        }else if(e1==MB_MRE_REV_DATA||e3==MB_MRE_REV_DATA||e5==MB_MRE_REV_DATA)
        {
            message="RevData";
            code=8;
        }else if(e1==MB_MRE_TIMEDOUT||e3==MB_MRE_TIMEDOUT||e5==MB_MRE_TIMEDOUT)
        {


            message="Timeout";
            code=7;


        }else if(e1==MB_MRE_EXE_FUN||e3==MB_MRE_EXE_FUN||e5==MB_MRE_EXE_FUN)
        {
            message="ExeFun";
            code=8;
        }

        cJSON *QDTU_registration_information = cJSON_CreateObject();
        cJSON_AddStringToObject(QDTU_registration_information,"cmd","query_reg");
        cJSON* json = cJSON_Parse(json_data);
        cJSON* msgId = cJSON_GetObjectItem(json, "msgId");
        if(msgId->valueint!=NULL)
        {
            cJSON_AddNumberToObject(QDTU_registration_information,"msgId",msgId->valueint);
        }

        cJSON *payload  = cJSON_CreateObject();
        cJSON_AddNumberToObject(payload,"code",code);
        cJSON_AddStringToObject(payload,"message",message);
        cJSON_AddStringToObject(payload,"softVersion",softVersion);

        cJSON_AddStringToObject(payload,"deviceSN",deviceSN);
        cJSON_AddStringToObject(payload,"dtuMode",dtuMode);
        cJSON_AddNumberToObject(payload,"dtuStatus",1);

        cJSON *device  = cJSON_CreateObject();

        cJSON *bms_1  = cJSON_CreateArray();
        cJSON *bms  = cJSON_CreateObject();
        cJSON_AddStringToObject(bms,"deviceSN"," ");
        cJSON_AddStringToObject(bms,"deviceId","1_1_2");
        cJSON_AddNumberToObject(bms,"productType",1);
        cJSON_AddStringToObject(bms,"protocolVersion",24);
        cJSON_AddNumberToObject(bms,"deviceManufacturer",0);
        cJSON_AddNumberToObject(bms,"hardwareVersion",24);
        cJSON_AddNumberToObject(bms,"deviceStatus",24);
        cJSON_AddItemToArray(bms_1,bms);
        cJSON_AddItemToObject(device,"bms",bms_1);

        cJSON *pcs_1  = cJSON_CreateArray();
        cJSON *pcs  = cJSON_CreateObject();
        cJSON_AddStringToObject(pcs,"deviceSN",productID);
        cJSON_AddStringToObject(pcs,"deviceId","1_1_1");
        sprintf(convert, "%.2f", RS485_protocol_version);
        cJSON_AddStringToObject(pcs,"protocolVersion",convert);
        cJSON_AddNumberToObject(pcs,"deviceManufacturer",4);

        strcpy(softwareVersion, "cpu1:V");
        sprintf(convert, "%.2f", softwareVersion_1);
        strcat(softwareVersion, convert);

        strcat(softwareVersion, ",cpu2:V");
        sprintf(convert, "%.2f", softwareVersion_2);
        strcat(softwareVersion, convert);

        cJSON_AddStringToObject(pcs,"softwareVersion",softwareVersion);

        strcpy(hardwareVersion, "control:V");
        sprintf(convert, "%.2f", hardwareVersion_1);
        strcat(hardwareVersion, convert);

        strcat(hardwareVersion, ",power:V");
        sprintf(convert, "%.2f", hardwareVersion_2);
        strcat(hardwareVersion, convert);

        cJSON_AddStringToObject(pcs,"hardwareVersion",hardwareVersion);

        cJSON_AddNumberToObject(pcs,"deviceStatus",devicestatus_pcs);

        cJSON_AddItemToArray(pcs_1,pcs);               //添加对象到数组中

        cJSON_AddItemToObject(device,"pcs",pcs_1);   //添加数组到对象中

        cJSON_AddItemToObject(payload,"device",device);
        cJSON_AddNumberToObject(payload,"regTime",1);
        cJSON_AddItemToObject(QDTU_registration_information,"payload",payload);
        json_data = cJSON_Print(QDTU_registration_information);
        cJSON_Delete(json);
        cJSON_Delete(QDTU_registration_information);*/
    return json_data;
}
char *QDTU_device_status(char *json_data) //查询DTU设备状态
{
    /*      eMBMasterReqErrCode e1,e3;
         eMBErrorCode e2,e4;
         e2=MB_ENOERR;
         u16 product_ID[20],Device_status[0];//产品序列号字符串
         char productID[21];
         for(int i=0;i<5;i++ )
         {
             DJY_EventDelay(10*1000);
             e1=eMBMasterReqReadHoldingRegister(1,53,20,-1);
             e2=eMBMasterRegHoldingCBGet(1,product_ID,53,20);
             if(e1==MB_MRE_NO_ERR&&e2==MB_MRE_NO_ERR)
             {
                 break;
             }
         }
         uint8_t low_bits[20] = {0};
         for (int i = 0; i < 20; i++) {
             low_bits[i] = product_ID[i]& 0xFF;
             sprintf(productID + i, "%d", low_bits[i]);
         }

         for(int i=0;i<5;i++ )
         {
             DJY_EventDelay(10*1000);
             e3=eMBMasterReqReadHoldingRegister(1,528,1,-1);
             e4=eMBMasterRegHoldingCBGet(1,Device_status,528,1);
             if(e3==MB_MRE_NO_ERR&&e4==MB_MRE_NO_ERR)
             {
                 break;
             }
         }


        char* message;
        int code;
        if(e1==MB_MRE_NO_ERR||e2==MB_MRE_NO_ERR)
        {
            message="NoErr";
            code=0;
        }else if(e1==MB_MRE_NO_REG||e2==MB_MRE_NO_REG)
        {
            message="NoReg";
            code=8;
        }else if(e1==MB_MRE_ILL_ARG||e2==MB_MRE_ILL_ARG)
        {
            message="IllArg";
            code=8;
        }else if(e1==MB_MRE_REV_DATA||e2==MB_MRE_REV_DATA)
        {
            message="RevData";
            code=8;
        }else if(e1==MB_MRE_TIMEDOUT||e2==MB_MRE_TIMEDOUT)
        {
            message="Timeout";
            code=7;
        }else if(e1==MB_MRE_EXE_FUN||e2==MB_MRE_EXE_FUN)
        {
            message="ExeFun";
            code=8;
        }



        cJSON *QDTU_device_status = cJSON_CreateObject();
        cJSON_AddStringToObject(QDTU_device_status,"cmd","query_DTU_Status");
        cJSON_AddNumberToObject(QDTU_device_status,"msgId",1);

        cJSON *payload  = cJSON_CreateObject();
        cJSON_AddNumberToObject(payload,"softVersion",0);
        cJSON_AddNumberToObject(payload,"code",0);
        cJSON_AddStringToObject(payload,"message","success");
        cJSON_AddNumberToObject(payload,"dtuStatus",1);

        cJSON *device  = cJSON_CreateObject();          //创建一个数组

        cJSON *bms_1  = cJSON_CreateArray();
        cJSON *bms  = cJSON_CreateObject();          //创建一个对象
        cJSON_AddStringToObject(bms,"deviceSN"," ");    //添加字符串
        cJSON_AddStringToObject(bms,"deviceId","1_1_2");  //添加逻辑值
        cJSON_AddNumberToObject(bms,"deviceStatus",25);
        cJSON_AddItemToArray(bms_1,bms);               //添加对象到数组中
        cJSON_AddItemToObject(device,"bms",bms_1);

        cJSON *pcs_1  = cJSON_CreateArray();
        cJSON *pcs  = cJSON_CreateObject();          //创建一个对象
        cJSON_AddStringToObject(pcs,"deviceSN",productID);    //添加字符串
        cJSON_AddStringToObject(pcs,"deviceId","1_1_1");       //添加整型数字
        cJSON_AddNumberToObject(pcs,"deviceStatus",25);
        cJSON_AddItemToArray(pcs_1,pcs);               //添加对象到数组中

        cJSON_AddItemToObject(device,"pcs",pcs_1);   //添加数组到对象中

        cJSON_AddItemToObject(payload,"device",device);
        cJSON_AddNumberToObject(payload,"regTime",1);
        cJSON_AddItemToObject(QDTU_device_status,"payload",payload);
        json_data = cJSON_Print(QDTU_device_status);
        cJSON_Delete(QDTU_device_status);*/
    return json_data;
}

#define CFG_PCS_PRODUCT_LENGTH  20

char *QProduct_information(void) //查询产品信息
{
    u8 *Ret = NULL;
    cJSON *json = NULL;
    cJSON *json_data = NULL;
    cJSON *json_payload = NULL;
    u32 Addr = 0;
    eMBMasterReqErrCode e1;
    eMBErrorCode e2;
    u16 buf[20];
    u16 product_ID[CFG_PCS_PRODUCT_LENGTH];
    char productID[CFG_PCS_PRODUCT_LENGTH + 1];
    char Version1[CFG_SOFT_HARD_VERSION_MAX_LENGTH];
    char Version2[CFG_SOFT_HARD_VERSION_MAX_LENGTH];
    char MergeVersion[32];

    Addr = GetServerAddr();
    PCS_ErrCode = ModbusSlaveAddressIsValid(Addr);
    if (PCS_ErrCode == DTU_RET_SUCCESS)
    {
        DJY_EventDelay(10 * 1000);
        e1 = eMBMasterReqReadHoldingRegister(Addr, 11, 19, -1);
        e2 = eMBMasterRegHoldingCBGet(Addr, buf, 11, 19);
        PCS_ErrCode = GetModbusErrMessage(e1, e2);
        if (PCS_ErrCode == DTU_RET_SUCCESS) //如果上面的超时了就不执行下面的操作了，直接输出超时
        {
            DJY_EventDelay(10*1000);
            e1 = eMBMasterReqReadHoldingRegister(Addr, 53, CFG_PCS_PRODUCT_LENGTH, -1);
            e2 = eMBMasterRegHoldingCBGet(Addr, product_ID, 53, CFG_PCS_PRODUCT_LENGTH);
            PCS_ErrCode = GetModbusErrMessage(e1, e2);
        }
        if (PCS_ErrCode == DTU_RET_SUCCESS)
        {
            for (int i = 0; i < CFG_PCS_PRODUCT_LENGTH; i++)//可能有问题
            {
                productID[i]=product_ID[i] & 0xFF;
            }
            productID[CFG_PCS_PRODUCT_LENGTH]='\0';
            json = CreateRetJson(4, true, true);
            if (json == NULL)
            {
                error_printf("PCS", "json is NULL\r\n");
            }
            else
            {
                json_payload = cJSON_GetObjectItem(json, "payload");
                json_data = cJSON_GetObjectItem(json_payload, "data");
                cJSON_AddNumberToObject(json_data, "productType", 1);
                cJSON_AddStringToObject(json_data, "productSN", productID);

                memset(Version1, 0, sizeof(Version1));
                memset(Version2, 0, sizeof(Version2));
                memset(MergeVersion, 0, sizeof(MergeVersion));
                Magnification(buf[9], Version1, sizeof(Version1), 2);
                Magnification(buf[10], Version2, sizeof(Version2), 2);
                sprintf(MergeVersion, "cpu1:V%s,cpu2:V%s", Version1, Version2);
                cJSON_AddStringToObject(json_data, "softwareVersion", MergeVersion);

                memset(Version1, 0, sizeof(Version1));
                memset(Version2, 0, sizeof(Version2));
                memset(MergeVersion, 0, sizeof(MergeVersion));
                Magnification(buf[11], Version1, sizeof(Version1), 2);
                Magnification(buf[12], Version2, sizeof(Version2), 2);
                sprintf(MergeVersion, "control:V%s,power:V%s", Version1, Version2);
                cJSON_AddStringToObject(json_data, "hardwareVersion", MergeVersion);

                memset(Version1, 0, sizeof(Version1));
                Magnification(buf[17], Version1, sizeof(Version1), 2);
                cJSON_AddStringToObject(json_data, "protocolVersion", Version1);
                cJSON_AddNumberToObject(json_data, "deviceType", buf[0]);

                Ret = cJSON_Print(json);
                if (Ret == NULL)
                {
                    error_printf("PCS", "Ret is NULL\r\n");
                    strncpy(errlog_PCSBTS,"json print fail", sizeof(errlog_PCSBTS));
                    PCS_ErrCode = DTU_RET_OTHER_ERR;
                }
                cJSON_Delete(json);
            }
        }
    }

    return Ret;
}
char *QController(void) //控制器数据查询
{
    u32 Addr = 0;
    eMBMasterReqErrCode e1;
    eMBErrorCode e2;
    u8 *Ret = NULL;
    cJSON *json = NULL;
    cJSON *json_payload = NULL;
    cJSON *json_data = NULL;
    u16 buf[14];
    u8 TempData[20];
    Addr = GetServerAddr();
    PCS_ErrCode = ModbusSlaveAddressIsValid(Addr);
    if (DTU_RET_SUCCESS == PCS_ErrCode)
    {

        DJY_EventDelay(10 * 1000);
        e1 = eMBMasterReqReadHoldingRegister(Addr, 256, 14, -1);
        e2 = eMBMasterRegHoldingCBGet(Addr, buf, 256, 14);
        PCS_ErrCode = GetModbusErrMessage(e1, e2);
        if (DTU_RET_SUCCESS == PCS_ErrCode)
        {

            json = CreateRetJson(5, true, true);
            if (json == NULL)
            {
                error_printf("PCS", "json is NULL\r\n");
            }
            else
            {
                json_payload = cJSON_GetObjectItem(json, "payload");
                json_data = cJSON_GetObjectItem(json_payload, "data");
                cJSON_AddNumberToObject(json_data, "packSOC", buf[0]);

                Magnification(buf[1], TempData, sizeof(TempData), 1);
                cJSON_AddStringToObject(json_data, "packVoltage", TempData);

                Magnification(buf[2], TempData, sizeof(TempData), 1);
                cJSON_AddStringToObject(json_data, "packCurrent", TempData);

                Magnification(buf[7], TempData, sizeof(TempData), 1);
                cJSON_AddStringToObject(json_data, "pvVoltage", TempData);

                Magnification(buf[8], TempData, sizeof(TempData), 1);
                cJSON_AddStringToObject(json_data, "pvCurrent", TempData);

                cJSON_AddNumberToObject(json_data, "pvPower", buf[9]);
                
                switch (buf[11])
                {
                    case 0:
                        cJSON_AddStringToObject(json_data, "chargeStatus", "Chgarge_off");
                        break;
                    case 1:
                        cJSON_AddStringToObject(json_data, "chargeStatus", "Quik_charge");
                        break;
                    case 2:
                        cJSON_AddStringToObject(json_data, "chargeStatus", "Const_voltage_charge");
                        break;
                    case 4:
                        cJSON_AddStringToObject(json_data, "chargeStatus", "Float_charge");
                        break;
                    case 5:
                        cJSON_AddStringToObject(json_data, "chargeStatus", "Reserved");
                        break;
                    case 6:
                        cJSON_AddStringToObject(json_data, "chargeStatus", "Li_battery_acitvate");
                        break;
                    case 7:
                        cJSON_AddStringToObject(json_data, "chargeStatus", "Reserved");
                        break;
                    default:
                        cJSON_AddStringToObject(json_data, "chargeStatus", "unknown");
                        break;
                }
                cJSON_AddNumberToObject(json_data, "chargePower", buf[13]);

                Ret = cJSON_Print(json);
                if (Ret == NULL)
                {
                    error_printf("PCS", "Ret is NULL\r\n");
                    strncpy(errlog_PCSBTS,"json print fail", sizeof(errlog_PCSBTS));
                    PCS_ErrCode = DTU_RET_OTHER_ERR;
                }
                cJSON_Delete(json);
            }
        }
    }

    return Ret;
}
char *QInverter_data(void) //逆变器数据查询
{
    u32 Addr = 0;
    u8 *Ret = NULL;
    eMBMasterReqErrCode e1;
    eMBErrorCode e2;
    u16 buf[25], Fault_code[4];
    cJSON *json = NULL;
    cJSON *json_payload = NULL;
    cJSON *json_data = NULL;
    cJSON *json_FaultCode = NULL; 
    int InverterYear = 0;
    u8 InverterMouth = 0;
    u16 InverterDay = 0;
    u8 InverterHour = 0;
    u8 InverterMin = 0;
    u8 InverterSecond = 0;
    char TempData[20];  //按照"2023-06-21 10:51:14"格式排列日期

    Addr = GetServerAddr();
    PCS_ErrCode = ModbusSlaveAddressIsValid(Addr);
    if (DTU_RET_SUCCESS == PCS_ErrCode)
    {
        DJY_EventDelay(10 * 1000);
        e1 = eMBMasterReqReadHoldingRegister(Addr, 516, 4, -1);
        e2 = eMBMasterRegHoldingCBGet(Addr, Fault_code, 516, 4);
        PCS_ErrCode = GetModbusErrMessage(e1, e2);
        if (DTU_RET_SUCCESS == PCS_ErrCode)
        {
            DJY_EventDelay(10 * 1000);
            e1 = eMBMasterReqReadHoldingRegister(Addr, 524, 25, -1);
            e2 = eMBMasterRegHoldingCBGet(Addr, buf, 524, 25);
            PCS_ErrCode = GetModbusErrMessage(e1, e2);
        }

        if (DTU_RET_SUCCESS == PCS_ErrCode)
        {
            InverterYear = 2000 + ((buf[0] >> 8) & 0xff); //年(如2023就只有23没有20)和月组成两个字节数据，通过偏移获取数据，下面也一样
            InverterMouth = (u8)buf[0] & 0xff;
            InverterDay = (buf[1] >> 8) & 0xff;
            InverterHour = (u8)buf[1] & 0xff;
            InverterMin = (buf[2] >> 8) & 0xff;
            InverterSecond = (u8)buf[2];
            
            memset(TempData, 0, sizeof(TempData));
            sprintf(TempData, "%d-%02d-%02d %02d:%02d:%02d", 
                    InverterYear, InverterMouth, InverterDay, InverterHour, InverterMin, InverterSecond);

            json = CreateRetJson(6, true, true);
            if (json == NULL)
            {
                error_printf("PCS", "json is NULL\r\n");
            }
            else
            {
                json_payload = cJSON_GetObjectItem(json, "payload");
                json_data = cJSON_GetObjectItem(json_payload, "data");
                json_FaultCode = cJSON_CreateArray(); //故障码
                if (json_FaultCode == NULL)
                {
                    error_printf("PCS", "json_FaultCode is NULL\r\n");
                    strncpy(errlog_PCSBTS,"json create fail", sizeof(errlog_PCSBTS));
                    PCS_ErrCode = DTU_RET_OTHER_ERR;
                }
                else
                {
                    cJSON_AddItemToObject(json_data, "currentFaultCode", json_FaultCode);
                    cJSON_AddNumberToObject(json_data, "deviceStatus", buf[4]);
                    cJSON_AddStringToObject(json_data, "currentTime", TempData);

                    Magnification(buf[6], TempData, sizeof(TempData), 1);
                    cJSON_AddStringToObject(json_data, "busVoltage", TempData);
                    Magnification(buf[7], TempData, sizeof(TempData), 1);
                    cJSON_AddStringToObject(json_data, "gridVoltage", TempData);
                    Magnification(buf[8], TempData, sizeof(TempData), 1);
                    cJSON_AddStringToObject(json_data, "gridCurrent", TempData);
                    Magnification(buf[9], TempData, sizeof(TempData), 2);
                    cJSON_AddStringToObject(json_data, "gridFrequency", TempData);
                    Magnification(buf[10], TempData, sizeof(TempData), 1);
                    cJSON_AddStringToObject(json_data, "invertVoltage", TempData);
                    Magnification(buf[11], TempData, sizeof(TempData), 1);
                    cJSON_AddStringToObject(json_data, "invertCurrent", TempData);
                    Magnification(buf[12], TempData, sizeof(TempData), 2);
                    cJSON_AddStringToObject(json_data, "invertFrequency", TempData);
                    Magnification(buf[13], TempData, sizeof(TempData), 1);
                    cJSON_AddStringToObject(json_data, "loadCurrent", TempData);
                    Magnification(buf[15], TempData, sizeof(TempData), 1);
                    cJSON_AddStringToObject(json_data, "loadActivePower", TempData);
                    Magnification(buf[16], TempData, sizeof(TempData), 1);
                    cJSON_AddStringToObject(json_data, "loadApparentPower", TempData);
                    Magnification(buf[18], TempData, sizeof(TempData), 1);
                    cJSON_AddStringToObject(json_data, "gridChargeCurrent", TempData);
                    cJSON_AddNumberToObject(json_data, "loadRate", buf[19]);
                    Magnification(buf[20], TempData, sizeof(TempData), 1);
                    cJSON_AddStringToObject(json_data, "radiatorTempA", TempData);
                    Magnification(buf[21], TempData, sizeof(TempData), 1);
                    cJSON_AddStringToObject(json_data, "radiatorTempB", TempData);
                    Magnification(buf[22], TempData, sizeof(TempData), 1);
                    cJSON_AddStringToObject(json_data, "radiatorTempC", TempData);
                    Magnification(buf[24], TempData, sizeof(TempData), 1);
                    cJSON_AddStringToObject(json_data, "pvChargeCurrent", TempData);

                    cJSON_AddNumberToObject(json_FaultCode, "", Fault_code[0]);
                    cJSON_AddNumberToObject(json_FaultCode, "", Fault_code[1]);
                    cJSON_AddNumberToObject(json_FaultCode, "", Fault_code[2]);
                    cJSON_AddNumberToObject(json_FaultCode, "", Fault_code[3]);

                    Ret = cJSON_Print(json);
                    if (Ret == NULL)
                    {
                        error_printf("PCS", "Ret is NULL\r\n");
                        strncpy(errlog_PCSBTS,"json print fail", sizeof(errlog_PCSBTS));
                        PCS_ErrCode = DTU_RET_OTHER_ERR;
                    }
                }
                cJSON_Delete(json);
            }
        }

    }
    return Ret;
}
char *QHistorical_Weekly_Statistical_Data(void) //历史一周统计数据查询
{
    u32 Addr = 0;
    u8 *Ret = NULL;
    eMBMasterReqErrCode e1;
    eMBErrorCode e2;
    cJSON *json = NULL;
    cJSON *json_payload = NULL;
    cJSON *json_data = NULL;
    cJSON *json_RecentGenerate = NULL;
    cJSON *json_RecentCharge = NULL;
    cJSON *json_RecentDischarge = NULL;
    cJSON *json_GridRecentCharge = NULL;
    cJSON *json_LoadRecentConsume = NULL;
    cJSON *json_LoadRecentConsumeDataFromGrid = NULL;
    u16 buf[21], arr[21];
    char TempData[20];

    Addr = GetServerAddr();
    PCS_ErrCode = ModbusSlaveAddressIsValid(Addr);
    if (DTU_RET_SUCCESS == PCS_ErrCode)
    {
        DJY_EventDelay(10 * 1000);
        e1 = eMBMasterReqReadHoldingRegister(Addr, 61440, 21, -1);
        e2 = eMBMasterRegHoldingCBGet(Addr, buf, 61440, 21);
        PCS_ErrCode = GetModbusErrMessage(e1, e2);
        if (DTU_RET_SUCCESS == PCS_ErrCode)
        {
            DJY_EventDelay(10 * 1000);
            e1 = eMBMasterReqReadHoldingRegister(Addr, 61461, 21, -1);
            e2 = eMBMasterRegHoldingCBGet(Addr, arr, 61461, 21);
            PCS_ErrCode = GetModbusErrMessage(e1, e2);
        }

        if (DTU_RET_SUCCESS == PCS_ErrCode)
        {
            json = CreateRetJson(7, true, true);
            if (json == NULL)
            {
                error_printf("PCS", "json is NULL\r\n");
            }
            else
            {
                json_payload = cJSON_GetObjectItem(json, "payload");
                json_data = cJSON_GetObjectItem(json_payload, "data");
                json_RecentGenerate = cJSON_CreateArray();
                if (json_RecentGenerate == NULL)
                {
                    error_printf("PCS", "json_RecentGenerate is NULL\r\n");
                    strncpy(errlog_PCSBTS,"json create fail", sizeof(errlog_PCSBTS));
                    PCS_ErrCode = DTU_RET_OTHER_ERR;
                }
                else
                {
                    cJSON_AddItemToObject(json_data, "pvRecentGenerateData_7", json_RecentGenerate);

                    json_RecentCharge = cJSON_CreateArray();
                    if (json_RecentCharge == NULL)
                    {
                        error_printf("PCS", "json_RecentCharge is NULL\r\n");
                        strncpy(errlog_PCSBTS,"json create fail", sizeof(errlog_PCSBTS));
                        PCS_ErrCode = DTU_RET_OTHER_ERR;
                    }
                    else
                    {
                        cJSON_AddItemToObject(json_data, "packRecentChargeData_7", json_RecentCharge);
                        json_RecentDischarge = cJSON_CreateArray();
                        if (json_RecentDischarge == NULL)
                        {
                            error_printf("PCS", "json_RecentDischarge is NULL\r\n");
                            strncpy(errlog_PCSBTS,"json create fail", sizeof(errlog_PCSBTS));
                            PCS_ErrCode = DTU_RET_OTHER_ERR;
                        }
                        else
                        {
                            cJSON_AddItemToObject(json_data, "packRecentDischargeData_7", json_RecentDischarge);
                            json_GridRecentCharge = cJSON_CreateArray();
                            if (json_GridRecentCharge == NULL)
                            {
                                error_printf("PCS", "json_GridRecentCharge is NULL\r\n");
                                strncpy(errlog_PCSBTS,"json create fail", sizeof(errlog_PCSBTS));
                                PCS_ErrCode = DTU_RET_OTHER_ERR;
                            }
                            else
                            {
                                cJSON_AddItemToObject(json_data, "gridRecentChargeData_7", json_GridRecentCharge);
                                json_LoadRecentConsume = cJSON_CreateArray();
                                if (json_LoadRecentConsume == NULL)
                                {
                                    error_printf("PCS", "json_LoadRecentConsume is NULL\r\n");
                                    strncpy(errlog_PCSBTS,"json create fail", sizeof(errlog_PCSBTS));
                                    PCS_ErrCode = DTU_RET_OTHER_ERR;
                                }
                                else
                                {
                                    cJSON_AddItemToObject(json_data, "loadRecentConsumeData_7", json_LoadRecentConsume);
                                    json_LoadRecentConsumeDataFromGrid = cJSON_CreateArray();
                                    if (json_LoadRecentConsumeDataFromGrid == NULL)
                                    {
                                        error_printf("PCS", "json_LoadRecentConsumeDataFromGrid is NULL\r\n");
                                        strncpy(errlog_PCSBTS,"json create fail", sizeof(errlog_PCSBTS));
                                        PCS_ErrCode = DTU_RET_OTHER_ERR;
                                    }
                                    else
                                    {
                                        cJSON_AddItemToObject(json_data, "loadRecentConsumeDataFromGrid_7", json_LoadRecentConsumeDataFromGrid);
                                        Magnification(buf[0], TempData, sizeof(TempData), 1);
                                        cJSON_AddStringToObject(json_RecentGenerate, "", TempData);
                                        Magnification(buf[1], TempData, sizeof(TempData), 1);
                                        cJSON_AddStringToObject(json_RecentGenerate, "", TempData);
                                        Magnification(buf[2], TempData, sizeof(TempData), 1);
                                        cJSON_AddStringToObject(json_RecentGenerate, "", TempData);
                                        Magnification(buf[3], TempData, sizeof(TempData), 1);
                                        cJSON_AddStringToObject(json_RecentGenerate, "", TempData);
                                        Magnification(buf[4], TempData, sizeof(TempData), 1);
                                        cJSON_AddStringToObject(json_RecentGenerate, "", TempData);
                                        Magnification(buf[5], TempData, sizeof(TempData), 1);
                                        cJSON_AddStringToObject(json_RecentGenerate, "", TempData);
                                        Magnification(buf[6], TempData, sizeof(TempData), 1);
                                        cJSON_AddStringToObject(json_RecentGenerate, "", TempData);



                                        cJSON_AddNumberToObject(json_RecentCharge, "", buf[7]);
                                        cJSON_AddNumberToObject(json_RecentCharge, "", buf[8]);
                                        cJSON_AddNumberToObject(json_RecentCharge, "", buf[9]);
                                        cJSON_AddNumberToObject(json_RecentCharge, "", buf[10]);
                                        cJSON_AddNumberToObject(json_RecentCharge, "", buf[11]);
                                        cJSON_AddNumberToObject(json_RecentCharge, "", buf[12]);
                                        cJSON_AddNumberToObject(json_RecentCharge, "", buf[13]);


                                        cJSON_AddNumberToObject(json_RecentDischarge, "", buf[14]);
                                        cJSON_AddNumberToObject(json_RecentDischarge, "", buf[15]);
                                        cJSON_AddNumberToObject(json_RecentDischarge, "", buf[16]);
                                        cJSON_AddNumberToObject(json_RecentDischarge, "", buf[17]);
                                        cJSON_AddNumberToObject(json_RecentDischarge, "", buf[18]);
                                        cJSON_AddNumberToObject(json_RecentDischarge, "", buf[19]);
                                        cJSON_AddNumberToObject(json_RecentDischarge, "", buf[20]);

                                        cJSON_AddNumberToObject(json_GridRecentCharge, "", arr[0]);
                                        cJSON_AddNumberToObject(json_GridRecentCharge, "", arr[1]);
                                        cJSON_AddNumberToObject(json_GridRecentCharge, "", arr[2]);
                                        cJSON_AddNumberToObject(json_GridRecentCharge, "", arr[3]);
                                        cJSON_AddNumberToObject(json_GridRecentCharge, "", arr[4]);
                                        cJSON_AddNumberToObject(json_GridRecentCharge, "", arr[5]);
                                        cJSON_AddNumberToObject(json_GridRecentCharge, "", arr[6]);


                                        Magnification(buf[7], TempData, sizeof(TempData), 1);
                                        cJSON_AddStringToObject(json_LoadRecentConsume, "", TempData);

                                        Magnification(buf[8], TempData, sizeof(TempData), 1);
                                        cJSON_AddStringToObject(json_LoadRecentConsume, "", TempData);

                                        Magnification(buf[9], TempData, sizeof(TempData), 1);
                                        cJSON_AddStringToObject(json_LoadRecentConsume, "", TempData);

                                        Magnification(buf[10], TempData, sizeof(TempData), 1);
                                        cJSON_AddStringToObject(json_LoadRecentConsume, "", TempData);

                                        Magnification(buf[11], TempData, sizeof(TempData), 1);
                                        cJSON_AddStringToObject(json_LoadRecentConsume, "", TempData);

                                        Magnification(buf[12], TempData, sizeof(TempData), 1);
                                        cJSON_AddStringToObject(json_LoadRecentConsume, "", TempData);

                                        Magnification(buf[13], TempData, sizeof(TempData), 1);
                                        cJSON_AddStringToObject(json_LoadRecentConsume, "", TempData);

                                        Magnification(buf[14], TempData, sizeof(TempData), 1);
                                        cJSON_AddStringToObject(json_LoadRecentConsumeDataFromGrid, "", TempData);

                                        Magnification(buf[15], TempData, sizeof(TempData), 1);
                                        cJSON_AddStringToObject(json_LoadRecentConsumeDataFromGrid, "", TempData);

                                        Magnification(buf[16], TempData, sizeof(TempData), 1);
                                        cJSON_AddStringToObject(json_LoadRecentConsumeDataFromGrid, "", TempData);

                                        Magnification(buf[17], TempData, sizeof(TempData), 1);
                                        cJSON_AddStringToObject(json_LoadRecentConsumeDataFromGrid, "", TempData);

                                        Magnification(buf[18], TempData, sizeof(TempData), 1);
                                        cJSON_AddStringToObject(json_LoadRecentConsumeDataFromGrid, "", TempData);

                                        Magnification(buf[19], TempData, sizeof(TempData), 1);
                                        cJSON_AddStringToObject(json_LoadRecentConsumeDataFromGrid, "", TempData);

                                        Magnification(buf[20], TempData, sizeof(TempData), 1);
                                        cJSON_AddStringToObject(json_LoadRecentConsumeDataFromGrid, "", TempData);
                                        
                                        Ret = cJSON_Print(json);
                                        if (Ret == NULL)
                                        {
                                            error_printf("PCS", "Ret is NULL\r\n");
                                            strncpy(errlog_PCSBTS,"json print fail", sizeof(errlog_PCSBTS));
                                            PCS_ErrCode = DTU_RET_OTHER_ERR;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                cJSON_Delete(json);
            }
        }
    }
    return Ret;
}

char *Qdaily_statistical_data(void) //当天统计数据查询
{
    u32 Addr = 0;
    u8 *Ret = NULL;
    eMBMasterReqErrCode e1;
    eMBErrorCode e2;
    cJSON *json = NULL;
    cJSON *json_payload = NULL;
    cJSON *json_data = NULL;
    u16 buf[19];
    char TempData[20];

    Addr = GetServerAddr();
    PCS_ErrCode = ModbusSlaveAddressIsValid(Addr);
    if (DTU_RET_SUCCESS == PCS_ErrCode)
    {
        DJY_EventDelay(10 * 1000);
        e1 = eMBMasterReqReadHoldingRegister(Addr, 61485, 19, -1);
        e2 = eMBMasterRegHoldingCBGet(Addr, buf, 61485, 19);
        PCS_ErrCode = GetModbusErrMessage(e1, e2);
        if (DTU_RET_SUCCESS == PCS_ErrCode)
        {

            json = CreateRetJson(8, true, true);
            if (json == NULL)
            {
                error_printf("PCS", "json is NULL\r\n");
            }
            else
            {
                json_payload = cJSON_GetObjectItem(json, "payload");
                json_data = cJSON_GetObjectItem(json_payload, "data");
                cJSON_AddNumberToObject(json_data, "todayChargeAmpereHourSum", buf[0]);
                cJSON_AddNumberToObject(json_data, "todayDischargeAmpereHourSum", buf[1]);
                Magnification(buf[2], TempData, sizeof(TempData), 1);//当天PV发电量
                cJSON_AddStringToObject(json_data, "todayPVGenerateElectricSum", TempData);
                Magnification(buf[3], TempData, sizeof(TempData), 1);//负载当天用电量
                cJSON_AddStringToObject(json_data, "todayLoadConsumeElectricSum", TempData);
                cJSON_AddNumberToObject(json_data, "todayACPowerChargeSum", buf[14]);//市电当天充电电量
                Magnification(buf[15], TempData, sizeof(TempData), 1);//负载当天从市电消耗电量
                cJSON_AddStringToObject(json_data, "todayLoadConsumeFromACPower", TempData);

                cJSON_AddNumberToObject(json_data, "todayInverterWorkTime", buf[17]);//逆变当天工作时间
                cJSON_AddNumberToObject(json_data, "todayBypassWorkTime", buf[18]);//旁路当天工作时间

                Ret = cJSON_Print(json);
                if (Ret == NULL)
                {
                    error_printf("PCS", "Ret is NULL\r\n");
                    strncpy(errlog_PCSBTS,"json print fail", sizeof(errlog_PCSBTS));
                    PCS_ErrCode = DTU_RET_OTHER_ERR;
                }
                cJSON_Delete(json);
            }
        }

    }
    return Ret;
}
char *QTotal_historical_statistics(void) //历史统计总数据查询
{
    u32 Addr = 0;
    u8 *Ret = NULL;
    eMBMasterReqErrCode e1;
    eMBErrorCode e2;
    cJSON *json = NULL;
    cJSON *json_payload = NULL;
    cJSON *json_data = NULL;
    u16 buf[27];
    int InverterYear = 0;
    u8 InverterMouth = 0;
    u16 InverterDay = 0;
    u8 InverterHour = 0;
    u8 InverterMin = 0;
    u8 InverterSecond = 0;
    char TempData[20];

    Addr = GetServerAddr();
    PCS_ErrCode = ModbusSlaveAddressIsValid(Addr);
    if (DTU_RET_SUCCESS == PCS_ErrCode)
    {

        DJY_EventDelay(10 * 1000);
        e1 = eMBMasterReqReadHoldingRegister(Addr, 61489, 27, -1);
        e2 = eMBMasterRegHoldingCBGet(Addr, buf, 61489, 27);
        PCS_ErrCode = GetModbusErrMessage(e1, e2);
        if (DTU_RET_SUCCESS == PCS_ErrCode)
        {
            json = CreateRetJson(9, true, true);
            if (json == NULL)
            {
                error_printf("PCS", "json is NULL\r\n");
            }
            else
            {
                json_payload = cJSON_GetObjectItem(json, "payload");
                json_data = cJSON_GetObjectItem(json_payload, "data");
                cJSON_AddNumberToObject(json_data, "packChargeAmpereHourSum", buf[3]);
                cJSON_AddNumberToObject(json_data, "totalRunningDay", buf[0]);
                cJSON_AddNumberToObject(json_data, "packDischargeAmpereHourSum", buf[5]);

                Magnification(buf[7], TempData, sizeof(TempData), 1);
                cJSON_AddStringToObject(json_data, "PVGenerateElectricSum", TempData);

                Magnification(buf[9], TempData, sizeof(TempData), 1);
                cJSON_AddStringToObject(json_data, "loadConsumeElectricSum", TempData);

                InverterYear = 2000 + ((buf[15] >> 8) & 0xff);
                InverterMouth = (u8)(buf[15] & 0xff);
                InverterDay = (buf[16] >> 8) & 0xff;
                InverterHour = (u8)(buf[16] & 0xff);
                InverterMin = (buf[17] >> 8) & 0xff;
                InverterSecond = (u8)(buf[17] & 0xff);
                memset(TempData, 0, sizeof(TempData));
                sprintf(TempData, "%d-%02d-%02d %02d:%02d:%02d", 
                        InverterYear, InverterMouth, InverterDay, InverterHour, InverterMin, InverterSecond);
                cJSON_AddStringToObject(json_data, "bootTime", TempData);
                InverterYear = 2000 + ((buf[18] >> 8) & 0xff);
                InverterMouth = (u8)(buf[18] & 0xff);
                InverterDay = (buf[19] >> 8) & 0xff;
                InverterHour = (u8)(buf[19] & 0xff);
                InverterMin = (buf[20] >> 8) & 0xff;
                InverterSecond = (u8)(buf[20] & 0xff);
                memset(TempData, 0, sizeof(TempData));
                sprintf(TempData, "%d-%02d-%02d %02d:%02d:%02d", 
                        InverterYear, InverterMouth, InverterDay, InverterHour, InverterMin, InverterSecond);
                cJSON_AddStringToObject(json_data, "lastBalanceChargeCompleteTime", TempData);

                Magnification(buf[21], TempData, sizeof(TempData), 1);
                cJSON_AddStringToObject(json_data, "ACPowerChargeSum", TempData);
                Magnification(buf[23], TempData, sizeof(TempData), 1);
                cJSON_AddStringToObject(json_data, "loadConsumeFromACPowerSum", TempData);

                cJSON_AddNumberToObject(json_data, "inverterWorkTimeSum", buf[25]);
                cJSON_AddNumberToObject(json_data, "bypassWorkTimeSum", buf[26]);

                Ret = cJSON_Print(json);
                if (Ret == NULL)
                {
                    error_printf("PCS", "Ret is NULL\r\n");
                    strncpy(errlog_PCSBTS,"json print fail", sizeof(errlog_PCSBTS));
                    PCS_ErrCode = DTU_RET_OTHER_ERR;
                }
                cJSON_Delete(json);
            }
        }

    }
    return Ret;
}
char *QHistorical_fault_data(void) //历史故障数据查询
{
    u32 Addr = 0;
    u8 *Ret = NULL;
    eMBMasterReqErrCode e1;
    eMBErrorCode e2;
    cJSON *json = NULL;
    cJSON *json_payload = NULL;
    cJSON *json_data = NULL;
    cJSON *json_FaultRecordArray = NULL;
    cJSON *json_FaultRecord = NULL;
    int InverterYear = 0;
    u8 InverterMouth = 0;
    u16 InverterDay = 0;
    u8 InverterHour = 0;
    u8 InverterMin = 0;
    u8 InverterSecond = 0;
    char TempData[20];
    u32 i = 0;
    u16 Fault_Addr[16] = {63488, 63504, 63520, 63536, 63552, 
            63568, 63584, 63600, 63616, 63632, 63648, 63664, 63680, 63696, 63712, 63728};
    u16 Fault_record[64]={0};
    
    Addr = GetServerAddr();
    PCS_ErrCode = ModbusSlaveAddressIsValid(Addr);
    if (DTU_RET_SUCCESS != PCS_ErrCode)
    {
        return NULL;
    }

    for (i = 0; i < (sizeof(Fault_Addr) / sizeof(u16)); i++)
    {
        DJY_EventDelay(10 * 1000);
        e1 = eMBMasterReqReadHoldingRegister(Addr, Fault_Addr[i], 4, -1);
        e2 = eMBMasterRegHoldingCBGet(Addr, &Fault_record[i * 4], Fault_Addr[i], 4);
        PCS_ErrCode = GetModbusErrMessage(e1, e2);
        if (DTU_RET_SUCCESS != PCS_ErrCode)
        {
            return NULL;
        }
    }
    json = CreateRetJson(10, true, true);
    if (json == NULL)
    {
        error_printf("PCS", "json is NULL\r\n");
    }
    else
    {
        json_payload = cJSON_GetObjectItem(json, "payload");
        json_data = cJSON_GetObjectItem(json_payload, "data");
        json_FaultRecordArray = cJSON_CreateArray();
        if (json_FaultRecordArray == NULL)
        {
            error_printf("PCS", "json_FaultRecordArray is NULL\r\n");
            strncpy(errlog_PCSBTS,"json create fail", sizeof(errlog_PCSBTS));
            PCS_ErrCode = DTU_RET_OTHER_ERR;
        }
        else
        {
            cJSON_AddItemToObject(json_data, "faultRecord", json_FaultRecordArray);
            for (i = 0; i < (sizeof(Fault_Addr) / sizeof(u16)); i++)
            {
                if (Fault_record[i * 4] != 0)
                {

                    json_FaultRecord = cJSON_CreateObject();
                    if (json_FaultRecord == NULL)
                    {
                        error_printf("PCS", "json_FaultRecord is NULL\r\n");
                        strncpy(errlog_PCSBTS,"json create fail", sizeof(errlog_PCSBTS));
                        PCS_ErrCode = DTU_RET_OTHER_ERR;
                        break;
                    }
                    else
                    {
                        cJSON_AddItemToArray(json_FaultRecordArray, json_FaultRecord);

                        InverterYear = 2000 + ((Fault_record[1 + i * 4] >> 8) & 0xff);
                        InverterMouth = (u8)(Fault_record[1 + i * 4] & 0xff);
                        InverterDay = (Fault_record[2 + i * 4] >> 8) & 0xff;
                        InverterHour = (u8)(Fault_record[2 + i * 4] & 0xff);
                        InverterMin = (Fault_record[3 + i * 4] >> 8) & 0xff;
                        InverterSecond = (u8)(Fault_record[3 + i * 4] & 0xff);
                        memset(TempData, 0, sizeof(TempData));
                        sprintf(TempData, "%d-%02d-%02d %02d:%02d:%02d", 
                                InverterYear, InverterMouth, InverterDay, InverterHour, InverterMin, InverterSecond);
                        cJSON_AddNumberToObject(json_FaultRecord, "faultCode", Fault_record[i * 4]);
                        cJSON_AddStringToObject(json_FaultRecord, "faultTime", TempData);
                    }
                }

            }
            Ret = cJSON_Print(json);
            if (Ret == NULL)
            {
                error_printf("PCS", "Ret is NULL\r\n");
                strncpy(errlog_PCSBTS,"json print fail", sizeof(errlog_PCSBTS));
                PCS_ErrCode = DTU_RET_OTHER_ERR;
            }
        }
        cJSON_Delete(json);
    }
    return Ret;
}

char *QBattery_parameters(void) //电池参数设定值查询
{
    u32 Addr = 0;
    u8 *Ret = NULL;
    eMBMasterReqErrCode e1;
    eMBErrorCode e2;
    char TempData[20];
    cJSON *json = NULL;
    cJSON *json_payload = NULL;
    cJSON *json_data = NULL;
    u16 buf[19], arr[1], container[2];

    Addr = GetServerAddr();
    PCS_ErrCode = ModbusSlaveAddressIsValid(Addr);
    if (DTU_RET_SUCCESS != PCS_ErrCode)
    {
        return NULL;
    }

    DJY_EventDelay(10 * 1000);
    e1 = eMBMasterReqReadHoldingRegister(Addr, 57345, 19, -1);
    e2 = eMBMasterRegHoldingCBGet(Addr, buf, 57345, 19);
    PCS_ErrCode = GetModbusErrMessage(e1, e2);
    if (DTU_RET_SUCCESS != PCS_ErrCode)
    {
        return NULL;
    }

    DJY_EventDelay(10 * 1000);
    e1 = eMBMasterReqReadHoldingRegister(Addr, 57371, 1, -1);
    e2 = eMBMasterRegHoldingCBGet(Addr, arr, 57371, 1);
    PCS_ErrCode = GetModbusErrMessage(e1, e2);
    if (DTU_RET_SUCCESS != PCS_ErrCode)
    {
        return NULL;
    }

    DJY_EventDelay(10 * 1000);
    e1 = eMBMasterReqReadHoldingRegister(Addr, 57378, 2, -1);
    e2 = eMBMasterRegHoldingCBGet(Addr, container, 57378, 2);
    PCS_ErrCode = GetModbusErrMessage(e1, e2);
    if (DTU_RET_SUCCESS != PCS_ErrCode)
    {
        return NULL;
    }
    
    json = CreateRetJson(11, true, true);
    if (json == NULL)
    {
        error_printf("PCS", "json is NULL\r\n");
    }
    else
    {
        json_payload = cJSON_GetObjectItem(json, "payload");
        json_data = cJSON_GetObjectItem(json_payload, "data");
        Magnification(buf[0], TempData, sizeof(TempData), 1);
        cJSON_AddStringToObject(json_data, "pvMaxsizeCharge", TempData);
        cJSON_AddNumberToObject(json_data, "packRatedVoltage", buf[2]);
        cJSON_AddNumberToObject(json_data, "packType", buf[3]);
        Magnification(buf[5], TempData, sizeof(TempData), 1);
        cJSON_AddStringToObject(json_data, "limitChargeVoltage", TempData);
        Magnification(buf[11], TempData, sizeof(TempData), 1);
        cJSON_AddStringToObject(json_data, "undervoltAlarmVolt", TempData);
        Magnification(buf[12], TempData, sizeof(TempData), 1);
        cJSON_AddStringToObject(json_data, "overdischargeVoltage", TempData);
        Magnification(buf[13], TempData, sizeof(TempData), 1);
        cJSON_AddStringToObject(json_data, "dischargeLimitVoltage", TempData);
        Magnification(arr[0], TempData, sizeof(TempData), 1);
        cJSON_AddStringToObject(json_data, "ACPowerSwitchVoltage", TempData);
        Magnification(container[0], TempData, sizeof(TempData), 1);
        cJSON_AddStringToObject(json_data, "switchInverterVolt", TempData);
        Magnification(buf[6], TempData, sizeof(TempData), 1);
        cJSON_AddStringToObject(json_data, "balanceChargeVoltage", TempData);
        Magnification(buf[7], TempData, sizeof(TempData), 1);
        cJSON_AddStringToObject(json_data, "overchargeVoltage", TempData);
        Magnification(buf[8], TempData, sizeof(TempData), 1);
        cJSON_AddStringToObject(json_data, "overchargeRecoveryVoltage", TempData);
        Magnification(buf[9], TempData, sizeof(TempData), 1);
        cJSON_AddStringToObject(json_data, "elevatedChargeRecoveryVoltage", TempData);
        Magnification(buf[10], TempData, sizeof(TempData), 1);
        cJSON_AddStringToObject(json_data, "overdischargeRecoveryVoltage", TempData);

        cJSON_AddNumberToObject(json_data, "overdischargeDelayTime", buf[15]);
        cJSON_AddNumberToObject(json_data, "balanceChargingTime", buf[16]);
        cJSON_AddNumberToObject(json_data, "extendedChargingTime", buf[17]);
        cJSON_AddNumberToObject(json_data, "balanceChargingInterval", buf[18]);
        Magnification(buf[4], TempData, sizeof(TempData), 1);
        cJSON_AddStringToObject(json_data, "overvoltageVoltageProt", TempData);
        cJSON_AddNumberToObject(json_data, "balanceChargeTimeOutPeriod", container[1]);

        Ret = cJSON_Print(json);
        if (Ret == NULL)
        {
            error_printf("PCS", "Ret is NULL\r\n");
            strncpy(errlog_PCSBTS,"json print fail", sizeof(errlog_PCSBTS));
            PCS_ErrCode = DTU_RET_OTHER_ERR;
        }
        cJSON_Delete(json);
    }

    return Ret;
}
char *QInverter_parameters(void) //逆变器参数设定值查询
{
    u32 Addr = 0;
    u8 *Ret = NULL;
    eMBMasterReqErrCode e1;
    eMBErrorCode e2;
    char TempData[20];
    u16 buf[21];
    cJSON *json = NULL;
    cJSON *json_payload = NULL;
    cJSON *json_data = NULL;

    Addr = GetServerAddr();
    PCS_ErrCode = ModbusSlaveAddressIsValid(Addr);
    if (DTU_RET_SUCCESS != PCS_ErrCode)
    {
        return NULL;
    }


    DJY_EventDelay(10 * 1000);
    e1 = eMBMasterReqReadHoldingRegister(Addr, 57857, 21, -1);
    e2 = eMBMasterRegHoldingCBGet(Addr, buf, 57857, 21);
    PCS_ErrCode = GetModbusErrMessage(e1, e2);
    if (DTU_RET_SUCCESS != PCS_ErrCode)
    {
        return NULL;
    }

    json = CreateRetJson(12, true, true);
    if (json == NULL)
    {
        error_printf("PCS", "json is NULL\r\n");
    }
    else
    {
        json_payload = cJSON_GetObjectItem(json, "payload");
        json_data = cJSON_GetObjectItem(json_payload, "data");
        cJSON_AddNumberToObject(json_data, "parallelMode", buf[0]);
        Magnification(buf[4], TempData, sizeof(TempData), 1);
        cJSON_AddStringToObject(json_data, "LimitChargeCurrentFromAC", TempData);

        cJSON_AddNumberToObject(json_data, "EqualChargeEnable", buf[5]);
        Magnification(buf[7], TempData, sizeof(TempData), 1);
        cJSON_AddStringToObject(json_data, "outputVolt", TempData);
        Magnification(buf[8], TempData, sizeof(TempData), 1);
        cJSON_AddStringToObject(json_data, "outputFrequency", TempData);
        Magnification(buf[9], TempData, sizeof(TempData), 1);
        cJSON_AddStringToObject(json_data, "MaxsizeChargeCurrent", TempData);

        cJSON_AddNumberToObject(json_data, "ACInputRange", buf[10]);
        cJSON_AddNumberToObject(json_data, "energySavingMode", buf[11]);
        cJSON_AddNumberToObject(json_data, "overloadAutoRestart", buf[12]);
        cJSON_AddNumberToObject(json_data, "overtemperatureAutoRestart", buf[13]);
        cJSON_AddNumberToObject(json_data, "chargePriority", buf[14]);
        cJSON_AddNumberToObject(json_data, "AlarmControl", buf[15]);
        cJSON_AddNumberToObject(json_data, "inputSourceInterruptAlarmEnable", buf[16]);
        cJSON_AddNumberToObject(json_data, "overloadBypassEnable", buf[17]);
        cJSON_AddNumberToObject(json_data, "phaseShiftTransformer", buf[19]);
        cJSON_AddNumberToObject(json_data, "BMSEnable", buf[20]);

        Ret = cJSON_Print(json);
        if (Ret == NULL)
        {
            error_printf("PCS", "Ret is NULL\r\n");
            strncpy(errlog_PCSBTS,"json print fail", sizeof(errlog_PCSBTS));
            PCS_ErrCode = DTU_RET_OTHER_ERR;
        }
        cJSON_Delete(json);
    }

    return Ret;
}

char *PCS_onORoff_control(cJSON *json) // PCS开关机控制指令
{
    u8 *Ret = NULL;
    u32 Addr = 0;
    cJSON *json_payload;
    cJSON *json_switchControl;
    eMBMasterReqErrCode e1;

    json_payload = cJSON_GetObjectItem(json, "payload");
    json_switchControl = cJSON_GetObjectItem(json_payload, "switchControl");
    if (json_switchControl == NULL)
    {
        error_printf("PCS", "switchControl is NULL\r\n");
        PCS_ErrCode = DTU_RET_PARAM_ERR;
    }
    else
    {
        if (json_switchControl->valueint != 0 && json_switchControl->valueint != 1)
        {
            error_printf("PCS", "switchControl param is error\r\n");
            PCS_ErrCode = DTU_RET_PARAM_ERR;
        }
        else
        {
            Addr = GetServerAddr();
            PCS_ErrCode = ModbusSlaveAddressIsValid(Addr);
            if (PCS_ErrCode == DTU_RET_SUCCESS)
            {                
                DJY_EventDelay(10 * 1000);
                e1 = eMBMasterReqWriteHoldingRegister(Addr, 57088, json_switchControl->valueint, -1);
                if (e1 != MB_MRE_REV_DATA)
                {
                    error_printf("PCS", "switch fail\r\n");
                    sprintf(errlog_PCSBTS, "switch fail %d", e1);
                    PCS_ErrCode = DTU_RET_OTHER_ERR;
                }
                else
                {
                    json = CreateRetJson(13, false, true);
                    if (json == NULL)
                    {
                        error_printf("PCS", "json is NULL\r\n");
                    }
                    else
                    {
                        Ret = cJSON_Print(json);
                        if (Ret == NULL)
                        {
                            error_printf("PCS", "Ret is NULL\r\n");
                            strncpy(errlog_PCSBTS,"json print fail", sizeof(errlog_PCSBTS));
                            PCS_ErrCode = DTU_RET_OTHER_ERR;
                        }
                        cJSON_Delete(json);
                    }
                }
            }
        }
    }
    return Ret;
}
char *PCS_reset_control(void) // PCS复位控制指令
{
    u8 *Ret = NULL;
    u32 Addr = 0;
    cJSON *json = NULL;
    eMBMasterReqErrCode e1;

    Addr = GetServerAddr();
    PCS_ErrCode = ModbusSlaveAddressIsValid(Addr);
    if (DTU_RET_SUCCESS != PCS_ErrCode)
    {
        return NULL;
    }

    DJY_EventDelay(10 * 1000);
    e1 = eMBMasterReqWriteHoldingRegister(Addr, 57089, 1, -1);
    if (e1 != MB_MRE_REV_DATA)
    {
        error_printf("PCS", "switch fail\r\n");
        sprintf(errlog_PCSBTS, "switch fail %d", e1);
        PCS_ErrCode = DTU_RET_OTHER_ERR;
    }
    else
    {
        json = CreateRetJson(14, false, true);
        if (json == NULL)
        {
            error_printf("PCS", "json is NULL\r\n");
        }
        else
        {
            Ret = cJSON_Print(json);
            if (Ret == NULL)
            {
                error_printf("PCS", "Ret is NULL\r\n");
                strncpy(errlog_PCSBTS,"json print fail", sizeof(errlog_PCSBTS));
                PCS_ErrCode = DTU_RET_OTHER_ERR;
            }
            cJSON_Delete(json);
        }
    }

    return Ret;
}

char *PCS_Factory_reset_command(void) // PCS恢复出厂设置指令
{
    u8 *Ret = NULL;
    u32 Addr = 0;
    cJSON *json = NULL;
    eMBMasterReqErrCode e1;

    Addr = GetServerAddr();
    PCS_ErrCode = ModbusSlaveAddressIsValid(Addr);
    if (DTU_RET_SUCCESS != PCS_ErrCode)
    {
        return NULL;
    }

    DJY_EventDelay(10 * 1000);
    e1 = eMBMasterReqWriteHoldingRegister(Addr, 57090, 1, -1);
    PCS_ErrCode = GetModbusErrMessage(e1, MB_ENOERR);
    if (DTU_RET_SUCCESS != PCS_ErrCode)
    {
        return NULL;
    }

    json = CreateRetJson(15, false, true);
    if (json == NULL)
    {
        error_printf("PCS", "json is NULL\r\n");
    }
    else
    {
        Ret = cJSON_Print(json);
        if (Ret == NULL)
        {
            error_printf("PCS", "Ret is NULL\r\n");
            strncpy(errlog_PCSBTS,"json print fail", sizeof(errlog_PCSBTS));
            PCS_ErrCode = DTU_RET_OTHER_ERR;
        }
        cJSON_Delete(json);
    }

    return Ret;
}
char *PCS_Clear_History(void) // PCS清除历史记录指令
{
    u8 *Ret = NULL;
    u32 Addr = 0;
    cJSON *json = NULL;
    eMBMasterReqErrCode e1;

    Addr = GetServerAddr();
    PCS_ErrCode = ModbusSlaveAddressIsValid(Addr);
    if (DTU_RET_SUCCESS != PCS_ErrCode)
    {
        return NULL;
    }

    DJY_EventDelay(10 * 1000);
    e1 = eMBMasterReqWriteHoldingRegister(Addr, 57093, 1, -1);
    PCS_ErrCode = GetModbusErrMessage(e1, MB_ENOERR);
    if (DTU_RET_SUCCESS != PCS_ErrCode)
    {
        return NULL;
    }

    json = CreateRetJson(16, false, true);
    if (json == NULL)
    {
        error_printf("PCS", "json is NULL\r\n");
    }
    else
    {
        Ret = cJSON_Print(json);
        if (Ret == NULL)
        {
            error_printf("PCS", "Ret is NULL\r\n");
            strncpy(errlog_PCSBTS,"json print fail", sizeof(errlog_PCSBTS));
            PCS_ErrCode = DTU_RET_OTHER_ERR;
        }
        cJSON_Delete(json);
    }
    return Ret;
}

char *PCS_balanced_charging(void) // PCS立即均衡充电控制指令
{
    u8 *Ret = NULL;
    u32 Addr = 0;
    cJSON *json = NULL;
    eMBMasterReqErrCode e1;

    Addr = GetServerAddr();
    PCS_ErrCode = ModbusSlaveAddressIsValid(Addr);
    if (DTU_RET_SUCCESS != PCS_ErrCode)
    {
        return NULL;
    }

    DJY_EventDelay(10 * 1000);
    e1 = eMBMasterReqWriteHoldingRegister(Addr, 57101, 1, -1);
    PCS_ErrCode = GetModbusErrMessage(e1, MB_ENOERR);
    if (DTU_RET_SUCCESS != PCS_ErrCode)
    {
        return NULL;
    }
    
    json = CreateRetJson(17, false, true);
    if (json == NULL)
    {
        error_printf("PCS", "json is NULL\r\n");
    }
    else
    {
        Ret = cJSON_Print(json);
        if (Ret == NULL)
        {
            error_printf("PCS", "Ret is NULL\r\n");
            strncpy(errlog_PCSBTS,"json print fail", sizeof(errlog_PCSBTS));
            PCS_ErrCode = DTU_RET_OTHER_ERR;
        }
        cJSON_Delete(json);
    }
    return Ret;
}
char *PCS_battery_parameter_setting(cJSON *json) // PCS电池参数设定指令
{
    u8 *Ret = NULL;
    u32 Addr = 0;
    eMBMasterReqErrCode e1;

    Addr = GetServerAddr();
    PCS_ErrCode = ModbusSlaveAddressIsValid(Addr);
    if (DTU_RET_SUCCESS != PCS_ErrCode)
    {
        return NULL;
    }

    cJSON *json_payload = cJSON_GetObjectItem(json, "payload");

    cJSON *pvMaxsizeCharge = cJSON_GetObjectItem(json_payload, "pvMaxsizeCharge");                             //光伏最大充电电流设置
    cJSON *packType = cJSON_GetObjectItem(json_payload, "packType");                                           //蓄电池类型设定
    cJSON *limitChargeVoltage = cJSON_GetObjectItem(json_payload, "limitChargeVoltage");                       // 充电限制电压
    cJSON *undervoltAlarmVolt = cJSON_GetObjectItem(json_payload, "undervoltAlarmVolt");                       //欠压警告电压
    cJSON *overdischargeVoltage = cJSON_GetObjectItem(json_payload, "overdischargeVoltage");                   //过放电压
    cJSON *dischargeLimitVoltage = cJSON_GetObjectItem(json_payload, "dischargeLimitVoltage");                 //放电限制电压
    cJSON *ACPowerSwitchVoltage = cJSON_GetObjectItem(json_payload, "ACPowerSwitchVoltage");                   //市电切换电压
    cJSON *switchInverterVolt = cJSON_GetObjectItem(json_payload, "switchInverterVolt");                       //逆变切换电压
    cJSON *balanceChargeVoltage = cJSON_GetObjectItem(json_payload, "balanceChargeVoltage");                   //均衡充电电压
    cJSON *overchargeVoltage = cJSON_GetObjectItem(json_payload, "overchargeVoltage");                         //提升充电电压
    cJSON *overchargeRecoveryVoltage = cJSON_GetObjectItem(json_payload, "overchargeRecoveryVoltage");         //浮充充电电压
    cJSON *elevatedChargeRecoveryVoltage = cJSON_GetObjectItem(json_payload, "elevatedChargeRecoveryVoltage"); //提升充电返回电压
    cJSON *overdischargeRecoveryVoltage = cJSON_GetObjectItem(json_payload, "overdischargeRecoveryVoltage");   //过放返回电压
    cJSON *overdischargeDelayTime = cJSON_GetObjectItem(json_payload, "overdischargeDelayTime");               //过放延时时间
    cJSON *balanceChargingTime = cJSON_GetObjectItem(json_payload, "balanceChargingTime");                     //均衡充电时间
    cJSON *extendedChargingTime = cJSON_GetObjectItem(json_payload, "extendedChargingTime");                   //提升充电时间
    cJSON *balanceChargingInterval = cJSON_GetObjectItem(json_payload, "balanceChargingInterval");             //均衡充电间隔
    cJSON *overvoltageVoltageProt = cJSON_GetObjectItem(json_payload, "overvoltageVoltageProt");               //超压电压保护点
    cJSON *balanceChargeTimeOutPeriod = cJSON_GetObjectItem(json_payload, "balanceChargeTimeOutPeriod");       //均衡充电超时时间

    if (NULL == pvMaxsizeCharge || NULL == packType || NULL == limitChargeVoltage || NULL == undervoltAlarmVolt
        || NULL == overdischargeVoltage || NULL == dischargeLimitVoltage || NULL == ACPowerSwitchVoltage 
        || NULL == switchInverterVolt || NULL == balanceChargeVoltage || NULL == overchargeVoltage
        || NULL == overchargeRecoveryVoltage || NULL == elevatedChargeRecoveryVoltage || NULL == overdischargeRecoveryVoltage
        || NULL == overdischargeDelayTime || NULL == balanceChargingTime || NULL == extendedChargingTime
        || NULL == balanceChargingInterval || NULL == overvoltageVoltageProt || NULL == balanceChargeTimeOutPeriod)
    {
        PCS_ErrCode = DTU_RET_PARAM_ERR;
        return NULL;
    }


    //校验服务器下发的数据是否在正常范围内
    if ((pvMaxsizeCharge->valueint > 100) || (packType->valueint > 14) || undervoltAlarmVolt->valueint < 9 || undervoltAlarmVolt->valueint > 15.5 || overdischargeVoltage->valueint < 9 ||
        overdischargeVoltage->valueint > 15.5 || dischargeLimitVoltage->valueint < 9 || dischargeLimitVoltage->valueint > 15.5 ||
        ACPowerSwitchVoltage->valueint < 9 || ACPowerSwitchVoltage->valueint > 15.5 || switchInverterVolt->valueint < 9 ||
        switchInverterVolt->valueint > 15.5 || balanceChargeVoltage->valueint < 9 || balanceChargeVoltage->valueint > 15.5 ||
        overchargeVoltage->valueint < 9 || overchargeVoltage->valueint > 15.5 || overchargeRecoveryVoltage->valueint < 9 ||
        overchargeRecoveryVoltage->valueint > 15.5 || elevatedChargeRecoveryVoltage->valueint < 9 || elevatedChargeRecoveryVoltage->valueint > 15.5 ||
        overdischargeRecoveryVoltage->valueint < 9 || overdischargeRecoveryVoltage->valueint > 15.5 || overdischargeDelayTime->valueint > 120||
        balanceChargingTime->valueint > 600 || extendedChargingTime->valueint > 600 || extendedChargingTime->valueint < 10||
        balanceChargingInterval->valueint > 255)
    {
        PCS_ErrCode = DTU_RET_PARAM_ERR;
        return NULL;
    }

    u16 buf_1[1] = {pvMaxsizeCharge->valueint};
    u16 buf_2[5] = {packType->valueint, limitChargeVoltage->valuedouble, undervoltAlarmVolt->valuedouble, overdischargeVoltage->valuedouble, dischargeLimitVoltage->valuedouble};
    u16 buf_3[10] = {ACPowerSwitchVoltage->valuedouble, switchInverterVolt->valuedouble, balanceChargeVoltage->valuedouble, overchargeVoltage->valuedouble, overchargeRecoveryVoltage->valuedouble,
                     elevatedChargeRecoveryVoltage->valuedouble, overdischargeRecoveryVoltage->valuedouble, overdischargeDelayTime->valueint, balanceChargingTime->valueint, extendedChargingTime->valueint, balanceChargingInterval->valueint};
    u16 buf_4[2] = {overvoltageVoltageProt->valuedouble, balanceChargeTimeOutPeriod->valuedouble};

    DJY_EventDelay(10 * 1000);
    e1 = eMBMasterReqWriteMultipleHoldingRegister(Addr, 57345, 1, buf_1, -1);
    PCS_ErrCode = GetModbusErrMessage(e1, MB_ENOERR);
    if (DTU_RET_SUCCESS != PCS_ErrCode)
    {
        return NULL;
    }
    e1 = eMBMasterReqWriteMultipleHoldingRegister(Addr, 57347, 12, buf_2, -1);
    PCS_ErrCode = GetModbusErrMessage(e1, MB_ENOERR);
    if (DTU_RET_SUCCESS != PCS_ErrCode)
    {
        return NULL;
    }
    e1 = eMBMasterReqWriteMultipleHoldingRegister(Addr, 57360, 4, buf_3, -1);
    PCS_ErrCode = GetModbusErrMessage(e1, MB_ENOERR);
    if (DTU_RET_SUCCESS != PCS_ErrCode)
    {
        return NULL;
    }
    e1 = eMBMasterReqWriteMultipleHoldingRegister(Addr, 57378, 2, buf_4, -1);
    PCS_ErrCode = GetModbusErrMessage(e1, MB_ENOERR);
    if (DTU_RET_SUCCESS != PCS_ErrCode)
    {
        return NULL;
    }

    json = CreateRetJson(18, false, true);
    if (json == NULL)
    {
        error_printf("PCS", "json is NULL\r\n");
    }
    else
    {
        Ret = cJSON_Print(json);
        if (Ret == NULL)
        {
            error_printf("PCS", "Ret is NULL\r\n");
            strncpy(errlog_PCSBTS,"json print fail", sizeof(errlog_PCSBTS));
            PCS_ErrCode = DTU_RET_OTHER_ERR;
        }
        cJSON_Delete(json);
    }

    return Ret;
}
char *PCS_inverter_parameter_setting(cJSON *json) // PCS逆变器参数设定指令
{
    u8 *Ret = NULL;
    u32 Addr = 0;
    eMBMasterReqErrCode e1;

    Addr = GetServerAddr();
    PCS_ErrCode = ModbusSlaveAddressIsValid(Addr);
    if (DTU_RET_SUCCESS != PCS_ErrCode)
    {
        return NULL;
    }

    cJSON *json_payload = cJSON_GetObjectItem(json, "payload");
    cJSON *parallelMode = cJSON_GetObjectItem(json_payload, "parallelMode");                              //并机模式
    cJSON *LimitChargeCurrentFromAC = cJSON_GetObjectItem(json_payload, "LimitChargeCurrentFromAC");      //市电充电电流限制
    cJSON *EqualChargeEnable = cJSON_GetObjectItem(json_payload, "EqualChargeEnable");                    //均衡充电使能
    cJSON *outputVolt = cJSON_GetObjectItem(json_payload, "outputVolt");                                  //输出电压
    cJSON *outputFrequency = cJSON_GetObjectItem(json_payload, "outputFrequency");                        // 输出频率
    cJSON *MaxsizeChargeCurrent = cJSON_GetObjectItem(json_payload, "MaxsizeChargeCurrent");              //最大充电电流
    cJSON *ACInputRange = cJSON_GetObjectItem(json_payload, "ACInputRange");                              // AC输入范围
    cJSON *energySavingMode = cJSON_GetObjectItem(json_payload, "energySavingMode");                      //节能模式
    cJSON *overloadAutoRestart = cJSON_GetObjectItem(json_payload, "overloadAutoRestart");                //过载自动重启
    cJSON *overtemperatureAutoRestart = cJSON_GetObjectItem(json_payload, "overtemperatureAutoRestart");  //过温自动重启
    cJSON *chargePriority = cJSON_GetObjectItem(json_payload, "chargePriority");                          //充电优先级
    cJSON *AlarmControl = cJSON_GetObjectItem(json_payload, "AlarmControl");                              // 告警控制
    cJSON *inputSourceInterruptAlarmEnable = cJSON_GetObjectItem(json_payload, "overdischargeDelayTime"); // 输入源中断时告警使能
    cJSON *overloadBypassEnable = cJSON_GetObjectItem(json_payload, "overloadBypassEnable");              //过载旁路使能
    cJSON *phaseShiftTransformer = cJSON_GetObjectItem(json_payload, "phaseShiftTransformer");            //分相变压器
    cJSON *BMSEnable = cJSON_GetObjectItem(json_payload, "BMSEnable");                                    // BMS使能

    if (NULL == json_payload || NULL == parallelMode || NULL == LimitChargeCurrentFromAC || NULL == EqualChargeEnable 
        || NULL == outputVolt || NULL == outputFrequency || NULL == MaxsizeChargeCurrent 
        || NULL == ACInputRange || NULL == energySavingMode || NULL == overloadAutoRestart
        || NULL == overtemperatureAutoRestart || NULL == chargePriority || NULL == AlarmControl
        || NULL == inputSourceInterruptAlarmEnable || NULL == overloadBypassEnable || NULL == phaseShiftTransformer
        || NULL == BMSEnable)
    {
        PCS_ErrCode = DTU_RET_PARAM_ERR;
        return NULL;
    }

    if (LimitChargeCurrentFromAC->valueint > 100 || 80 > LimitChargeCurrentFromAC->valueint || LimitChargeCurrentFromAC->valueint > 100
        || 100 > outputVolt->valueint || outputVolt->valueint > 264 || 45 > outputFrequency->valueint || outputFrequency->valueint > 65
        || MaxsizeChargeCurrent->valueint > 150 || ACInputRange->valueint > 1 || 
        overtemperatureAutoRestart->valueint > 1 || EqualChargeEnable->valueint > 1 ||
        energySavingMode->valueint > 1 || overloadAutoRestart->valueint > 1 || AlarmControl->valueint > 1 ||
        inputSourceInterruptAlarmEnable->valueint > 1 || overloadBypassEnable->valueint > 1
        || chargePriority->valueint > 3)
    {
        PCS_ErrCode = DTU_RET_PARAM_ERR;
        return NULL;
    }


    //校验服务器下发的数据是否在正常范围内
    u16 buf_1[3] = {parallelMode->valueint, LimitChargeCurrentFromAC->valueint, EqualChargeEnable->valueint};
    u16 buf_2[12] = {outputVolt->valuedouble, outputFrequency->valuedouble, MaxsizeChargeCurrent->valuedouble, ACInputRange->valueint, energySavingMode->valueint, overloadAutoRestart->valueint, overtemperatureAutoRestart->valueint, chargePriority->valueint,
                     AlarmControl->valueint, inputSourceInterruptAlarmEnable->valueint, overloadBypassEnable->valueint};
    u16 buf_3[2] = {phaseShiftTransformer->valueint, BMSEnable->valueint};

    DJY_EventDelay(10 * 1000);
    e1 = eMBMasterReqWriteMultipleHoldingRegister(Addr, 57857, 3, buf_1, -1);
    PCS_ErrCode = GetModbusErrMessage(e1, MB_ENOERR);
    if (DTU_RET_SUCCESS != PCS_ErrCode)
    {
        return NULL;
    }
    DJY_EventDelay(10 * 1000);
    e1 = eMBMasterReqWriteMultipleHoldingRegister(Addr, 57864, 12, buf_2, -1);
    PCS_ErrCode = GetModbusErrMessage(e1, MB_ENOERR);
    if (DTU_RET_SUCCESS != PCS_ErrCode)
    {
        return NULL;
    }
    DJY_EventDelay(10 * 1000);
    e1 = eMBMasterReqWriteMultipleHoldingRegister(Addr, 57876, 2, buf_3, -1);
    PCS_ErrCode = GetModbusErrMessage(e1, MB_ENOERR);
    if (DTU_RET_SUCCESS != PCS_ErrCode)
    {
        return NULL;
    }


    json = CreateRetJson(19, false, true);
    if (json == NULL)
    {
        error_printf("PCS", "json is NULL\r\n");
    }
    else
    {
        Ret = cJSON_Print(json);
        if (Ret == NULL)
        {
            error_printf("PCS", "Ret is NULL\r\n");
            strncpy(errlog_PCSBTS,"json print fail", sizeof(errlog_PCSBTS));
            PCS_ErrCode = DTU_RET_OTHER_ERR;
        }
        cJSON_Delete(json);
    }
    return Ret;
}

char *Modify_device_time(cJSON *json) //修改设备时间指令
{
    cJSON *json_payload = cJSON_GetObjectItem(json, "payload");
    cJSON *json_currentTime = cJSON_GetObjectItem(json_payload, "currentTime");
    char time_str[20];
    u16 year, month, day, hour, minute, second;
    u8 *Ret = NULL;
    u32 Addr = 0;
    u16 buf[3];
    eMBMasterReqErrCode e1;

    Addr = GetServerAddr();
    PCS_ErrCode = ModbusSlaveAddressIsValid(Addr);
    if (DTU_RET_SUCCESS != PCS_ErrCode)
    {
        return NULL;
    }

    if (json_currentTime == NULL)
    {
        error_printf("PCS", "switchControl is NULL\r\n");
        PCS_ErrCode = DTU_RET_PARAM_ERR;
        return NULL;
    }

    strncpy(time_str, json_currentTime->valuestring, sizeof(time_str));
    
    year = 10 * (time_str[2] - '0') + time_str[3] - '0';
    month = 10 * (time_str[5] - '0') + time_str[6] - '0';
    day = 10 * (time_str[8] - '0') + time_str[9] - '0';;
    hour = 10 * (time_str[11] - '0') + time_str[12] - '0';
    minute = 10 * (time_str[14] - '0') + time_str[15] - '0';
    second = 10 * (time_str[17] - '0') + time_str[18] - '0';

    buf[0] = ((year << 8) & 0xff00) | (month & 0xff);
    buf[1] = ((day << 8) & 0xff00) | (hour & 0xff);
    buf[2] = ((minute << 8) & 0xff00) | (second & 0xff);

    DJY_EventDelay(10 * 1000);
    e1 = eMBMasterReqWriteMultipleHoldingRegister(Addr, 524, 3, buf, -1);
    PCS_ErrCode = GetModbusErrMessage(e1, MB_ENOERR);
    if (DTU_RET_SUCCESS != PCS_ErrCode)
    {
        return NULL;
    }

    json = CreateRetJson(20, false, true);
    if (json == NULL)
    {
        error_printf("PCS", "json is NULL\r\n");
    }
    else
    {
        Ret = cJSON_Print(json);
        if (Ret == NULL)
        {
            error_printf("PCS", "Ret is NULL\r\n");
            strncpy(errlog_PCSBTS,"json print fail", sizeof(errlog_PCSBTS));
            PCS_ErrCode = DTU_RET_OTHER_ERR;
        }
        cJSON_Delete(json);
    }
    return Ret;
}
char *Restart_DTU(void) //重启DTU
{
    u8 *Ret = NULL;
    cJSON *json;

    json = CreateRetJson(21, false, false);
    if (json == NULL)
    {
        error_printf("PCS", "json is NULL\r\n");
    }
    else
    {
        Ret = cJSON_Print(json);
        if (Ret == NULL)
        {
            error_printf("PCS", "Ret is NULL\r\n");
            strncpy(errlog_PCSBTS,"json print fail", sizeof(errlog_PCSBTS));
            PCS_ErrCode = DTU_RET_OTHER_ERR;
        }
        else
        {
            DTU_Reset == true;
        }
        cJSON_Delete(json);
    }
    return Ret;
}

char *QMqtt(cJSON *json)
{
    char *json_data = NULL;

    cJSON *json_cmd = cJSON_GetObjectItem(json, "cmd");
    char *command = json_cmd->valuestring;
    memset(errlog_PCSBTS, 0 , sizeof(errlog_PCSBTS));
    PCS_ErrCode = DTU_RET_SUCCESS;
    if (command == NULL)
    {
        error_printf("PCS", "cmd is NULL\n");
        PCS_ErrCode = DTU_RET_CMD_INVALID;
    }
    else
    {
        if (strcmp(command, QMqtt_group[0]) == 0) //根据数组内容分配到不同方法
        {
            json_data = Registration_Instructions(json);//注册指令
        }
        else if (strcmp(command, QMqtt_group[1]) == 0)
        {
            json_data = Fault_reporting();//故障上报指令
        }
        else if (strcmp(command, QMqtt_group[2]) == 0)
        {
            json_data = QDTU_registration_information(json);//查询DTU注册信息
        }
        else if (strcmp(command, QMqtt_group[3]) == 0)
        {
            json_data = QDTU_device_status(json);//查询DTU设备状态
        }
        else if (strcmp(command, QMqtt_group[4]) == 0)
        {
            json_data = QProduct_information();//查询产品信息
        }
        else if (strcmp(command, QMqtt_group[5]) == 0)
        {
            json_data = QController();//控制器数据查询
        }
        else if (strcmp(command, QMqtt_group[6]) == 0)
        {
            json_data = QInverter_data();//逆变器数据查询
        }
        else if (strcmp(command, QMqtt_group[7]) == 0)
        {
            json_data = QHistorical_Weekly_Statistical_Data();//历史一周统计数据查询
        }
        else if (strcmp(command, QMqtt_group[8]) == 0)
        {
            json_data = Qdaily_statistical_data();//当天统计数据查询
        }
        else if (strcmp(command, QMqtt_group[9]) == 0)
        {
            json_data = QTotal_historical_statistics();//历史统计总数据查询
        }
        else if (strcmp(command, QMqtt_group[10]) == 0)
        {
            json_data = QHistorical_fault_data();//历史故障数据查询
        }
        else if (strcmp(command, QMqtt_group[11]) == 0)
        {
            json_data = QBattery_parameters();//电池参数设定值查询
        }
        else if (strcmp(command, QMqtt_group[12]) == 0)
        {
            json_data = QInverter_parameters();//逆变器参数设定值查询
        }
        else if (strcmp(command, QMqtt_group[13]) == 0)
        {
            json_data = PCS_onORoff_control(json);// PCS开关机控制指令
        }
        else if (strcmp(command, QMqtt_group[14]) == 0)
        {
            json_data = PCS_reset_control(); // PCS复位控制指令
        }
        else if (strcmp(command, QMqtt_group[15]) == 0)
        {
            json_data = PCS_Factory_reset_command();// PCS恢复出厂设置指令
        }
        else if (strcmp(command, QMqtt_group[16]) == 0)
        {
            json_data = PCS_Clear_History();// PCS清除历史记录指令
        }
        else if (strcmp(command, QMqtt_group[17]) == 0)
        {
            json_data = PCS_balanced_charging();// PCS立即均衡充电控制指令
        }
        else if (strcmp(command, QMqtt_group[18]) == 0)
        {
            json_data = PCS_battery_parameter_setting(json);// PCS电池参数设定指令
        }
        else if (strcmp(command, QMqtt_group[19]) == 0)
        {
            json_data = PCS_inverter_parameter_setting(json);// PCS逆变器参数设定指令
        }
        else if (strcmp(command, QMqtt_group[20]) == 0)
        {
            json_data = Modify_device_time(json);//修改设备时间指令
        }
        else if (strcmp(command, QMqtt_group[21]) == 0)
        {
            json_data = Restart_DTU();//重启DTU
        }
        else
        {
            PCS_ErrCode = DTU_RET_DEV_NOT_SUPP_CMD;
        }
    }
    return json_data;
}
