/*******************************************************************************
 * Copyright (c) 2012, 2020 IBM Corp.
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v2.0
 * and Eclipse Distribution License v1.0 which accompany this distribution.
 *
 * The Eclipse Public License is available at
 *   https://www.eclipse.org/legal/epl-2.0/
 * and the Eclipse Distribution License is available at
 *   http://www.eclipse.org/org/documents/edl-v10.php.
 *
 * Contributors:
 *    Ian Craggs - initial contribution
 *******************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include "MQTTAsync.h"
#include "mqtt_api.h"
#include "com_api.h"
#include "kk_product.h"
//#include "kcloud_log.h"
static char s_ccuid[DEVICE_CODE_LEN] = {0};
int KK_Get_ccuid(_OU_ char *device_code)
{    
    strncpy(device_code, s_ccuid, strlen(s_ccuid));
    printf("HAL_Get_ccuid:%s\n",s_ccuid);
    return strlen(s_ccuid);
}
static int _setDevice_Code(_IN_ char *device_code,int len)
{
    memset(s_ccuid, 0x0, DEVICE_CODE_LEN);
    printf("_setDevice_Code:%s\n",device_code);
    strncpy(s_ccuid, device_code, len);
    return len;
}
static void KK_Ccuid_init(void)
{
    uint8_t ccuid[DEVICE_CODE_LEN] = {0};
    int ccuid_len = 0;
    HAL_Execel_cmd(GET_CCUID_CMD,(char *)ccuid,sizeof(ccuid),&ccuid_len);
    printf("GET_CCUID_CMD:%s\n",ccuid);
    if(ccuid_len > 0 && ccuid_len <= DEVICE_CODE_LEN){
        _setDevice_Code(ccuid,ccuid_len-1);
    }else{
        _setDevice_Code(KK_CCU_ID,strlen(KK_CCU_ID));
    }
}
static int mqtt_start(void)
{
	int count = 0;
	MQTTAsync mqttClient;
	int rc = 0;
	mqttClient = KK_MQTT_Connect();
	if(mqttClient == NULL)
	{
		WARNING_PRINT("KK_MQTT_Connect FAIL!!!\n");
	}
	while(1)
	{
		usleep(100000L);
		if(kk_get_cloud_status() == 0){
			//printf("------------------------------>count:%d\n",count);
			count++;
			if(count>500)
			{
				count = 0;
				WARNING_PRINT("---------------------------------->CONNECT FAIL!!!\n");
				break;
				//INFO_PRINT("i am send now\n");
				//KK_MQTT_SendMsg(TOPIC,"hello my world",2);
			}
		}else{
			if(count > 0){
				count = 0;
			}
		}
		//INFO_PRINT(" %s \n",testStr);

	}
	INFO_PRINT("MQTTAsync_destroy\n");
	MQTTAsync_destroy(&mqttClient);
	return -1;

}
int kk_start_ccu_register(void);
extern int kk_info_report_start(void);
int main(int argc, char* argv[])
{
	int rc = 0;
	open("kcloud",LOG_PID,LOG_USER);
	/*set the callback to get the device date to cloud*/
	KK_Ccuid_init();
	kk_ipc_init(IPC_APP2MID,(ipc_cb*)KK_Data_FromDev,NULL,NULL);
	//kk_info_report_start();
again:	
	rc = kk_start_ccu_register();
	if(rc == 0){
		rc = mqtt_start();
		if(rc < 0){
			sleep(2);
			goto again;	
		}
	}else{
		sleep(2);
		goto again;
	}
	return rc;
}

