#include <stdio.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <time.h>
#include <errno.h>
#include <signal.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/time.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "cJSON.h"
#include "com_api.h"
#include "kk_hal.h"
#include "kk_product.h"
#include "kcloud_config.h"
#include "infra_sha256.h"
#include <netdb.h>
#include <arpa/inet.h>
#include <netinet/tcp.h>
#include <sys/stat.h>
#include "kk_log.h"
//#include <curl/curl.h>
#include "../../common/curl/include/curl/curl.h"
#include "MQTTAsync.h"
#include "mqtt_api.h"
#define BUFSIZE 1024
#define PRODUCTSECRET  "123456"

static int isIpV4Addr(const char *ipAddr)
{
    int ip_part_1 = 0;
    int ip_part_2 = 0;
    int ip_part_3 = 0;
    int ip_part_4 = 0;
    char end_char = 0;
    
    if((NULL == ipAddr) || (0 == strlen(ipAddr))){
        return -1;
    }
    
    if(4 == sscanf(ipAddr,"%d.%d.%d.%d%c",&ip_part_1,&ip_part_2,&ip_part_3,&ip_part_4,&end_char)){
        if((ip_part_1 >= 0) && (ip_part_1 <= 255) &&
           (ip_part_2 >= 0) && (ip_part_2 <= 255) &&
           (ip_part_3 >= 0) && (ip_part_3 <= 255) &&
           (ip_part_4 >= 0) && (ip_part_4 <= 255) 
        ){
            return 0;
        }
    }
    return -1;
}
int kk_execel_cmd(char * cmd,char * buf,int buf_len,int* ret_len)
{
	if(cmd == NULL || buf == NULL || buf_len == 0)
	{
		INFO_PRINT("arg error\n");
		return -1;
	}

	memset(buf,0,buf_len);

	FILE *fp = NULL;
	fp = popen(cmd,"r");
	while(fgets(buf,buf_len,fp)!=NULL){
		INFO_PRINT("%s return %s",cmd,buf);  
	}
	pclose (fp);

	*ret_len = strlen(buf);
	return 0;
}
int kk_parse_deviceSecret(char *info){
	FILE *fp;
	if(info == NULL){
		return -1;
	}
	cJSON* infoObj = cJSON_Parse(info);
	if(infoObj == NULL){
		INFO_PRINT("[%s][%d]\n",__FUNCTION__,__LINE__);        
		return -1;
	}
	//cJSON *data = cJSON_GetObjectItem(infoObj,"data");
	//if(data == NULL)
	//{
		//return -1;
	//}
	cJSON *deviceSecret = cJSON_GetObjectItem(infoObj,"deviceSecret");
	if(deviceSecret == NULL) return -1;
	fp = fopen(KK_DEVICESECRET_PATH, "w+");
	if(fp != NULL){
		fwrite(deviceSecret->valuestring,strlen(deviceSecret->valuestring),1,fp);
		fclose(fp);
	}
	cJSON_Delete(infoObj);
	return 0;
}
int kk_parse_token(char *info){
	FILE *fp;
	if(info == NULL){
		INFO_PRINT("[%s][%d]\n",__FUNCTION__,__LINE__);
		return -1;
	}
	cJSON* infoObj = cJSON_Parse(info);
	if(infoObj == NULL){
		return -1;
	}
	cJSON *data = cJSON_GetObjectItem(infoObj,"data");
	if(data == NULL)
	{
		cJSON_Delete(infoObj);
		return -1;
	}
	cJSON *jwt = cJSON_GetObjectItem(data,"jwt");
	if(jwt == NULL) return -1;
	fp = fopen(KK_TOKEN_PATH, "w+");
    if(fp != NULL){
        fwrite(jwt->valuestring,strlen(jwt->valuestring),1,fp);
		#ifdef CONFIG_A133_PLATFORM
        fsync(fp);
	    fclose(fp);
		#else
		fclose(fp);
		system("sync;sync;sync");
		#endif
    }  
	//cJSON *ccuid = cJSON_GetObjectItem(infoObj,"ccu_id");
	//if(ccuid == NULL) return -1;	
	//fp = fopen("/usr/kk/kk_ccuid.txt", "w+");
    //if(fp != NULL){
        //fwrite(ccuid->valuestring,strlen(ccuid->valuestring),1,fp);
	    //fclose(fp);
   // }
    cJSON_Delete(infoObj);
	return 0;
}
char *kk_dictionary_order(char *deviceCode, char *productCode,char *randomId)
{
	char str[3][16]={0};
	char temp[16];
	int i,l,len;
	char *signSource = NULL;  
	memcpy(&str[0],deviceCode,strlen(deviceCode));
	memcpy(&str[1],productCode,strlen(productCode));
	memcpy(&str[2],randomId,strlen(randomId));    
	//for (i=0;i<3;i++)
	//{
		//for (l=0;l<16;l++)
		//{
			//INFO_PRINT("%c",str[i][l]);
		//}
		//INFO_PRINT("\n");
	//}
	//排序
	INFO_PRINT("after order：\n");
	int j,k;
	for( j=0;j<3;j++)
	for( k=j+1;k<3;k++)
	{
		if(strcmp(str[j],str[k])>0)
		{//交换
			strcpy(temp,str[j]);
			strcpy(str[j],str[k]);
			strcpy(str[k],temp);
		}
	}
		//for(i=0;i<3;i++)//输出
			//INFO_PRINT("%s\n",str[i]);
	len = strlen(deviceCode) + strlen(productCode) + strlen(randomId) + 1;            
	signSource = malloc(len);
	if (signSource == NULL) {
		return NULL;
	}
	memset(signSource, 0, len);
	snprintf(signSource, len, "%s%s%s", str[0],str[1],str[2]);  
	INFO_PRINT("signSource %s\n",signSource);
	return signSource;           
}

static const char * base64char = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
int base64_encode( const unsigned char *bindata, char *base64, int binlength )
{
    int i, j;
    unsigned char current;

    for ( i = 0, j = 0 ; i < binlength ; i += 3 )
    {
        current = (bindata[i] >> 2) ;
        current &= (unsigned char)0x3F;
        base64[j++] = base64char[(int)current];

        current = ( (unsigned char)(bindata[i] << 4 ) ) & ( (unsigned char)0x30 ) ;
        if ( i + 1 >= binlength )
        {
            base64[j++] = base64char[(int)current];
            base64[j++] = '=';
            base64[j++] = '=';
            break;
        }
        current |= ( (unsigned char)(bindata[i+1] >> 4) ) & ( (unsigned char) 0x0F );
        base64[j++] = base64char[(int)current];

        current = ( (unsigned char)(bindata[i+1] << 2) ) & ( (unsigned char)0x3C ) ;
        if ( i + 2 >= binlength )
        {
            base64[j++] = base64char[(int)current];
            base64[j++] = '=';
            break;
        }
        current |= ( (unsigned char)(bindata[i+2] >> 6) ) & ( (unsigned char) 0x03 );
        base64[j++] = base64char[(int)current];

        current = ( (unsigned char)bindata[i+2] ) & ( (unsigned char)0x3F ) ;
        base64[j++] = base64char[(int)current];
    }
    base64[j] = '\0';
    return 0;
}
int arrayToStr(unsigned char *buf, unsigned int buflen, char *out)
{
    char strBuf[65] = {0};
    char pbuf[32];
    int i;
    for(i = 0; i < buflen; i++)
    {
        sprintf(pbuf, "%02x", buf[i]);
        strncat(strBuf, pbuf, 2);
    }
    strncpy(out, strBuf, buflen * 2);
    INFO_PRINT("out = %s\n", out);
    return buflen * 2;
}

static char * kk_create_register_info()
{
	cJSON *root;
	char *out = NULL;
	char *signSource,*base64Out = NULL;
	char mac[16] = {0};
	char ramdonId[16] = {0};
	unsigned char sign_hex[32] = {0};
	char sign_hex_str[65] = {0}; 
	uint8_t productSecret[64] = {0};
	char ccuid[32] = {0};
	char pid[32] = {0};
	int productSecret_len = 0;
	char keyTmp[64] = {0};
	root=cJSON_CreateObject();
	HAL_Get_mac(mac);
	HAL_GetTime_s(ramdonId);
	KK_Get_ccuid(ccuid);
	kk_cloud_get_pid(pid);
	kk_cloud_get_key(keyTmp);
	cJSON_AddStringToObject(root, "deviceCode", ccuid);
	cJSON_AddStringToObject(root, "productCode",pid);
	signSource = kk_dictionary_order(ccuid,pid,KK_CCU_RANDOM);
	utils_hmac_sha256((const uint8_t *)signSource, strlen(signSource), (const uint8_t *)keyTmp, strlen((const char*)keyTmp), sign_hex);
	arrayToStr(sign_hex,32,sign_hex_str);

	base64Out = malloc(128);
	if (base64Out == NULL) {
		cJSON_Delete(root);
		return NULL;
	}
	INFO_PRINT("[%s][%d]sign_hex:%s\n",__FUNCTION__,__LINE__,sign_hex_str);
	//memset(base64Out, 0, 128);     
	//base64_encode(sign_hex_str,base64Out,strlen(sign_hex_str));  
	INFO_PRINT("[%s][%d]base64Out:%s\n",__FUNCTION__,__LINE__,base64Out);
	cJSON_AddStringToObject(root, "sign",sign_hex_str);
	cJSON_AddStringToObject(root, "random",KK_CCU_RANDOM);
	free(signSource);
	free(base64Out);
	out=cJSON_Print(root);
	//cJSON_Minify(out);
	cJSON_Delete(root);
	INFO_PRINT("--------------------->kk_create_register_info:%s\n",out);
	return out;
}
char g_clientId[64] = {0};
static char * kk_create_get_jwt_info()
{
	cJSON *root;
	FILE *fp;
	char *out = NULL;
	char timestamp[16] = {0};
	char deviceSecret[64] = {0};
	char ccuid[32] = {0};
	char pid[32] = {0};
	HAL_GetTime_s(timestamp);
	KK_Get_ccuid(ccuid);
	kk_cloud_get_pid(pid);
	sprintf(g_clientId, CLIENTID, ccuid,timestamp);
	root=cJSON_CreateObject();
	cJSON_AddStringToObject(root, "deviceCode", ccuid);
	cJSON_AddStringToObject(root, "productCode",pid);
	cJSON_AddStringToObject(root, "clientId",g_clientId);
	fp = fopen(KK_DEVICESECRET_PATH, "r");
	if(fp != NULL){
		fread(deviceSecret,1,sizeof(deviceSecret),fp);
		fclose(fp);
	}
	cJSON_AddStringToObject(root, "deviceSecret",deviceSecret);

	out=cJSON_Print(root);
	//cJSON_Minify(out);
	cJSON_Delete(root);
	INFO_PRINT("--------------------->kk_create_get_jwt_info:%s\n",out);
	return out;
}
char s_ServerIp[16] = {0};
static int kk_send_register_info(int sockfd,const char * path,int type)
{
	char str1[1024], str2[1024],str[16] = {0};
	char tmp[128] = {0};
	int len = 0,sendlen = 0;
	char *pinfo = NULL;
	memset(str2, 0, sizeof(str2));
	if(type == 0){
		pinfo = kk_create_register_info();
		strcat(str2, pinfo);
	}else{
		pinfo = kk_create_get_jwt_info();
		strcat(str2, pinfo);
	}
	len = strlen(str2);
	sprintf(str, "%d", len);

	memset(str1, 0, sizeof(str1));
	memset(tmp, 0, sizeof(tmp));   
	sprintf(tmp, "POST %s HTTP/1.1\n", path);     
	strcat(str1, tmp);
	memset(tmp, 0, sizeof(tmp)); 
	sprintf(tmp, "Host: %s:%d\n",s_ServerIp, PORT);  
	strcat(str1, tmp);
	strcat(str1, "Content-Type: application/json\n");
	strcat(str1, "Content-Length: ");
	strcat(str1, str);
	strcat(str1, "\n\n");
	//str2的值为post的数据
	strcat(str1, str2);
	strcat(str1, "\r\n\r\n");
	INFO_PRINT("%s\n",str1);   
	sendlen = write(sockfd,str1,strlen(str1));
	if(pinfo){
		free(pinfo);
	}
	return sendlen;
}

int kk_start_ccu_register(void)
{
	int sockfd, ret, i, h;
	struct sockaddr_in servaddr;
	char buf[1024] = {0}, buf2[1024] = {0};
	fd_set   t_set1;
	struct timeval  tv;
	int registerType = 0;
	if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0 ) {
		INFO_PRINT("---socket error!\n");
		return -1;
	};
	bzero(&servaddr, sizeof(servaddr));
	servaddr.sin_family = AF_INET;
	servaddr.sin_port = htons(PORT);
	struct hostent *host = gethostbyname(MQTT_AUTH_HOST_NAME);
	if(NULL == host)
	{
		INFO_PRINT("gethostbyname h_errno\n");
		close(sockfd);
		return -1;
	}	
	memcpy(s_ServerIp,inet_ntoa(*(struct in_addr*)(host->h_addr_list[0])),strlen(inet_ntoa(*(struct in_addr*)(host->h_addr_list[0]))));
	INFO_PRINT("---------------------------->s_ServerIp:%s\n",s_ServerIp);
	if (inet_pton(AF_INET, s_ServerIp, &servaddr.sin_addr) <= 0 ){
		INFO_PRINT("--inet_pton error!\n");
		close(sockfd);
		return -1;
	};

	if (connect(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0){
		INFO_PRINT("connect error!\n");
		close(sockfd);
		return -1;
	}
	INFO_PRINT("connect successful\n");
	ret = kk_send_register_info(sockfd,"/deviceRegister/register",0);
	if (ret < 0) {
		INFO_PRINT("send fail\n");
		close(sockfd);
		return -1;
	}else{
		INFO_PRINT("send success send %d bytes！\n\n", ret);
	}
	registerType = 1;

	tv.tv_sec= 1;
	tv.tv_usec= 0;
	h= 0;
	while(1){
		FD_ZERO(&t_set1);
		FD_SET(sockfd, &t_set1);
		h = select(sockfd +1, &t_set1, NULL, NULL, &tv);
		if (h == 0) 
		{
			INFO_PRINT("kk_register receive nothing\n");
			close(sockfd);
			return -1;
		}
		if (h < 0) {
			close(sockfd);
			return -1;
		};
		if ( FD_ISSET(sockfd, &t_set1) ){
			memset(buf, 0, 1024);
			memset(buf2, 0, 1024);
			i= read(sockfd, buf, 1024);
			if (i <= 0){
				close(sockfd);
				return -1;
			}
			INFO_PRINT("\n get %s\n",buf);
			if(registerType == 1){//get deviceSecret
				char* deviceSecret = strstr(buf,"deviceSecret");
				if(deviceSecret != NULL){ 
					char* start = strchr(buf,'{');
					char* end = strrchr(buf,'}');
					strncpy(buf2,start,end-start+1);
					INFO_PRINT("[%s][%d]buf2:%s\n",__FUNCTION__,__LINE__,buf2);
					ret = kk_parse_deviceSecret(buf2);
					if(ret == 0){
						ret = kk_send_register_info(sockfd,"/auth/generateJwt",1);
						if (ret < 0) {
							INFO_PRINT("send fail'\n");
							close(sockfd);
							return -1;
						}else{
							printf("send success send %d bytes！\n\n", ret);
						}
						registerType = 2;
					}
				}
			}else if(registerType == 2){
				char* jwt = strstr(buf,"jwt");
				if(jwt != NULL){
					char* start = strchr(buf,'{');
					char* end = strrchr(buf,'}');
					if(start != NULL && end != NULL){
						strncpy(buf2,start,end-start+1);
						ret = kk_parse_token(buf2);
						if(ret == 0){
							close(sockfd);
							return 0;
						}
					}
				}
			}
		}
	}
	close(sockfd);
	return -1;
}
static int _kk_parse_auth_dl_host(cJSON *authInfo,char *url){
    if(authInfo == NULL ||url == NULL){
        return -1;
    }
    cJSON *host = cJSON_GetObjectItem(authInfo,"host");
    cJSON *proto = cJSON_GetObjectItem(authInfo,"proto");
    cJSON *port = cJSON_GetObjectItem(authInfo,"port");
    if(host != NULL && proto != NULL && port != NULL){
        sprintf(url,"%s://%s:%d/auth-server/1.0/ccu_std/auth",proto->valuestring,host->valuestring,port->valueint);
        INFO_PRINT("%s\n",url); 
        return 0;
    }  
    return -1;  
}
static int _kk_get_auth_dl_host(char *buf,char *url){
    cJSON *authInfo = NULL;
    if(buf == NULL || url == NULL){
        return -1;
    }
    cJSON* configObj = cJSON_Parse(buf);
    if(configObj == NULL){
        return -2;
    }
    cJSON *data = cJSON_GetObjectItem(configObj,"data");
    if(data == NULL){
        authInfo = cJSON_GetObjectItem(configObj,"mqtt_auth_entry");
    }else{
        authInfo = cJSON_GetObjectItem(data,"mqtt_auth_entry");
    }
    _kk_parse_auth_dl_host(authInfo,url);
    cJSON_Delete(configObj);
    return 0;
}
static int s_getAuthSize = 0;
size_t receive_auth_data(void *buffer, size_t size, size_t nmemb, FILE *file){
	INFO_PRINT("buffer:%s\n",buffer);
    size_t s_getAuthSize = fwrite(buffer, size, nmemb, file);
    return s_getAuthSize;
}
static int _kk_auth_param_get(char *param){
	char productId[32] = {0};
	char key[128] = {0};	
	char ccuid[32] = {0};
	int productid_len = 0;	
	int key_len = 0;	
	if(param == NULL){
		return -1;
	}
	KK_Get_ccuid(ccuid);
	kk_cloud_get_pid(productId);
	kk_cloud_get_key(key);
    sprintf(param, "{\"username\":\"%s\",\"password\":\"%s\",\"productid\":\"%s\"}", 
                ccuid, key, productId); 
				
    //sprintf(param, "{\"username\":\"%s\",\"password\":\"%s\",\"productid\":\"%s\"}", 
                //"CCU_17199", "AD4C58175AC4029B9B63EC88656FE61D", "ccu_n12"); 				
	INFO_PRINT("param:%s\n",param);
	return 0;
}
int kk_register_auth_get(){
    int ret = 0;
    char *configData = NULL;
    char url[512] = {0};
	char param[512] = {0};
    FILE *file;
	int defaultFlag = 0;
    CURLcode res; 
	static int s_count = 0;
    CURL* curl;     
    ret = kk_check_config_file(KK_CONFIG_FILE_PATH,&configData);
defaultCon:	
    if(ret != 0){
		defaultFlag = 1;
        ret = kk_check_config_file(KK_DEFAULT_CONFIG_FILE_PATH,&configData);
    }
    if(ret == 0){
        ret = _kk_get_auth_dl_host(configData,url);
		if(ret == -2 && defaultFlag == 0){
			goto defaultCon;
		}
		if(ret == 0){
again:			
			s_count++;
			curl = curl_easy_init();  
			if (NULL == curl){
				if(configData != NULL){
					free(configData);
					configData = NULL;
				}
				return -1;
			}	
			_kk_auth_param_get(param);
			file = fopen(KK_AUTH_CONFIG_FILE_PATH,"w+");
			curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "POST");
			curl_easy_setopt(curl, CURLOPT_URL, url);
			curl_easy_setopt(curl, CURLOPT_POSTFIELDS, param);
			curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, receive_auth_data); 
			curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)file);
			curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
			curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);
			curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
			curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT_MS, 3000);
			curl_easy_setopt(curl, CURLOPT_TIMEOUT, 100);
			curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);  //支持服务器跳转
			curl_easy_setopt(curl, CURLOPT_TCP_KEEPALIVE, 1L);  // enable TCP keep-alive for this transfer 
			curl_easy_setopt(curl, CURLOPT_TCP_KEEPIDLE, 120L);	// keep-alive idle time to 120 seconds 
			curl_easy_setopt(curl, CURLOPT_TCP_KEEPINTVL, 60L);	// interval time between keep-alive probes: 60 seconds   
			res = curl_easy_perform(curl);
			if(res != CURLE_OK){
				curl_easy_cleanup(curl);
				fclose(file);
				if(configData != NULL){
					free(configData);
					configData = NULL;
				}        
				if(s_count < 3){
					sleep(2);
					goto again;
				}else{
					return -2;
				}  
				
			} 
			curl_easy_cleanup(curl);
			fclose(file); 
		}        
    }
    if(configData != NULL){
        free(configData);
        configData = NULL;
    }
    return 0;
}
static int _kk_parse_mq_info(char *data,char *mqhost,char *mqport,char *mqclientId,char *mqpwd,char *mqusr){
	cJSON* configObj = NULL;
	char tmpIP[17] = {0};	
	if(data == NULL){
		return -1;
	}
	configObj = cJSON_Parse(data);
	if(configObj == NULL){
		return -1;
	}
	cJSON *authdata = cJSON_GetObjectItem(configObj,"data");
	if(authdata == NULL) {cJSON_Delete(configObj);return -1;}	
	cJSON *hostJson = cJSON_GetObjectItem(authdata,"host");
	if(hostJson == NULL) {cJSON_Delete(configObj);return -1;}
	if(isIpV4Addr(hostJson->valuestring) != 0){
		struct hostent *host = gethostbyname(hostJson->valuestring);
		if(NULL == host){
			ERROR_PRINT("gethostbyname h_errno\n");
			cJSON_Delete(configObj);
			return -1;
		}	
		memcpy(tmpIP,inet_ntoa(*(struct in_addr*)(host->h_addr_list[0])),strlen(inet_ntoa(*(struct in_addr*)(host->h_addr_list[0]))));		
	}else{
		memcpy(tmpIP,hostJson->valuestring,strlen(hostJson->valuestring));		
	}	
	cJSON *port = cJSON_GetObjectItem(authdata,"port");
	if(port == NULL) {cJSON_Delete(configObj);return -1;}	
	cJSON *clientId = cJSON_GetObjectItem(authdata,"clientId");
	if(clientId == NULL) {cJSON_Delete(configObj);return -1;}		
	cJSON *password = cJSON_GetObjectItem(authdata,"password");
	if(password == NULL) {cJSON_Delete(configObj);return -1;}	
	cJSON *username = cJSON_GetObjectItem(authdata,"username");
	if(username == NULL) {cJSON_Delete(configObj);return -1;}		
	strncpy(mqhost,tmpIP,strlen(tmpIP));	
	strncpy(mqport,port->valuestring,strlen(port->valuestring));	
	strncpy(mqclientId,clientId->valuestring,strlen(clientId->valuestring));		
	strncpy(mqpwd,password->valuestring,strlen(password->valuestring));	
	strncpy(mqusr,username->valuestring,strlen(username->valuestring));	
	cJSON_Delete(configObj);	
	return 0;
}


MQTTAsync kk_connect_default(void)
{
	int ret = 0;
	char *configData = NULL;
	char tmpIP[17] = {0};
	char key[128] = {0};	
	char usrname[32] = {0};			
	char clientId[128] = {0};	
	int key_len = 0;
	char portStr[16] = {0};
	KK_Get_ccuid(usrname);

	HAL_Execel_cmd(GET_KEY_CMD,(char *)key,sizeof(key),&key_len);
	key[key_len-1] = '\0';		
	ret = kk_check_config_file(KK_DEFAULT_CONFIG_FILE_PATH,&configData);
	cJSON* configObj = cJSON_Parse(configData);
	if(configObj == NULL){
		goto error;
	}	
	cJSON *mqttentry = cJSON_GetObjectItem(configObj,"mqtt_entry");
	if(mqttentry == NULL) goto error;
	cJSON *hostJson = cJSON_GetObjectItem(mqttentry,"host");
	if(hostJson == NULL) goto error;
	cJSON *port = cJSON_GetObjectItem(mqttentry,"port");
	if(port == NULL) goto error;	
	cJSON *proto = cJSON_GetObjectItem(mqttentry,"proto");
	if(proto == NULL) goto error;
	if(isIpV4Addr(hostJson->valuestring) != 0){
		struct hostent *host = gethostbyname(hostJson->valuestring);
		if(NULL == host){
			INFO_PRINT("gethostbyname h_errno\n");
			goto error;
		}	
		memcpy(tmpIP,inet_ntoa(*(struct in_addr*)(host->h_addr_list[0])),strlen(inet_ntoa(*(struct in_addr*)(host->h_addr_list[0]))));		
	}else{
		memcpy(tmpIP,hostJson->valuestring,strlen(hostJson->valuestring));		
	}	
	sprintf(clientId,"GID_CCU@KONKE@CCU_STD@%s@1",usrname);
	if(configObj != NULL){
		cJSON_Delete(configObj);
	}	
	if(configData != NULL){
		free(configData);
		configData = NULL;
	}	
	sprintf(portStr,"%d",port->valueint);
	return KK_MQTT_Connect_ex(usrname,key,clientId,tmpIP,portStr);
error:
	if(configObj != NULL){
		cJSON_Delete(configObj);
	}
	if(configData != NULL){
		free(configData);
		configData = NULL;
	}
	return NULL;
}
MQTTAsync kk_mqtt_connect(){
	char *configData = NULL;
	char host[128] = {0};
	char port[8] = {0};
	char pwd[512] = {0};	
	char usrname[32] = {0};		
	char clientId[128] = {0};	
	int ret = 0;
	int defaultFlag = 0;
	cJSON* configObj = NULL;
	ret = kk_check_config_file(KK_AUTH_CONFIG_FILE_PATH,&configData);
    if(ret == 0){
		//defaultFlag = 1;
        //ret = kk_check_config_file(KK_DEFAULT_CONFIG_FILE_PATH,&configData);
		ret = _kk_parse_mq_info(configData,host,port,clientId,pwd,usrname);
		if(ret == 0){
			if(configData != NULL){
				free(configData);
				configData = NULL;
			}
			return KK_MQTT_Connect_ex(usrname,pwd,clientId,host,port);
		}else{
			return NULL;//kk_connect_default();
		}
	}else{
		return NULL;//kk_connect_default();
	}
}