/**
* @file:    $RCSfile: datahub.cpp,v $
* @brief:   $aliyun datahub include
*
* @version: $Revision: 1.00 $
* @date:    $Date: 2023/10/10 18:34:00 $
* @author:  $Author: wangwei $
* @state:   $State: Exp $
*
* @latest:  $Id: datahub.cpp,v 1.00 2023/10/10 18:34:00 wangwei Exp $
*
*/

using namespace std;

#include <stdio.h>
#include <stdlib.h>
#include <string>
#include "../mms/db_interface.h"
#include "../json/cjson.h"//WW 2023-08-27新增json解析函数
#include "../include/curl/curl.h" 

#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */


size_t req_reply_datahub(void* ptr, size_t size, size_t nmemb, void* stream)
{
	string* str = (string*)stream;
	(*str).append((char*)ptr, size * nmemb);
	return size * nmemb;
}

void SendWebAPI_Datahub(const string strUrl,char* topic,char* data)
{

	// curl初始化  
	CURL* curl = curl_easy_init();

	// curl返回值 
	CURLcode res;
	if (curl)
	{
		//设置curl的请求头
		struct curl_slist* header_list = NULL;
		header_list = curl_slist_append(header_list, "Content-Type:application/json;");

		curl_easy_setopt(curl, CURLOPT_HTTPHEADER, header_list);

		//不接收响应头数据0代表不接收 1代表接收
		curl_easy_setopt(curl, CURLOPT_HEADER, 0);

		//设置请求为post请求
		curl_easy_setopt(curl, CURLOPT_POST, 1);

		//设置请求的URL地址
		curl_easy_setopt(curl, CURLOPT_URL, strUrl.c_str());

		//设置post请求的参数
		cJSON* json_root = cJSON_CreateObject();

		cJSON_AddItemToObject(json_root, "topic", cJSON_CreateString(topic));
		cJSON_AddItemToObject(json_root, "data", cJSON_CreateString(data));

		char* szjson = cJSON_Print(json_root);

		curl_easy_setopt(curl, CURLOPT_POSTFIELDS, szjson);

		//设置ssl验证
		curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, false);
		curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, false);

		//CURLOPT_VERBOSE的值为1时，会显示详细的调试信息
		curl_easy_setopt(curl, CURLOPT_VERBOSE, 0);

		curl_easy_setopt(curl, CURLOPT_READFUNCTION, NULL);

		//设置数据接收和写入函数
		curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, req_reply_datahub);

		string resPost0;
		curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void*)&resPost0);

		curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);

		//设置超时时间
		curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 10);
		curl_easy_setopt(curl, CURLOPT_TIMEOUT, 10);

		printf(">>>Testaliyun datahub Post in curl post\n");

		// 开启post请求
		res = curl_easy_perform(curl);

		// 检查请求是否成功
		if (res != CURLE_OK) {
			printf("aliyun datahub failed res code: ");
		}
		else {
			printf("aliyun datahub success,string %s", resPost0.c_str());
			//后期添加webapi返回值判断
		}

		curl_slist_free_all(header_list);
		free(szjson);
		cJSON_Delete(json_root);
	}
	else
	{
		printf(">>> token curl init failed");
	}
	curl_easy_cleanup(curl);
}

void DataHub_Send_Datahub(char* topic,char* data)
{
	SendWebAPI_Datahub("http://127.0.0.1:8091/powerQuality/PQDATAHUB",topic,data);
}

#ifdef __cplusplus
}
#endif
