#include "downlink.h"
#include "uplink.h"
#include "device.h"
#include "gateway.h"
#include "../network_mgr/net_proc.h"
#include "../../User/includes.h"
#include "../storage/AT24c128.h"
#include "../gateway_collect/gateway_collect.h"
#include "../dev_mgr/taxctrl/tax_ctrl.h"
#include "../globalDef.h"
#include "../storage/AT24C128Opt.h"
#include "../network_mgr/net_ctrl.h"
#include "../storage/AT24C128Opt.h"
#include "nettimer.h"

#include "me3616.h"

extern ME3616  air;

downlink_config_t downlink_config;
void downlink_init(void)
{
    int ret;
    int i;
    uint32_t flag = 0;
//    memset(&downlink_config.collect_conf,0,sizeof(downlink_config.collect_conf));
//    printf("downlink size %d\n",sizeof(downlink_config));
 //   printf("gateway_read size %d\n",sizeof(gateway_read));

    sprintf(g_upLinkTopic,"%s%04x/%010u",(char*)MQTT_UPLINK_TOPIC,GATEWAY_DEVICE_TYPE, g_firmwareMsg.gatewayMsg.hardwareMsg.gateway_sn);


  //  fram_read_config_msg();
   // if(downlink_config.config_flag == CONFIG_WRITE)
    {
        
        g_ledStatus.collNum =  g_ledStatus.led16.status;
        g_runData.timeSendStatus = 1;
        g_runData.bUpdate = 0;
        g_runData.bsendOilData = 0;
        downlink_config.config_flag =  1;
        g_ledStatus.led16.status = 0x8000;
        set_led_update_status(g_ledStatus.led16.status);
    }

}

int downlink_gateway_para(uint8_t *data, uint16_t len)
{
    int ret=-1;
    int i,j,k;
    downlinkSysCmd0x1011 *p_msg = NULL;
    uint16_t flag = 0x01;
    uint8_t *tempdata;
    tempdata = data+5;





    p_msg = (downlinkSysCmd0x1011 *)data;



    memset(&downlink_config,0,sizeof(downlink_config));


   // if(p_msg->gateway_id != g_firmwareMsg.gatewayMsg.hardwareMsg.gateway_sn)
   //     return ret;

    downlink_config.gateway_id = p_msg->gateway_id;
//    downlink_config.collect_num = p_msg->collect_num;
//    g_firmwareMsg.gatewayMsg.configmsg.coll_num = p_msg->collect_num;
   // g_firmwareMsg.gatewayMsg.hardwareMsg.gateway_sn = p_msg->gateway_id;
   // if(p_msg->collect_num > COLLECT_MAX_NUM) //采集器个数大于最大值，数据错误，直接返回
  //      return ret;


    downlink_config.config_flag = CONFIG_WRITE;
    fram_write_config_msg(flag);
    //fram_write_gateway_soft_msg();
    downlink_config.config_flag = flag;

    g_runData.timeSendStatus = 1;
    g_runData.bUpdate = 0;
    g_runData.bsendOilData = 0;
 //   AT24CXX_Write(CONFIG_ADDR,(uint8_t *)&downlink_config,sizeof(downlink_config));
    NVIC_SystemReset();//复位
	  return 0;
}
/*--------------------------------------------------------------
 *  解析网络下发的 系统类（0x01)的 0x1003指令 切换mqtt服务器
 * -------------------------------------------------------------*/
void downlink_analyze_system_cmd0x1003(uint8_t *data,uint16_t size)
{
    uint8_t len = 0;
    downlinkSysCmd0x1003 *msg = NULL;

    msg = (downlinkSysCmd0x1003*)data;

    if(msg->gateway_sn != downlink_config.gateway_id) return;
    //if(msg->targettype != GATEWAY_DEVICE_TYPE) return;

    memset(&(g_mqttRunDa.mqttMsg),0,sizeof(MqttIdPort));

    memcpy(g_mqttRunDa.mqttMsg.ip,msg->str,msg->iplen);
    len = msg->iplen;
    memcpy(g_mqttRunDa.mqttMsg.port,msg->str+len,msg->portlen);
    len += msg->portlen;
    memcpy(g_mqttRunDa.mqttMsg.admin,msg->str+len,msg->userlen);
    len += msg->userlen;
    memcpy(g_mqttRunDa.mqttMsg.password,msg->str+len,msg->pwdlen);

    g_mqttRunDa.mqttIdlen = msg->iplen;
    g_mqttRunDa.mqttPortlen = msg->portlen;
    g_mqttRunDa.mqttUserlen = msg->userlen;
    g_mqttRunDa.mqttPwdlen = msg->pwdlen;

    close_tcp_mqtt();
    g_mqttRunDa.bChangeMqtt = 1;
    air.State.MQTT_State= 0;
    //g_mqttRunDa.bChangeSuc = 0;
    g_mqttRunDa.connectNum = 0;
    g_runData.cregStatus = 0;


}

/*--------------------------------------------------------------
 *  刷新税控序列号0x1012
 * --------------------------------------------------------------*/
void downlink_analyze_system_cmd0x1012(uint8_t *data,uint16_t size)
{

}

/*--------------------------------------------------------------
 *  设备重新启动 0x1021
 * --------------------------------------------------------------*/
void downlink_analyze_system_cmd0x1021(uint8_t *data,uint16_t size)
{

    downlinkSysCmd0x1021 *p_msg = NULL;

    p_msg = (downlinkSysCmd0x1021*)data;


    switch(p_msg->targetType){
    case 0x0101: // 网关
        if(p_msg->sn != downlink_config.gateway_id) break;
        NVIC_SystemReset();//复位//设备重新启动
        break;
    case 0x0201: // 采集器
        break;
    case 0x0301: // 液位仪采集器
        if(p_msg->sn != downlink_config.gateway_id) break;
        NVIC_SystemReset();//复位//设备重新启动
        break;
    case 0x0401: // 显示器

        break;
    }
}
/*---------------------------------------------------------------
 *  液位仪的配置信息初始化
 * --------------------------------------------------------------*/
void downlink_oil_sys_cmd0x1031(uint8_t *data, uint16_t size)
{
    downlinkSysOilCmd0x1031 *pmsg = NULL;
  //  char sendbuff[32] = {0};
  //  uint16_t len = 0;
 //   downlinkDataOilCmd0x1021 *msg = (downlinkDataOilCmd0x1021*)sendbuff;

    pmsg = (downlinkSysOilCmd0x1031*)data;

    if((pmsg->gateway_sn!=downlink_config.gateway_id) && (pmsg->gateway_sn!=0xFFFFFFFF) ) return;
    g_oilReadMsg.paraLen = pmsg->paraLen;
    memset(g_oilReadMsg.param,0,sizeof(g_oilReadMsg.param));
    memcpy(g_oilReadMsg.param,pmsg->param,pmsg->paraLen);
    g_oilReadMsg.bInit = 0x5;
    fram_write_oil_msg();
    timeout_stop(&g_timeOut);
    g_runData.bsendOilData = READ_TIMER;
//    msg->gateway_sn = downlink_config.gateway_id;

//    len = sizeof(downlinkDataOilCmd0x1021);
//    tax_net_send(sendbuff,len,0x01,0x2031);
}

/*--------------------------------------------------------------
 *  解析网络下发的 系统类（0x01）的数据
 * --------------------------------------------------------------*/
void downlink_analyze_system_cmd(uint16_t type, uint8_t *data, uint16_t size)
{
    switch(type){
    case COLL_DN_SYS_CMD1011: //系统类 采集路由信息初始化下行
        downlink_gateway_para(data,size);
        break;
    case COLL_DN_SYS_CMD1012: // 系统类，刷新税控序列号
        downlink_analyze_system_cmd0x1012(data,size);
        break;
    case COLL_DN_SYS_CMD1021: // 系统类，系统重新启动
        downlink_analyze_system_cmd0x1021(data,size);
        break;
    case GATEWAY_DN_SYS_CMD1003: //配置mqtt服务器
        downlink_analyze_system_cmd0x1003(data,size);
        break;
    case COLL_DN_SYS_CMD1001: // 升级
        gateway_update_proc(data,size);
        break;
    case OILL_DN_SYS_CMD1031: // 系统类，油罐下行配置
        downlink_oil_sys_cmd0x1031(data,size);
        break;
    }
}
/*----------------------------------------------------------------------
 *  解析网络下发的  状态类的信息   固件信息下行指令 0x1001
 * ---------------------------------------------------------------------*/
void downlink_analyze_status_cmd0x1001(uint16_t type, uint8_t *data,uint16_t size)
{
    uint8_t index = 0;
    uint8_t sendBuff[160];
    uint8_t sendLen = 0;

    downlinkStatusCmd0x1001 *pMsg = NULL;

    pMsg = (downlinkStatusCmd0x1001*)data;

    if(pMsg->gateway_sn!=downlink_config.gateway_id) return;
    memset(sendBuff,0,sizeof(sendBuff));
    switch(pMsg->targetType){
    case 0x0101: // 网关
        uplink_tax_statusmcmd_0x2001(sendBuff,&sendLen,pMsg->targetType,0);
        tax_net_send(sendBuff,sendLen,FIRST_TYPE_STATUS,COLL_UP_STATUS_CMD2001);
        break;
    case 0x0201: // 采集器
        
        break;
    case 0x0301: // 液位仪采集器
        uplink_tax_statusmcmd_0x2001(sendBuff,&sendLen,pMsg->targetType,0);
        tax_net_send(sendBuff,sendLen,FIRST_TYPE_STATUS,COLL_UP_STATUS_CMD2001);
        break;
    case 0x0401: // 显示器

        break;
    }
}

/*--------------------------------------------------------------
 *  解析网络下发的状态类（0x02）的数据
 * --------------------------------------------------------------*/
void downlink_analyze_status_cmd(uint16_t type,uint8_t *data, uint16_t size)
{
    switch(type){
    case COLL_DN_STATUS_CMD1001: // 固件信息下行
        downlink_analyze_status_cmd0x1001(type,data,size);
        break;
    }
}
/*--------------------------------------------------------------------
 *  读取液位仪的数据
 * --------------------------------------------------------------------*/
void downlink_oil_data_cmd0x1021(uint8_t *data,uint16_t size)
{
    downlinkDataOilCmd0x1021 *pmsg = NULL;

    pmsg = (downlinkDataOilCmd0x1021*)data;

    if((pmsg->gateway_sn!=downlink_config.gateway_id) && (pmsg->gateway_sn!=0xFFFFFFFF)) return ;

	timeout_stop(&g_timeOut);
        g_runData.bsendOilData = READ_TIMER;
        g_runData.bread = 1;
}

/*--------------------------------------------------------------------
 * 数据类 0x03 类的信息
 * -------------------------------------------------------------------*/
void downlink_analyze_data_cmd(uint16_t type,uint8_t *data, uint16_t size)
{
    switch(type){
    case SECOND_TYPE_DATA_TAX : //报税口类

        break;
    case SECOND_TYPE_DATA_LED : // 显示屏

        break;
    case COLL_OIL_DATA_CMD1021 : // 液位仪
        downlink_oil_data_cmd0x1021(data,size);
        break;
    }
}


extern uint16_t crc16_get(uint8_t *data, uint8_t size);
int downlink_gateway_analyze(uint8_t *data, uint16_t len)
{
    int ret = 1;
    uint16_t crc,fcrc;
    uint8_t msg_type = 0;
    sverMsgHeader *p_msg = (sverMsgHeader *)data;

    if(p_msg->len > 128)
        return ret;

    crc = _crc16_get(data,p_msg->len+FRAME_HEADER_LEN-2);// len-2);
    fcrc = p_msg->info[p_msg->len-1];
    fcrc = (fcrc<<8)|p_msg->info[p_msg->len-2];

    if(p_msg->frame_header != 0xfefe){printf("rcv net data head error\r\n"); return 0;}
    if(crc != fcrc) {printf("rcv net data crc error\r\n"); return 0;}

    msg_type = p_msg->msgtypeFirst;
    printf("msg_type:%d\n",msg_type);
    switch(msg_type)
    {
        case FIRST_TYPE_SYST: //0x01
            downlink_analyze_system_cmd(p_msg->msgtypeSecd,(uint8_t*)p_msg->info,p_msg->len);
            break;
        case FIRST_TYPE_STATUS: // 0x02
            downlink_analyze_status_cmd(p_msg->msgtypeSecd,(uint8_t*)p_msg->info,p_msg->len);
            break;
        case FIRST_TYPE_DATA: // 0x03
            downlink_analyze_data_cmd(p_msg->msgtypeSecd,(uint8_t*)p_msg->info,p_msg->len);
            break;
        default:
            break;
    }
    return 0;
}
