#include <stdio.h>
#include <stdlib.h>
#include <string.h>


#include "kk_data_mng.h"
#include "kk_ccu_msg.h"
#include "kk_lan_sync.h"
#include "kk_lan_debug.h"
#include "kk_lan_node_db.h"
#include "kk_lan_new_dev_notify.h"
#include "kk_oldccu_msg.h"

/*******获取同步数据json*******/
static cJSON *kk_get_sync_data(cJSON *payload)
{
	return cJSON_GetObjectItem(payload,DATA_STR);
}


/*******同步信息-同步房间*******/
static cJSON *_kk_syn_room_item(SYN_ROOM_ITEM *room)
{
	cJSON *item = cJSON_CreateObject();
	
	cJSON_AddStringToObject(item, FLOOR_ID_STR, (room->floor_id==NULL)?EMPTY_STR:room->floor_id);
	cJSON_AddStringToObject(item, ID_STR, (room->room_id==NULL)?EMPTY_STR:room->room_id);
	cJSON_AddStringToObject(item, ROOM_ICON_STR, (room->room_icon==NULL)?EMPTY_STR:room->room_icon);
	cJSON_AddStringToObject(item, NAME_STR, (room->room_name==NULL)?EMPTY_STR:room->room_name);
	cJSON_AddStringToObject(item, ROOM_STATUS_STR, (room->room_status==NULL)?EMPTY_STR:room->room_status);
	
	return item;
}

static cJSON *_kk_syn_rooms_info(int num,SYN_ROOM_ITEM *rooms)
{
	cJSON *roomsAry = cJSON_CreateArray();
	cJSON *room = NULL;
	int i;
	
	SYN_ROOM_ITEM *item = rooms;

	for(i=0;i<num;i++,item++){
		room = _kk_syn_room_item(item);
		if(room!=NULL){
			cJSON_AddItemToArray(roomsAry,room);
		}
	}
	return roomsAry;
}


cJSON *kk_sync_rooms_to_sdk(cJSON *root,cJSON *data)
{
	cJSON *rooms = cJSON_GetObjectItem(data,ROOMS_STR);
	cJSON *room;
	cJSON *roomId,*name,*devices,*scenes;
	cJSON *roomsAry = NULL;
	
	int i;
	int num = cJSON_GetArraySize(rooms);

	SYN_ROOM_ITEM* items = (SYN_ROOM_ITEM*)malloc(sizeof(SYN_ROOM_ITEM)*num);
	SYN_ROOM_ITEM* item = items;
	memset(item,0,(sizeof(SYN_ROOM_ITEM)*num));

	for(i=0;i<num;i++,item++){
		room = cJSON_GetArrayItem(rooms,i);
		
		roomId = cJSON_GetObjectItem(room,ROOMS_ID_STR);
		name = cJSON_GetObjectItem(room,NAME_STR);
		devices = cJSON_GetObjectItem(room,DEVICES_STR);
		scenes= cJSON_GetObjectItem(room,SCENES_STR);

		//todo
		item->floor_id = NULL; 
		item->room_id = roomId->valuestring;
		item->room_icon = NULL;
		item->room_name = name->valuestring;
		item->room_status = NULL;
	}


	

	roomsAry = _kk_syn_rooms_info(num,items);
	cJSON_AddItemToObject(root, ROOMS_STR, roomsAry);
	return root;
}

/*******场景同步*******/

static cJSON *_kk_scene_action_build(SYN_SCENE_ACTION *act)
{
	SYN_SCENE_ACTION *ptr = act;

	if(ptr->nodeid==-1 || ptr->operation==NULL ||
		ptr->operation==NULL){

		return NULL;
	}
	cJSON *action = cJSON_CreateObject();
	cJSON_AddStringToObject(action, "area",(ptr->ui_area==NULL)?"":ptr->ui_area);
	cJSON_AddStringToObject(action, "name",(ptr->ui_name==NULL)?"":ptr->ui_name);
	cJSON_AddStringToObject(action, "delay",(ptr->delay==NULL)?"0":ptr->delay);
	cJSON_AddNumberToObject(action, "nodeid",ptr->nodeid);
	cJSON_AddStringToObject(action, "operate_type",ptr->operate_type);
	cJSON_AddStringToObject(action, "operation",ptr->operation);
	cJSON_AddStringToObject(action, "room_id",ptr->ui_room_id);
	return action;
}


cJSON *kk_scene_actions_build(SYN_SCENE_ACTION *act,int num)
{
	int i;
	cJSON *actions = cJSON_CreateArray();
	

	//printf("------------------->num:%d\n",num);
	SYN_SCENE_ACTION *ptr=act;
	for(i=0;i<num;i++,ptr++){
		//printf("--------------------------->[%s][%d]\n",__FUNCTION__,__LINE__);
		cJSON * action = _kk_scene_action_build(ptr);
		//printf("--------------------------->[%s][%d]\n",__FUNCTION__,__LINE__);
		cJSON_AddItemToArray(actions,action);
		//printf("--------------------------->[%s][%d]\n",__FUNCTION__,__LINE__);
	}
	//printf("--------------------------->[%s][%d]\n",__FUNCTION__,__LINE__);
	return actions;
}

cJSON *kk_scene_build(SYN_SCENE_ITEM **content)
{
	SYN_SCENE_ITEM *ptr= *content;
	cJSON *scene = cJSON_CreateObject();

	if(content==NULL ||*content==NULL){
		return scene;
	}

	cJSON *actions = kk_scene_actions_build(ptr->act,ptr->act_num);

	cJSON_AddItemToObject(scene, "actions",actions);
	cJSON_AddStringToObject(scene, "id",ptr->scene_id);
	cJSON_AddStringToObject(scene, "name",ptr->name);
	cJSON_AddStringToObject(scene, "pannel_id",(ptr->pannel_id==NULL)?"*":ptr->pannel_id);
	cJSON_AddStringToObject(scene, "room_id",ptr->room_id);
	cJSON_AddStringToObject(scene, "scene_image","");
	cJSON_AddStringToObject(scene, "scene_type",ptr->scenetype);

	if(ptr->time==NULL){
		cJSON_AddStringToObject(scene, "timer_enable","0");
		cJSON_AddStringToObject(scene, "time","");
	}else{
		cJSON_AddStringToObject(scene, "timer_enable","1");
		cJSON_AddStringToObject(scene, "time",ptr->time);
	}
	cJSON_AddStringToObject(scene, "week",(ptr->week==NULL)?"":ptr->week);
	return scene;
	
}

int kk_sync_actions(cJSON *actions,SYN_SCENE_ACTION **act)
{
	cJSON *deviceCode,*delay,*epNum,*propertyName,*type,*propertyValue;

	int i,num = cJSON_GetArraySize(actions);
	int node = -1;
	int get_flag = 0;

	*act = (SYN_SCENE_ACTION *)malloc(sizeof(SYN_SCENE_ACTION)*num);
	memset(*act,0,sizeof(SYN_SCENE_ACTION)*num);

	SYN_SCENE_ACTION *ptr=*act;

	for(i=0;i<num;i++,ptr++){


		cJSON *item;
		item = cJSON_GetArrayItem(actions,i);
	
		deviceCode = cJSON_GetObjectItem(item,"deviceCode");
		delay = cJSON_GetObjectItem(item,"delay");
		epNum = cJSON_GetObjectItem(item,"epNum");
		propertyName= cJSON_GetObjectItem(item,"propertyName");
		type= cJSON_GetObjectItem(item,"type");
		propertyValue= cJSON_GetObjectItem(item,"propertyValue");


		ptr->ui_area = NULL;
		ptr->ui_name = NULL;
		ptr->ui_room_id = NULL;
		ptr->delay = delay->valuestring;
		ptr->nodeid = kk_lan_db_node_get(deviceCode->valuestring,epNum->valueint);

		ptr->operate_type ="*";//type->valuestring;//根据实际设备调整
		ptr->operation = "*";//propertyValue->valuestring;//
	}
	return num;
}





static int kk_sync_scene_condition(cJSON *condition,SYN_SCENE_ITEM **build)
{
	cJSON *itemAry = NULL;
	cJSON *startTime,*endTime,*crossDay,*repeat_days;

	if(condition==NULL ||build==NULL||*build==NULL){
		return -1;
	}

	if((itemAry = cJSON_GetObjectItem(condition,"items"))==NULL){
		return -1;
	}
	
	int i,j,num = cJSON_GetArraySize(itemAry);
	int repeat;
	int get_flag = 0;

	SYN_SCENE_ITEM *ptr=*build;
	
	for(i=0;i<num;i++){
		cJSON *item;

		item = cJSON_GetArrayItem(condition,i);
		startTime = cJSON_GetObjectItem(item,"startTime");
		endTime = cJSON_GetObjectItem(item,"endTime");
		crossDay = cJSON_GetObjectItem(item,"crossDay");
		repeat_days = cJSON_GetObjectItem(item,"repeat_days");
		repeat = repeat_days->valueint;

		if(get_flag==0){
			get_flag = 1;
			char temp[10];
			ptr->week = malloc(32);
			memset(ptr->week,0,32);
			for(j=0;j<7;j++){
				if(repeat&(1<<j)){
					memset(temp,0,10);
					snprintf(temp,10,"%d",j);
					strcat(ptr->week,temp);
				}
			}
		}
	}
	return get_flag;
}


typedef struct{
	char *name;
	char *type;
}scenetype_map_s;
static scenetype_map_s sceneTypeMap[] = {
	{"聚会模式","1"},
	{"会议模式","2"},	
	{"家庭影院","3"},
	{"回家模式","4"},
	{"烛光模式","5"},	
	{"离家模式","6"},	
	{"早晨模式","7"},
	{"睡觉模式","8"},	
	{"影院模式","9"},
	{"娱乐模式","13"},		
};
static int kk_get_sceneTypeMap_table_size(void)
{
	return sizeof(sceneTypeMap)/sizeof(scenetype_map_s);
}
cJSON *kk_sync_scence_to_sdk(cJSON *root,cJSON *data)
{
	cJSON *scenes = cJSON_GetObjectItem(data,SCENES_STR);

	cJSON *actions,*enable,*name,*sceneId,*sceneType,*trigger,*condition,*roomId;
	
	int i,num = cJSON_GetArraySize(scenes);
	int k = 0,isMatch = 0;
	
	SYN_SCENE_ITEM *build= (SYN_SCENE_ITEM *)malloc(sizeof(SYN_SCENE_ITEM)*num);
	if(build == NULL){
		return NULL;
	}
	memset(build,0,sizeof(SYN_SCENE_ITEM)*num);
	
	cJSON *scenesAry = cJSON_CreateArray();
	cJSON *sceneItem;

	SYN_SCENE_ITEM *pScene = build;

	for(i=0;i<num;i++,pScene++){
		printf("i=%d\n",i);
		cJSON *item = cJSON_GetArrayItem(scenes,i);
		actions = cJSON_GetObjectItem(item,ACTIONS_STR);
		enable = cJSON_GetObjectItem(item,ENABLE_STR);
		name = cJSON_GetObjectItem(item,NAME_STR);
		sceneId= cJSON_GetObjectItem(item,SCENE_ID_STR);
		sceneType= cJSON_GetObjectItem(item,SCENE_TYPE_STR);
		trigger= cJSON_GetObjectItem(item,SCENE_TRIGGER_STR);
		condition= cJSON_GetObjectItem(item,CONDITION_STR);
		roomId = cJSON_GetObjectItem(item,ROOMS_ID_STR);
		if(roomId == NULL){
			INFO_PRINT("-------------------->NO ROOMID\n");
			continue;
		}
		/*过滤多控 iftt，定时相关场景*/
		if(sceneType == NULL||sceneType->type!=cJSON_Number||sceneType->valueint != 0){
			continue;
		}
		
		int size = kk_get_sceneTypeMap_table_size();
		isMatch = 0;
		for(k = 0; k < size; k++){
			//printf("---------------------------->producTypeMap[k].type:%s\n",producTypeMap[k].type);
			if(!strcmp(name->valuestring,sceneTypeMap[k].name)){
				pScene->scenetype = sceneTypeMap[k].type;
				isMatch = 1;
				break;
			}
		}		
		if(isMatch == 0){
			pScene->scenetype = "100";//自定义场景
		}
		pScene->act_num = kk_sync_actions(actions,&pScene->act);

		kk_sync_scene_condition(condition,&pScene);


		pScene->scene_id = sceneId->valuestring;
		pScene->name = name->valuestring;
		pScene->pannel_id = NULL;
		pScene->room_id = roomId->valuestring;
		sceneItem = kk_scene_build(&pScene);

		cJSON_AddItemToArray(scenesAry,sceneItem);

	}

	cJSON_AddItemToObject(root, "scenes", scenesAry);
	free(build);
	return root;
}

//同步设备
int _kk_sync_device_item(cJSON *deviceCode,cJSON *epNum,cJSON *name,cJSON *roomId,cJSON *deviceAry)
{
	kk_map_dev_node_t *node = NULL;
	char nodeid[32] = {0};
	char gwmac[32] = {0};
	char submac[32] = {0};


	kk_map_dev_ctx *ctx = _kk_map_dev_ctx();
	
	if(deviceCode == NULL || deviceAry==NULL){
		return -1;
	}

	list_for_each_entry(node, &ctx->dev_list, linked_list, kk_map_dev_node_t) {
		if (node != NULL) {
			if(strlen(node->deviceCode)==strlen(deviceCode->valuestring) &&
				!strcmp(node->deviceCode,deviceCode->valuestring)){
				//空调内机不放入devices
				if(strcmp(node->productCode,"3062") == 0){
					continue;
				}
				cJSON *subdevicesItem = cJSON_CreateObject();

				if(epNum==NULL ||epNum->type!=cJSON_String){
					cJSON_AddStringToObject(subdevicesItem, CHANNEL_STRING, "1");
					kk_creater_nodeid(node->deviceCode,1,nodeid);
				}else{
					cJSON_AddStringToObject(subdevicesItem, CHANNEL_STRING, epNum->valuestring);
					kk_creater_nodeid(node->deviceCode,atoi(epNum->valuestring),nodeid);
				}
				cJSON_AddStringToObject(subdevicesItem, NODEID_STRING, nodeid);

				if(name==NULL ||name->type!=cJSON_String){
					cJSON_AddStringToObject(subdevicesItem, NAME_STRING, "unkown");
				}else{
					cJSON_AddStringToObject(subdevicesItem, NAME_STRING, name->valuestring);
				}
				
				if(name==NULL ||name->type!=cJSON_String){
					cJSON_AddStringToObject(subdevicesItem, ROOM_ID_STRING, "unkown");
				}else{
					cJSON_AddStringToObject(subdevicesItem, ROOM_ID_STRING, roomId->valuestring);
				}

				//todo
				cJSON_AddStringToObject(subdevicesItem, DEVICE_FIELD_STRING, "");
				cJSON_AddStringToObject(subdevicesItem, DEVICE_FIELD_IDNDEX_STRING, "");
				cJSON_AddStringToObject(subdevicesItem, DEVICE_ICON_STRING, "");
				cJSON_AddStringToObject(subdevicesItem, DEVICE_POS_STRING, "");
				_deviceCode_switchto_mac(node->gwDeviceCode,gwmac);
				cJSON_AddStringToObject(subdevicesItem, GW_MAC_STRING, gwmac);
				_deviceCode_switchto_mac(node->deviceCode,submac);
				cJSON_AddStringToObject(subdevicesItem, MAC_STRING, submac);

				cJSON_AddStringToObject(subdevicesItem, OPERATE_TYPE_STRING, node->opearteType);
				cJSON_AddItemToArray(deviceAry, subdevicesItem);
			}
		}
	}
	return 0;
}


int kk_sync_device(cJSON *roomId,cJSON *inDevAry,cJSON *outDevAry)
{
	kk_map_dev_node_t *node = NULL;
	kk_map_dev_ctx *ctx = _kk_map_dev_ctx();
	cJSON *deviceCode = NULL,*epNum = NULL,*name = NULL;
	int i,num;


	if(inDevAry==NULL||inDevAry->type!=cJSON_Array||
		outDevAry==NULL||outDevAry->type!=cJSON_Array){
		return -1;
	}
	num = cJSON_GetArraySize(inDevAry);

	for(i=0;i<num;i++){
		printf("...i=%d\n",i);
		cJSON *item = cJSON_GetArrayItem(inDevAry,i);
		deviceCode = cJSON_GetObjectItem(item,"deviceCode");
		epNum = cJSON_GetObjectItem(item,"epNum");
		name = cJSON_GetObjectItem(item,"name");
		_kk_sync_device_item(deviceCode,epNum,name,roomId,outDevAry);
	}


	return 0;
}

int kk_sync_devices_to_sdk(cJSON *root,cJSON *data)
{
	cJSON *rooms = cJSON_GetObjectItem(data,ROOMS_STR);
	cJSON *deviceAry = cJSON_CreateArray();
	int i,num = cJSON_GetArraySize(rooms);
	cJSON *roomId,*devices;

	for(i=0;i<num;i++){
		cJSON *room = cJSON_GetArrayItem(rooms,i);
		roomId = cJSON_GetObjectItem(room,ROOMS_ID_STR);
		devices = cJSON_GetObjectItem(room,DEVICES_STR);
		kk_sync_device(roomId,devices,deviceAry);
	}

	cJSON_AddItemToObject(root, DEVICES_STRING, deviceAry);
	return 0;
}


//同步设备状态
//
cJSON *_kk_sync_devicestatus_arg_build(kk_map_dev_node_t *node,int ch)
{
	int i,num=0,n_num = 0,o_num = 0;
	cJSON *newccu,*oldccu;
	cJSON *arg = NULL;
	int flag = 0;
	

	if(node == NULL ||node->syn_type!=1||node->syn_opcode==NULL){
		return arg;
	}

	newccu = node->newccu;
	oldccu = node->oldccu;

	if(newccu==NULL||newccu->type!=cJSON_Array ||
		oldccu==NULL||oldccu->type!=cJSON_Array){
		return arg;
	}

	n_num = cJSON_GetArraySize(newccu);
	o_num = cJSON_GetArraySize(oldccu);
	
	num = (n_num>o_num)?o_num:n_num;
	//channelNum
	arg = cJSON_CreateObject();
	for(i=0;i<num;i++){
		cJSON * newccuItem = cJSON_GetArrayItem(newccu,i);
		cJSON * oldccuItem = cJSON_GetArrayItem(oldccu,i);
		cJSON * newccuItemCh = cJSON_GetObjectItem(newccuItem,"channel");
		cJSON * oldccuItemCh = cJSON_GetObjectItem(oldccuItem,"channel");
		cJSON *val = NULL;

		cJSON *synType = cJSON_GetObjectItem(oldccuItem,"synType");
		cJSON *synKey = cJSON_GetObjectItem(oldccuItem,"syn");
		if(synType){
			if(synType->type!=cJSON_String ||synKey==NULL ||synKey->type!=cJSON_String) {
				continue ;
			}
			if(newccuItemCh==NULL||oldccuItemCh==NULL||
				newccuItemCh->type!=cJSON_String||
				oldccuItemCh->type!=cJSON_String){
				continue ;
			}
			//todo:
			if(strcmp(synType->valuestring,"timing_shutdown")==0) {
				cJSON *syn_obj = cJSON_CreateObject();

				double t=cJSON_GetObjectItem(newccuItem,"value")->valuedouble;
				char buff[32]={0};

				snprintf(buff,32,"%f",t);
					
				if(t>0){
					cJSON_AddBoolToObject(syn_obj, "enable",1);
					cJSON_AddStringToObject(syn_obj, "time",buff);
				}else{
					cJSON_AddBoolToObject(syn_obj, "enable",0);
					cJSON_AddNullToObject(syn_obj, "time");
				}
				flag = 1;
				cJSON_AddItemToObject(arg, synKey->valuestring,syn_obj);
				
			}else{
				if(atoi(newccuItemCh->valuestring)==atoi(oldccuItemCh->valuestring) &&
					atoi(newccuItemCh->valuestring)==ch){
					if((val = val_conver_new2old(newccuItem,oldccuItem,1))!=NULL){
						flag = 1;
						kk_lan_add_val_to_obj(arg,val,synKey->valuestring);
					}
				}
			}
		}
	}
	if(flag == 0){
		cJSON_Delete(arg);
		return NULL;
	}
	return arg;
}


static int _kk_sync_devices_status_arg_str(kk_map_dev_node_t *node,cJSON *devStatusAry,int *index)
{
	int i,num = 0;

	cJSON *newccu = NULL,*oldccu = NULL;
	cJSON *dev_status = NULL;
	

	if(node == NULL ||devStatusAry==NULL||index==NULL){
		return -1;
	}

	newccu = node->newccu;
	oldccu = node->oldccu;

	if(newccu==NULL||newccu->type!=cJSON_Array ||
		oldccu==NULL||oldccu->type!=cJSON_Array){
		return -2;
	}

	num = cJSON_GetArraySize(newccu);
	for(i=0;i<num;i++){
		cJSON * newccuItem = cJSON_GetArrayItem(newccu,i);
		cJSON * oldccuItem = cJSON_GetArrayItem(oldccu,i);
		
		cJSON *val = NULL;
		if((val = val_conver_new2old(newccuItem,oldccuItem,0))!=NULL){
			char indexId[16] = {0};
			char nodeid[32] = {0};
			cJSON *epNum = cJSON_GetObjectItem(newccuItem,CHANNEL_STRING);
			cJSON *opcode = cJSON_GetObjectItem(newccuItem,OPCODEMAP_STRING);

			if(opcode==NULL||opcode->type!=cJSON_String||
				epNum==NULL ||epNum->type!=cJSON_String){
				continue ;
			}
		
			dev_status = cJSON_CreateObject();
			kk_lan_add_val_to_obj(dev_status,val,"arg");

			kk_creater_nodeid(node->deviceCode,atoi(epNum->valuestring),nodeid);
			
			cJSON_AddStringToObject(dev_status, OPCODE_STRING,opcode->valuestring);
			cJSON_AddNumberToObject(dev_status, NODEID_STRING, atoi(nodeid));
			memset(indexId,0,sizeof(indexId));
			snprintf(indexId,sizeof(indexId),"%d",*index);
			*index += 1;
			cJSON_AddStringToObject(dev_status, "index", indexId);

			cJSON_AddItemToArray(devStatusAry,dev_status);
		}
	}
	return 0;
}





static int _kk_sync_devices_status_arg_obj(kk_map_dev_node_t *node,cJSON *devStatusAry,int *aryIx,int ch)
{
	char indexId[16] = {0};
	char nodeid[32] = {0};
	cJSON *arg = NULL;
	cJSON *dev_status = NULL;
	if(node==NULL ||devStatusAry==NULL||aryIx==NULL){
		return -1;
	}
	
	if((arg = _kk_sync_devicestatus_arg_build(node,ch))==NULL){
		return -2;
	}
	dev_status = cJSON_CreateObject();
	
	cJSON_AddItemToObject(dev_status,ARG_STRING,arg);
	cJSON_AddStringToObject(dev_status, OPCODE_STRING,node->syn_opcode);

	//新风多合一面板需要获取第三路状态
	if(strcmp(node->productCode,AIR_FRESH_MUTI_DEVICE) == 0){
		kk_creater_nodeid(node->deviceCode,3,nodeid);
	}else if(strcmp(node->productCode,HEATING_FRESH_MUTI_DEVICE) == 0){////地暖多合一面板需要获取第三路状态
		kk_creater_nodeid(node->deviceCode,2,nodeid);
	}else{
		kk_creater_nodeid(node->deviceCode,ch,nodeid);
	}
	cJSON_AddNumberToObject(dev_status, NODEID_STRING, atoi(nodeid));
	
	memset(indexId,0,sizeof(indexId));
	snprintf(indexId,sizeof(indexId),"%d",*aryIx);
	*aryIx+=1;
	cJSON_AddStringToObject(dev_status, "index", indexId);
	
	cJSON_AddItemToArray(devStatusAry,dev_status);
	return 0;
}

int kk_sync_devices_status_to_sdk(cJSON *root)
{
	int idx = 1;
	int i;
	kk_map_dev_node_t *node = NULL;	
	kk_map_dev_ctx *ctx = _kk_map_dev_ctx();
	kk_map_dev_node_t *n = NULL;

	cJSON *devStatusAry = cJSON_CreateArray();
	printf("[%s][%d]\n",__FUNCTION__,__LINE__);

	_kk_map_dev_mutex_lock();
	list_for_each_entry_safe(node,n, &ctx->dev_list, linked_list, kk_map_dev_node_t){

		if(node->syn_type==1){

			for(i=0;i<node->channelNum;i++){
				_kk_sync_devices_status_arg_obj(node,devStatusAry,&idx,i+1);
			}
			
		}else{
			_kk_sync_devices_status_arg_str(node,devStatusAry,&idx);
			//_kk_sync_devicestatus(node,devStatusAry);

		}
	}
	_kk_map_dev_mutex_unlock();
	cJSON_AddItemToObject(root, DEVICE_STATUS_STRING, devStatusAry);
	

	return 0;
}


//同步网关版本
cJSON *kk_sync_gw_version_to_sdk(cJSON *root,cJSON *data)
{
	cJSON *devicesAry = cJSON_GetObjectItem(data,DEVICES_STR);

	cJSON *gw_version = cJSON_CreateArray();
	int i,gw_num;
	if(devicesAry->type!=cJSON_Array){
		return NULL;
	}

	gw_num = cJSON_GetArraySize(devicesAry);

	for(i=0;i<gw_num;i++){
		cJSON *version = cJSON_CreateObject();
		
		cJSON *item = cJSON_GetArrayItem(devicesAry,i);

		//todo:下载版本,运行版本,网关类型转换
		cJSON *run_version = cJSON_GetObjectItem(item,"firmwareVersion");
		cJSON *download_version = cJSON_GetObjectItem(item,"firmwareVersion");
		cJSON *gw_mac = cJSON_GetObjectItem(item,"mac");
		cJSON *gw_type = cJSON_GetObjectItem(item,"name");

		cJSON_AddStringToObject(version,"run_version",(run_version->valuestring)?run_version->valuestring:"");
		cJSON_AddStringToObject(version,"download_version",(download_version->valuestring)?download_version->valuestring:"");
		cJSON_AddStringToObject(version,"gw_mac",(gw_mac->valuestring)?gw_mac->valuestring:"");
		cJSON_AddStringToObject(version,"gw_type",(gw_type->valuestring)?gw_type->valuestring:"");
		cJSON_AddItemToArray(gw_version,version);
	}

	cJSON_AddItemToObject(root, "gw_version", gw_version);

	return root;
}

//同步ccu版本
cJSON *kk_sync_ccu_version_to_sdk(cJSON *root,cJSON *data)
{
	//todo:同步CCU版本信息
	cJSON *ccu_version = cJSON_CreateObject();
	cJSON *version = cJSON_GetObjectItem(data,"firmwareVersion");
	if(version != NULL){
		cJSON_AddStringToObject(ccu_version, "cur_ccu_version", version->valuestring); 
	}else{
		cJSON_AddStringToObject(ccu_version, "cur_ccu_version", "1.0.0"); 
	}
	cJSON_AddStringToObject(ccu_version, "downloaded_ccu_version", "1.0.0"); 
	cJSON_AddItemToObject(root, "ccu_version", ccu_version);

	return root;
}


#define GUARD_LEAVE_HOME				1 //离家布防
#define UNGUARD							2 //撤防
#define GUARD_AT_HOME					3 //在家布防
#define GUARD_CUSTOM					4 //自定义防区布防

/*
1：在家安防传感器，
2：室外安防传感器，
3：24小时安防传感器。
4：24小时不告警传感器。
*/
typedef struct{
	char *nodeId;
	char *sensor_type;
}SYN_GUARD_SENSORS;
static int _kk_guard_sensors_build(cJSON *guard_sensors,int num,SYN_GUARD_SENSORS *sensors)
{
	int i;
	SYN_GUARD_SENSORS *pSensor;

	if(num<=0 || sensors==NULL){
		return -1;
	}
	
	pSensor = sensors;
	for(i=0;i<num;i++,pSensor++){
		cJSON *item = cJSON_CreateObject();
		cJSON_AddStringToObject(item,"nodeid",(pSensor->nodeId)?pSensor->nodeId:"-1");
		cJSON_AddStringToObject(item,"sensor_type",(pSensor->sensor_type)?pSensor->sensor_type:"0");
		cJSON_AddItemToArray(guard_sensors,item);
	}
	return 0;
}



int kk_sync_guard_to_sdk(cJSON *root,cJSON *data)
{
	char *armingStr = NULL;
	
	cJSON *guard = cJSON_CreateObject();
	cJSON *custom_guard_zone = cJSON_CreateArray();
	cJSON *guard_sensors = cJSON_CreateArray();
	
	cJSON *properties = cJSON_GetObjectItem(data,"properties");
	cJSON *ArmingState = NULL,*RoomIdsAry = NULL;
	
	cJSON_AddStringToObject(guard, "arming_status", "1");
	cJSON_AddItemToObject(guard,"custom_guard_zone",custom_guard_zone);
	cJSON_AddItemToObject(guard,"guard_sensors",guard_sensors);
	
	cJSON_AddItemToObject(root, "guard", guard);

	if(properties==NULL||properties->type!=cJSON_Object){
		return -1;
	}

	ArmingState = cJSON_GetObjectItem(properties,"ArmingState");
	if(ArmingState==NULL||ArmingState->type!=cJSON_Number){
		return -1;
	}

	/*
	"0": "离家布防",
	"1": "撤防",
	"2": "在家布防",
	"3": "区域布防"
	*/
	//1：离家布防，2：撤防，3：在家布防，4：自定义防区布防。
	
	if(ArmingState->valueint==0){
		armingStr = "1";
	}else if(ArmingState->valueint==2){
		armingStr = "3";
	}else if(ArmingState->valueint==3){
		armingStr = "4";
	}else {
		armingStr = "2";
	}
	
	cJSON_ReplaceItemInObject(guard, "arming_status", cJSON_CreateString(armingStr));
	if(ArmingState->valueint == 3){
		int i,num;
		cJSON *item = NULL;
		char roomIdStr[16] = {0};
		RoomIdsAry = cJSON_GetObjectItem(properties,"ccuRoomIds");
		if(RoomIdsAry==NULL||RoomIdsAry->type!=cJSON_Array){
			return -1;
		}
		num = cJSON_GetArraySize(RoomIdsAry);
		for(i=0;i<num;i++){
			item = cJSON_GetArrayItem(RoomIdsAry,i);
			if(item->type!=cJSON_Number){
				continue ;
			}
			memset(roomIdStr,0,sizeof(roomIdStr));
			snprintf(roomIdStr,sizeof(roomIdStr),"%d",item->valueint);
			cJSON_AddItemToArray(custom_guard_zone,cJSON_CreateString(roomIdStr));
		}
	}
	//新中控同步接口未有安防类传感器列表,故只保留实现接口,未具体实现转换
	_kk_guard_sensors_build(guard_sensors,-1,NULL);
	return 0;
}



//同步空调网关
/*

cJSON *_kk_sync_central_ac_gw(SYN_CENTRAL_AC_GW *gw)
{
	cJSON *item = cJSON_CreateObject();
	
	cJSON *status;

	cJSON_AddStringToObject(item, "bind_central_ac_gw_node_id",(gw->node)?gw->node:"");
	cJSON_AddStringToObject(item, "dev_name", (gw->dev_name)?gw->dev_name:"");
	cJSON_AddStringToObject(item, "id", (gw->id)?gw->id:"");
	cJSON_AddStringToObject(item, "room_id", (gw->room_id)?gw->room_id:"");

	cJSON_AddItemToObject(item, "status",gw->status?gw->status:cJSON_CreateNull());
	
	return item;
}
*/



static int kk_get_ac_indoor_info_by_deviceCode(cJSON *data,char *pdeviceCode,char*roomId,char*name,int epNum)
{
	cJSON *rooms = cJSON_GetObjectItem(data,"rooms");
	cJSON * item = rooms->child;
	
	while(item != NULL){
		cJSON *devices = cJSON_GetObjectItem(item,"devices");
		if(devices == NULL){
			return -1;
		}
		cJSON * subitem = devices->child;

		while(subitem != NULL){

			cJSON *deviceCode = cJSON_GetObjectItem(subitem,"deviceCode");
			cJSON *epObj = cJSON_GetObjectItem(subitem,"epNum");

			if(deviceCode != NULL && !strcmp(deviceCode->valuestring,pdeviceCode))
			{
				if(epObj!=NULL&&epObj->type==cJSON_String){
					if(atoi(epObj->valuestring)==epNum){
						cJSON *roomIdJ = cJSON_GetObjectItem(item,"roomId");
						cJSON *nameObj = cJSON_GetObjectItem(subitem,"name");
						if(roomId!=NULL){
							memcpy(roomId,roomIdJ->valuestring,strlen(roomIdJ->valuestring));
						}

						if(name!=NULL){
							memcpy(name,nameObj->valuestring,strlen(nameObj->valuestring));
						}
					
						
						return 0;
					}
				
				}else{
					cJSON *roomIdJ = cJSON_GetObjectItem(item,"roomId");
					cJSON *nameObj = cJSON_GetObjectItem(item,"name");
					if(roomId!=NULL){
						memcpy(roomId,roomIdJ->valuestring,strlen(roomIdJ->valuestring));
						
					}

					if(name!=NULL){
						memcpy(name,nameObj->valuestring,strlen(nameObj->valuestring));
					}
				
					
					return 0;
				}
				
			
				
			}
			subitem = subitem->next;
			
		}
		item = item->next;
	}
	debug_log(LOG_ALERT_LEVEL,"[err]\n");
	return -1;
}



new_dev_item g_new_item[16] = {0};
CENTRAL_AC_INDOOR_ITEM *g_indoor_item = NULL;
int g_newgw_count = 0;
int g_indoor_count = 0;
void kk_clear_indoor_data()
{
	memset(g_new_item,0x0,sizeof(new_dev_item)*16);
	if(g_indoor_item != NULL){
		free(g_indoor_item);
		g_indoor_item = NULL;
	}
	g_newgw_count = 0;
	g_indoor_count = 0;
}
void kk_create_new_central_ac(char *gwDeviceCode,char *deviceCode,char *nodeId)
{
	char gwmac[32] = {0};
	char submac[32] = {0};
	if(g_newgw_count > 64){
		return;
	}
	//printf("------------------CWC------------------------>[%s][%d]\n",__FUNCTION__,__LINE__);
	_deviceCode_switchto_mac(gwDeviceCode,gwmac);
	_deviceCode_switchto_mac(deviceCode,submac);
	memcpy(g_new_item[g_newgw_count].gwmac,gwmac,strlen(gwmac));
	memcpy(g_new_item[g_newgw_count].mac,submac,strlen(submac));
	memcpy(g_new_item[g_newgw_count].channel,"1",strlen("1"));
	memcpy(g_new_item[g_newgw_count].operate_type,"12001",strlen("12001"));
	memcpy(g_new_item[g_newgw_count].nodeid,nodeId,strlen(nodeId));
	g_newgw_count++;
	//printf("------------------CWC------------------------>[%s][%d]\n",__FUNCTION__,__LINE__);
	return;
}

char *modeMap[] = {
	"AUTO",
	"COLD",
	"HOT",
	"AIR_SUPPLY",
	"DEHUMIDIFICATION",
	"UNKONWN"
};
char *speedMap[] = {
	"AUTO",
	"UNKONWN",
	"LOW",
	"MID",
	"HIGH",
	"UNKONWN",
	"UNKONWN",
};




static INDOOR_AIR_DEV indoor_air_status[MAX_AC_GW_AIR_NUM];

int indoor_airstatus_table_match_item(const char *deviceCode)
{
	int i;
	for(i=0;i<MAX_AC_GW_AIR_NUM;i++){
		if(strcmp(deviceCode,indoor_air_status[i].deviceCode)==0){
			return i;
		}
	}
	
	return -1;
}


int indoor_airstatus_table_find_empty_item(void)
{
	int i;
	for(i=0;i<MAX_AC_GW_AIR_NUM;i++){
		if(strlen(indoor_air_status[i].deviceCode)==0){
			return i;
		}
	}
	
	return -1;
}

int indoor_airstatus_table_match_status_item(int epNum,INDOOR_AIR_STATUS *status)
{
	int i;
	INDOOR_AIR_STATUS *ptr=status;
	
	for(i=0;i<MAX_AC_INDOOR_AIR_NUM;i++,ptr++){
		if(ptr->epNum==epNum){
			return i;
		}
	}
	
	return -1;
}

int indoor_airstatus_table_find_empty_status_item(INDOOR_AIR_STATUS *status)
{
	int i;
	INDOOR_AIR_STATUS *ptr=status;
	
	for(i=0;i<MAX_AC_INDOOR_AIR_NUM;i++,ptr++){
		if(ptr->epNum==0){
			return i;
		}
	}
	
	return -1;
}


int indoor_airstatus_table_insert_item(const char *deviceCode,int epNum,int online,int PowerSwitch,double Temperature,int WindSpeed,int WorkMode)
{

	if(PowerSwitch==0&&Temperature==0&&WindSpeed==0&&WorkMode==0){
		return -1;
	}

	int ix = indoor_airstatus_table_match_item(deviceCode);

	if(ix!=-1){
		int ix2 = indoor_airstatus_table_match_status_item(epNum,indoor_air_status[ix].status);
		if(ix2!=-1){

			indoor_air_status[ix].status[ix2].online = online;
			indoor_air_status[ix].status[ix2].PowerSwitch = PowerSwitch;
			indoor_air_status[ix].status[ix2].Temperature = Temperature;
			indoor_air_status[ix].status[ix2].WindSpeed = WindSpeed;
			indoor_air_status[ix].status[ix2].WorkMode = WorkMode;
			debug_log(LOG_NOTICE_LEVEL,"[update] ix=%d,ix2=%d\n",ix,ix2);
		
		}else{
			ix2 = indoor_airstatus_table_find_empty_status_item(indoor_air_status[ix].status);
			if(ix2==-1){
				debug_log(LOG_WARNING_LEVEL,"table full!!!\n");
				return -1;
			}
			debug_log(LOG_NOTICE_LEVEL,"[add] epNum=%d,ix2=%d\n",epNum,ix2);

			indoor_air_status[ix].status[ix2].epNum = epNum;
			indoor_air_status[ix].status[ix2].online = online;
			indoor_air_status[ix].status[ix2].PowerSwitch = PowerSwitch;
			indoor_air_status[ix].status[ix2].Temperature = Temperature;
			indoor_air_status[ix].status[ix2].WindSpeed = WindSpeed;
			indoor_air_status[ix].status[ix2].WorkMode = WorkMode;
		}
	}else{
		ix = indoor_airstatus_table_find_empty_item();
		if(ix==-1){
			debug_log(LOG_WARNING_LEVEL,"table full!!!\n");
			return -1;
		}
		debug_log(LOG_NOTICE_LEVEL,"[add] deviceCode=%s\n",deviceCode);

		snprintf(indoor_air_status[ix].deviceCode,PRODUCT_CODE_LEN,"%s",deviceCode);
		indoor_air_status[ix].status[0].epNum = epNum;
		indoor_air_status[ix].status[0].online = online;
		indoor_air_status[ix].status[0].PowerSwitch = PowerSwitch;
		indoor_air_status[ix].status[0].Temperature = Temperature;
		indoor_air_status[ix].status[0].WindSpeed = WindSpeed;
		indoor_air_status[ix].status[0].WorkMode = WorkMode;
	}
	return 0;
}


INDOOR_AIR_STATUS *indoor_airstatus_table_find_item(const char *deviceCode,int epNum)
{
	int ix = indoor_airstatus_table_match_item(deviceCode);
	if(ix!=-1){
		int ix2 = indoor_airstatus_table_match_status_item(epNum,indoor_air_status[ix].status);
		if(ix2!=-1){
			return &indoor_air_status[ix].status[ix2];
		}
	}
	return NULL;
}

int indoor_airstatus_table_delete_item(const char *deviceCode)
{
	debug_log(LOG_NOTICE_LEVEL,"[delete] deviceCode=%s\n",deviceCode);
	int ix = indoor_airstatus_table_match_item(deviceCode);
	if(ix!=-1){
		memset(indoor_air_status[ix].deviceCode,0,PRODUCT_CODE_LEN);
		for(int i=0;i<MAX_AC_INDOOR_AIR_NUM;i++){
			memset(&indoor_air_status[ix].status[i],0,sizeof(INDOOR_AIR_STATUS));
		}
	}else{
		return -1;
	}
	return 0;
}





int kk_send_indoorAir_status(cJSON *info,const char *deviceCode)
{
	char epStr[4] = {0};
	char nodeStr[12] = {0};
	int node;
	if(info == NULL){
		return -1;
	}

	
	cJSON *epNum =  cJSON_GetObjectItem(info,"epNum");
	if(epNum == NULL){
		return -1;
	}
	cJSON *root = cJSON_CreateObject();
	node = kk_lan_db_node_get(deviceCode,atoi(epNum->valuestring));
	snprintf(nodeStr,sizeof(nodeStr),"%d",node);
	
	cJSON_AddStringToObject(root, "nodeid", nodeStr);
	cJSON_AddStringToObject(root, "opcode", "CENTRAL_AC_INDOOR_UNIT_STATUS");
	cJSON_AddStringToObject(root, "status", "success");	
	cJSON *arg = cJSON_CreateObject();
	cJSON_AddBoolToObject(arg, "online", 1);	
	cJSON *PowerSwitch =  cJSON_GetObjectItem(info,"PowerSwitch");
	if(PowerSwitch == NULL) {cJSON_Delete(root);return -1;}
	cJSON_AddBoolToObject(arg, "on", PowerSwitch->valueint);	
	cJSON *Temperature =  cJSON_GetObjectItem(info,"Temperature");
	if(Temperature == NULL) {cJSON_Delete(root);return -1;}
	cJSON_AddNumberToObject(arg,"settingTemperature",Temperature->valuedouble);
	cJSON *CurrentTemperature =  cJSON_GetObjectItem(info,"CurrentTemperature");
	if(CurrentTemperature == NULL) {cJSON_Delete(root);return -1;}
	cJSON_AddNumberToObject(arg,"roomTemperature",CurrentTemperature->valuedouble);
	cJSON *WindSpeed =  cJSON_GetObjectItem(info,"WindSpeed");
	if(WindSpeed == NULL) {cJSON_Delete(root);return -1;}
	cJSON_AddStringToObject(arg, "fanSpeed", speedMap[WindSpeed->valueint]);	
	cJSON *WorkMode =  cJSON_GetObjectItem(info,"WorkMode");
	if(WorkMode == NULL) {cJSON_Delete(root);return -1;}
	cJSON_AddStringToObject(arg, "runModel", modeMap[WorkMode->valueint]);	
	cJSON_AddItemToObject(root, "arg", arg);

	indoor_airstatus_table_insert_item(deviceCode,atoi(epNum->valuestring),1,PowerSwitch->valueint,Temperature->valuedouble,WindSpeed->valueint,WorkMode->valueint);

	send_msg_to_module(root);
	cJSON_Delete(root);	
	return 0;

}
cJSON *kk_sync_central_ac_to_sdk(cJSON *root,cJSON *data)
{
	int gw_num = 0,i = 0;
	int sub_num = 0,j = 0;
	int k = 0;
	char nodeid[8] = {0};
	char ac_gw_nodeid[8] = {0};
	char roomId[32] = {0};
	char deviceName[256] = {0};

	cJSON *central_ac_gws = cJSON_CreateArray();
//	SYN_CENTRAL_AC_GW ac;
	if(data == NULL){
		return NULL;
	}
	kk_clear_indoor_data();
	cJSON *gwAry = cJSON_GetObjectItem(data,DEVICES_STR);
	if(gwAry == NULL) return NULL;
	gw_num = cJSON_GetArraySize(gwAry);
	for(i = 0; i < gw_num; i++){
		cJSON *gwitem = cJSON_GetArrayItem(gwAry,i);
		cJSON *gwDeviceCode = cJSON_GetObjectItem(gwitem,"deviceCode");
		if(gwitem == NULL) return NULL;
		cJSON *subAry = cJSON_GetObjectItem(gwitem,DEVICES_STR);
		if(subAry == NULL) return NULL;
		sub_num = cJSON_GetArraySize(subAry);
		for(j = 0; j < sub_num; j++){
			cJSON *subitem = cJSON_GetArrayItem(subAry,j);
			if(subitem == NULL) return NULL;
			cJSON *productCode = cJSON_GetObjectItem(subitem,"productCode");
			if(productCode != NULL && strcmp(productCode->valuestring,"3062") == 0){//空调网关设备
				cJSON *deviceCode = cJSON_GetObjectItem(subitem,"deviceCode");

				kk_creater_nodeid(deviceCode->valuestring,1,ac_gw_nodeid);
	
				cJSON *properties = cJSON_GetObjectItem(subitem,"properties");
				cJSON *onlineStatus = cJSON_GetObjectItem(subitem,"onlineStatus");
				cJSON *indoorItem = cJSON_CreateObject();	

				kk_get_ac_indoor_info_by_deviceCode(data,deviceCode->valuestring,roomId,NULL,1);


				cJSON_AddStringToObject(indoorItem, "bind_central_ac_gw_node_id",ac_gw_nodeid);
				cJSON_AddStringToObject(indoorItem, "dev_name", "空调网关");
				cJSON_AddStringToObject(indoorItem, "id", ac_gw_nodeid);
				cJSON_AddStringToObject(indoorItem, "room_id", roomId);								
				cJSON_AddItemToArray(central_ac_gws,indoorItem);	
				
				cJSON *epsAry = cJSON_GetObjectItem(properties,"eps");
				cJSON *EpTotal = cJSON_GetObjectItem(properties,"EpTotal");
				
				
				int epsize = cJSON_GetArraySize(epsAry);
				g_indoor_item = (CENTRAL_AC_INDOOR_ITEM *)malloc(sizeof(CENTRAL_AC_INDOOR_ITEM)*epsize);
				if(g_indoor_item == NULL){
					return NULL;
				}
				memset(g_indoor_item,0x0,sizeof(CENTRAL_AC_INDOOR_ITEM)*epsize);
				g_indoor_count = epsize;
				for(k = 0; k < epsize; k++){
					char tmpIdx[16] = {0};
					cJSON *infoItem = cJSON_GetArrayItem(epsAry,k);
					if(infoItem == NULL) continue;


					kk_creater_nodeid(deviceCode->valuestring,k+2,nodeid);
					kk_get_ac_indoor_info_by_deviceCode(data,deviceCode->valuestring,g_indoor_item[k].room_id,g_indoor_item[k].dev_name,k+2);

					memcpy(g_indoor_item[k].id,nodeid,strlen(nodeid));
					sprintf(tmpIdx,"%d",k);
					memcpy(g_indoor_item[k].indooruint_addr,tmpIdx,strlen(tmpIdx));
					memcpy(g_indoor_item[k].nodeid,ac_gw_nodeid,strlen(ac_gw_nodeid));
					
					cJSON *PowerSwitch =  cJSON_GetObjectItem(infoItem,"PowerSwitch");
					g_indoor_item[k].ac_gw_status.on = PowerSwitch->valueint == 1?true:false;
					g_indoor_item[k].ac_gw_status.online = 1;
					cJSON *Temperature =  cJSON_GetObjectItem(infoItem,"Temperature");
					cJSON *CurrentTemperature =  cJSON_GetObjectItem(infoItem,"CurrentTemperature");
					g_indoor_item[k].ac_gw_status.settingTemperature = Temperature->valuedouble;
					g_indoor_item[k].ac_gw_status.roomTemperature = CurrentTemperature->valuedouble;
					cJSON *WindSpeed =  cJSON_GetObjectItem(infoItem,"WindSpeed");
					memcpy(g_indoor_item[k].ac_gw_status.speed,speedMap[WindSpeed->valueint],strlen(speedMap[WindSpeed->valueint]));
					cJSON *WorkMode =  cJSON_GetObjectItem(infoItem,"WorkMode");
					memcpy(g_indoor_item[k].ac_gw_status.mode,modeMap[WorkMode->valueint],strlen(modeMap[WorkMode->valueint]));

					cJSON *epNum = cJSON_GetObjectItem(infoItem,"epNum");
					
				
					indoor_airstatus_table_insert_item(deviceCode->valuestring,epNum->valueint,onlineStatus->valueint,PowerSwitch->valueint,Temperature->valuedouble,WindSpeed->valueint,WorkMode->valueint);

					debug_log(LOG_EMERG_LEVEL,"mark!!!\n");
				}
				kk_create_new_central_ac(gwDeviceCode->valuestring,deviceCode->valuestring,nodeid);
			}
		}
	}
	cJSON_AddItemToObject(root, "central_ac_gws", central_ac_gws);
	return root;
}

//同步空调网关内机
typedef struct{
	char id[AIR_AC_INDOOR_ID_SIZE];
	char room_id[AIR_AC_INDOOR_ROOM_ID_SIZE];
	char indoorunit_name[AIR_AC_INDOOR_NAME_SIZE];
	char indooruint_addr[AIR_AC_INDOOR_ADDR_SIZE];
	char central_ac_gw_devid[AIR_AC_INDOOR_ID_SIZE];
	cJSON * indoorunit_state;
}SYN_CENTRAL_AC_INDOOR;
cJSON *_kk_sync_central_ac_indoorunit_to_sdk(SYN_CENTRAL_AC_INDOOR* indoorunit)
{
	cJSON *item = cJSON_CreateObject();
	cJSON *status;

	cJSON_AddStringToObject(item, "id",(indoorunit->id)?indoorunit->id:"");
	cJSON_AddStringToObject(item, "room_id", (indoorunit->room_id)?indoorunit->room_id:"");
	cJSON_AddStringToObject(item, "indoorunit_name", (indoorunit->indoorunit_name)?indoorunit->indoorunit_name:"");
	cJSON_AddStringToObject(item, "indooruint_addr", (indoorunit->indooruint_addr)?indoorunit->indooruint_addr:"");
	cJSON_AddStringToObject(item, "central_ac_gw_devid", (indoorunit->central_ac_gw_devid)?indoorunit->central_ac_gw_devid:"");

	cJSON_AddItemToObject(item, "indoorunit_state",(indoorunit->indoorunit_state)?indoorunit->indoorunit_state:cJSON_CreateNull());
	return item;
}
cJSON *_kk_sync_central_ac_indoorunits(int num,SYN_CENTRAL_AC_INDOOR *indoorunits)
{
	int i;
	cJSON *central_ac_indoorunits = cJSON_CreateArray();
	SYN_CENTRAL_AC_INDOOR *pIndoorunit = indoorunits;
	
	for(i=0;i<num;i++,pIndoorunit++) {
	
		cJSON *item =_kk_sync_central_ac_indoorunit_to_sdk(pIndoorunit);
	
		cJSON_AddItemToArray(central_ac_indoorunits,item);
	}

	return central_ac_indoorunits;
}



cJSON *kk_sync_central_ac_indoorunits_to_sdk(cJSON *root,cJSON *data)
{
	int i = 0;

	cJSON *central_ac_indoorunits;
	central_ac_indoorunits = cJSON_CreateArray();
	
	SYN_CENTRAL_AC_INDOOR *indoorunitAry = NULL;
	SYN_CENTRAL_AC_INDOOR *pIndoorunit = NULL;

	indoorunitAry = (SYN_CENTRAL_AC_INDOOR *)malloc(g_indoor_count*sizeof(SYN_CENTRAL_AC_INDOOR));
	memset(indoorunitAry,0,g_indoor_count*sizeof(SYN_CENTRAL_AC_INDOOR));
	pIndoorunit = indoorunitAry;

	for(i=0;i<g_indoor_count;i++,pIndoorunit++){

		snprintf(pIndoorunit->id,AIR_AC_INDOOR_ID_SIZE,"%s",g_indoor_item[i].id);
		snprintf(pIndoorunit->room_id,AIR_AC_INDOOR_ROOM_ID_SIZE,"%s",g_indoor_item[i].room_id);
		snprintf(pIndoorunit->indoorunit_name,AIR_AC_INDOOR_NAME_SIZE,"%s",g_indoor_item[i].dev_name);
		snprintf(pIndoorunit->central_ac_gw_devid,AIR_AC_INDOOR_ID_SIZE,"%s",g_indoor_item[i].nodeid);
		snprintf(pIndoorunit->indooruint_addr,AIR_AC_INDOOR_ADDR_SIZE,"%s",g_indoor_item[i].indooruint_addr);

		cJSON *status = cJSON_CreateObject();
		cJSON_AddBoolToObject(status,"online",g_indoor_item[i].ac_gw_status.online);
		cJSON_AddBoolToObject(status,"on",g_indoor_item[i].ac_gw_status.on);
		cJSON_AddStringToObject(status,"runModel",g_indoor_item[i].ac_gw_status.mode);
		cJSON_AddStringToObject(status,"fanSpeed",g_indoor_item[i].ac_gw_status.speed);
		cJSON_AddNumberToObject(status,"settingTemperature",g_indoor_item[i].ac_gw_status.settingTemperature);
		cJSON_AddNumberToObject(status,"roomTemperature",g_indoor_item[i].ac_gw_status.roomTemperature);

		pIndoorunit->indoorunit_state = status;
	}
	
	central_ac_indoorunits = _kk_sync_central_ac_indoorunits(g_indoor_count,indoorunitAry);
	debug_log(LOG_ALERT_LEVEL,"mark...\n");
	cJSON_AddItemToObject(root, "central_ac_indoorunits", central_ac_indoorunits);	  

	return root;
}

//同步组
typedef struct{
	char *id;
	char *name;
	cJSON * nodes;
}SYN_GROUP;

cJSON *_kk_sync_group_nodes(int num,char* list[])
{
	int i;
	cJSON *nodesAry = cJSON_CreateArray();

	for(i=0;i<num;i++){
		cJSON *item = cJSON_CreateObject();
		cJSON_AddStringToObject(item, "nodeid", (list[i])?list[i]:"");
		cJSON_AddItemToArray(nodesAry,item);
	}
	return nodesAry;
}

cJSON *_kk_sync_group_to_sdk(SYN_GROUP *group)
{
	cJSON *item = cJSON_CreateObject();
	
	cJSON_AddStringToObject(item, "id", (group->id)?group->id:"");
	cJSON_AddStringToObject(item, "name", (group->name)?group->name:"");
	cJSON_AddItemToObject(item, "nodes", group->nodes?group->nodes:cJSON_CreateNull());
	return item;
}

cJSON *_kk_sync_groups(int num,SYN_GROUP *group)
{
	int i;
	cJSON *groups = cJSON_CreateArray();
	SYN_GROUP *pGrp = group;
	for(i=0;i<num;i++,pGrp++){
		cJSON *item = _kk_sync_group_to_sdk(pGrp);
		cJSON_AddItemToArray(groups,item);
	}
	return groups;
}

cJSON *kk_sync_groups_to_sdk(cJSON *root,cJSON *data)
{

	cJSON *groups = NULL;

	SYN_GROUP grp;

	grp.id = malloc(20);
	memset(grp.id,0,20);
	memcpy(grp.id,"1",sizeof("1"));

	grp.name = malloc(20);
	memset(grp.name,0,20);
	memcpy(grp.name,"2",sizeof("2"));


	char *list[2];
	list[0] = malloc(20);
	memset(list[0],0,20);
	memcpy(list[0],"x",sizeof("x"));

	list[1] = malloc(20);
	memset(list[1],0,20);
	memcpy(list[1],"y",sizeof("y"));

	grp.nodes=_kk_sync_group_nodes(2,list);
	groups = _kk_sync_groups(1,&grp);


	cJSON_AddItemToObject(root, "group", groups);
	return root;
}

//楼层信息
typedef struct{
	char *floor_icon;
	char *floor_2_bg;
	char * floor_pos;
	char * id;
	char *name;
}SYN_FLOOR;

static cJSON * kk_create_floor_obj(SYN_FLOOR *floor)
{
	cJSON *item = cJSON_CreateObject();
	
	cJSON_AddStringToObject(item, "floor_icon", (floor->floor_icon)?floor->floor_icon:"");
	cJSON_AddStringToObject(item, "floor_2_bg", (floor->floor_2_bg)?floor->floor_2_bg:"");
	cJSON_AddStringToObject(item, "floor_pos", (floor->floor_pos)?floor->floor_pos:"");
	cJSON_AddStringToObject(item, "id", (floor->id)?floor->id:"");
	cJSON_AddStringToObject(item, "name", (floor->name)?floor->name:"");

	return item;

}

static cJSON * kk_create_floors(int num ,SYN_FLOOR *floor)
{
	int i;
	cJSON *floors = cJSON_CreateArray();
	SYN_FLOOR * pFlr = floor;
	for(i=0;i<num;i++,pFlr++){
		 cJSON * item = kk_create_floor_obj(pFlr);
		cJSON_AddItemToArray(floors,item);
	}
	
	return floors;
}

static int kk_create_floors_to_sdk(cJSON *root,cJSON *data)
{
	cJSON *floors = NULL;

	SYN_FLOOR flr;
	memset(&flr,0,sizeof(SYN_FLOOR));
	flr.floor_2_bg = malloc(20);
	memset(flr.floor_2_bg,0,20);
	memcpy(flr.floor_2_bg,"1",sizeof("1"));
	
	
	flr.floor_icon= malloc(20);
	memset(flr.floor_icon,0,20);
	memcpy(flr.floor_icon,"2",sizeof("2"));
	
	flr.floor_pos= malloc(20);
	memset(flr.floor_pos,0,20);
	memcpy(flr.floor_pos,"3",sizeof("3"));
	flr.id= malloc(20);
	memset(flr.id,0,20);
	memcpy(flr.id,"4",sizeof("4"));
	flr.name= malloc(20);
	memset(flr.name,0,20);
	memcpy(flr.name,"一楼",sizeof("一楼"));

	floors = kk_create_floors(1,&flr);
	
	cJSON_AddItemToObject(root, "floors", floors);
	return 0;
}


//同步数据
int kk_create_syncinfo_to_sdk(cJSON *payload,int push)
{
	cJSON *air_box_devices;
	cJSON *alarms;
	cJSON *ccu_link_status;
	cJSON *link_arg;

	cJSON *cnwise_music_controllers;
	cJSON *code_lib_controllers;
	cJSON *controllers;
	cJSON *expand_rules;
	cJSON *data = kk_get_sync_data(payload);



	cJSON *root=cJSON_CreateObject();
	cJSON *aiks_controllers = cJSON_CreateArray();
	cJSON_AddItemToObject(root, "aiks_controllers", aiks_controllers);
	air_box_devices = cJSON_CreateArray();
	cJSON_AddItemToObject(root, "air_box_devices", air_box_devices);
	alarms = cJSON_CreateArray();
	cJSON_AddItemToObject(root, "alarms", alarms); 
	cJSON *shortcut_panel_configs=cJSON_CreateArray();
	cJSON_AddItemToObject(root, "shortcut_panel_configs", shortcut_panel_configs);
	ccu_link_status = cJSON_CreateObject(); 
	link_arg = cJSON_CreateObject(); 
	cJSON_AddItemToObject(ccu_link_status, "link_arg", link_arg);
	cJSON_AddStringToObject(ccu_link_status, "link_type", "broadband_net");
	cJSON_AddItemToObject(root, "ccu_link_status", ccu_link_status);
	cnwise_music_controllers = cJSON_CreateArray();
	cJSON_AddItemToObject(root, "cnwise_music_controllers", cnwise_music_controllers);       
	code_lib_controllers = cJSON_CreateArray();
	cJSON_AddItemToObject(root, "code_lib_controllers", code_lib_controllers);     


	controllers = cJSON_CreateArray();
	cJSON_AddItemToObject(root, "controllers", controllers);  
	




	

	kk_sync_devices_status_to_sdk(root);



	kk_sync_devices_to_sdk(root,data);




	kk_sync_rooms_to_sdk(root,data);


	kk_sync_scence_to_sdk(root,data);


	kk_sync_gw_version_to_sdk(root,data);

	kk_sync_ccu_version_to_sdk(root,data);



	kk_sync_guard_to_sdk(root,data);

	kk_sync_central_ac_to_sdk(root,data);


	kk_sync_central_ac_indoorunits_to_sdk(root,data);


	kk_sync_groups_to_sdk(root,data);


	kk_create_floors_to_sdk(root,data);


	#if 1 

	expand_rules = cJSON_CreateArray();

	cJSON_AddItemToObject(root, "expand_rules", expand_rules);

	


	#endif



	char *out=cJSON_Print(root);
	printf("out:%s\n",out);
	
	cJSON *msg = NULL;

	if(push==1){
		msg = old_ccu_msg_build_json("*","SYNC_INFO_PUSH",NULL,root);
	}else{
		msg = old_ccu_msg_build_json("*","SYNC_INFO",NULL,root);
	}
	
	send_msg_to_module(msg);
	cJSON_Delete(msg);
	free(out);
	if(g_indoor_count > 0){
		sleep(1);
		kk_new_device_send();
	}
	return 0;
}














