/*
 * EH_FindCCU.cpp
 *
 *  Created on: 2020年10月9日
 *      Author: hj
 */


#include "EH_FindCCU.h"
#include "../lib/EH_DEBUG.h"

#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>

#include "LSC_Logger.h"

#include "../KK_HwDevManager.h"
#include "../lib/EH_SDKDef.h"
#include "../MQ_CCU_Adapter.h"
#include "EH_ToolKit.h"

EH_FindCCU::EH_FindCCU() {
	destroyed = false;
}

// int EH_FindCCU::init(string ccuId, EH_FindCCUCallBackHandler* cb,string LocalIP) {
int EH_FindCCU::init(string ccuId,string LocalIP) {
	this->ccuId = ccuId;
	// this->cb = cb;
	this->ccuLocalIP = LocalIP;
	ccuSn = EH_ToolKit::GetMacNoSpace();
	LOGD("socket init.\n");

	searchCcuFd = -1;
	if ((searchCcuFd = socket(AF_INET, SOCK_DGRAM, 0)) == -1) {
		cout << "socket error" << endl;
		return -1;
	}

	const int opt = 1;
	//璁剧疆璇ュ��ュ��涓哄箍��绫诲��锛�
	int nb = 0;
	nb = setsockopt(searchCcuFd, SOL_SOCKET, SO_BROADCAST, (char *) &opt, sizeof(opt));
	if (nb == -1) {
		cout << "set socket error..." << endl;
		close(searchCcuFd);
		return -1;
	}

	timeval tv = {10, 0};
	nb = setsockopt(searchCcuFd, SOL_SOCKET, SO_RCVTIMEO, (char*)&tv, sizeof(timeval));
	if (nb == -1) {
		cout << "setsockopt failed" << endl;
		close(searchCcuFd);
		return -1;
	}

	pthread_t tid;
	pthread_create(&tid, NULL, run0, this);
	LOGD("find ccu init OK.\n");

	return 0;
}

void EH_FindCCU::destroy() {
	destroyed = true;
}

void* EH_FindCCU::run0(void* opt) {
	EH_FindCCU* findCcu = (EH_FindCCU*)opt;
	return findCcu->run(opt);
}

void* EH_FindCCU::run(void* opt) {
	while(true) {
		sendFindCCUMsg();
		sleep(2);
		}

	delete this;
	return NULL;
}


//UDP 广播
void EH_FindCCU::sendFindCCUMsg() {
	string findMsg = "";
	EH::Json::Value arg;
//	arg["ip"] = ccuLocalIP;
#ifdef NOT_X86
	arg["ip"]  = string(EH_ToolKit::GetLocalIP("eth1"));
#else
	arg["ip"]  = string(EH_ToolKit::GetLocalIP()); 
	// arg["ip"]  = string("127.0.0.1"); 
#endif
	arg["proto"] = "zigbee";//网关类型
	arg["ccu_id"] = ccuId;
	arg["kk_version"] = MQ_VERSION;
	arg["gw_id"] = ccuSn;//网关id，采用mac地址
	arg["gw_model_id"] = "KK-CC-H31"; //设备类型 //控客的
	arg["version"] = "1.2";
	arg["state"] = KK_HwDevManager::GetInstance()->GetConnectState();//要改成动态的获取
	findMsg =  EH_ToolKit::JsonToString(arg);

	struct sockaddr_in addrto;
	memset (&addrto, 0, sizeof(struct sockaddr_in));
	addrto.sin_family = AF_INET;
	addrto.sin_addr.s_addr = inet_addr("255.255.255.255");
	addrto.sin_port = htons(6767); //兴海定的端口号
	int nlen = sizeof(addrto);

	if (sendto(searchCcuFd, findMsg.c_str(), strlen(findMsg.c_str()), 0, (sockaddr*) &addrto, nlen) > 0) {
		LOGD("Send search ccu msg ok.%s.\n",findMsg.c_str());   //临时注释，避免日志过多。2020.10.14
	} else {
		LOGW("Send search ccu msg failed.error:%s.\n",strerror(errno));

	}
}

EH_FindCCU::~EH_FindCCU() {
	close(searchCcuFd);
	LOGD("~EH_FindCCU:%s.\n",ccuId.c_str());
}


