#include "Wcmn.h"
#include <open62541.h>
#include <signal.h>
#include <stdlib.h>
Wcmn::Wcmn(HmiApp* app, STTWidget *par, const string& id, const string& desc) : STTPage(app->getRuntime(), par, id, desc) {
	hmiApp = app;
}

Wcmn::~Wcmn() {
}

void Wcmn::onInit() {

}

void Wcmn::createParts() {
	setMainArg(0, 0, 1024, 600);
	setMainStyle(0, 0xffffff, 0xffffff, 0, 255, 0, 0xc0c0c0);

	/*----------------------------- AsyncWorker : wMAsyncWorker2         -----------------------------*/
	wMAsyncWorker2 = new STTAsyncWorker(p_rt, this, "wMAsyncWorker2");
	wMAsyncWorker2->setPeriod(1000);
	wMAsyncWorker2->onActionHandler(this, (EHandler) &Wcmn::wMAsyncWorker2_ref_cb);
	wMAsyncWorker2->start();

	/*called after widget created.*/

	return; //createParts END
}

void Wcmn::onLoad() {

}

bool Wcmn::onClosing() {
	return true;
}

void Wcmn::onDispose() {

}

static UA_Client *g_client = NULL;
static bool opc_connected = false;
void initOpcClient()
{
    g_client = UA_Client_new();
    UA_ClientConfig_setDefault(UA_Client_getConfig(g_client));

    UA_StatusCode retval =
        UA_Client_connect(g_client, "opc.tcp://127.0.0.1:4840");

    if(retval != UA_STATUSCODE_GOOD)
    {
        printf("OPCUA connect failed %d\n", (int)retval);
        UA_Client_delete(g_client);
        g_client = NULL;
        opc_connected = false;
        return;
    }

    printf("OPCUA connected\n");
    opc_connected = true;
}

void readOpcTemperature()
{
    if(!opc_connected || !g_client)
        return;

    UA_Variant value;
    UA_Variant_init(&value);

    UA_NodeId nodeId = UA_NODEID_STRING(1,(char*)"Temperature");

    UA_StatusCode retval =
        UA_Client_readValueAttribute(g_client, nodeId, &value);

    if(retval == UA_STATUSCODE_GOOD && UA_Variant_hasScalarType(&value,&UA_TYPES[UA_TYPES_DOUBLE]))
    {
        UA_Double temp = *(UA_Double*)value.data;

        printf("Temperature = %f\n", temp);
        fflush(stdout);
        // 可以写入你的 HMI 变量
        // vm->setDouble("温度", temp);
    }

    UA_Variant_clear(&value);
}

void Wcmn::writeOpcTemperature(){
	UA_Variant value;
	UA_Variant_init(&value);

	float f;
	vm->getFloat("温度",f);
	UA_Double newTemp = (double)f;

	UA_Variant_setScalar(&value,&newTemp,&UA_TYPES[UA_TYPES_DOUBLE]);

	UA_StatusCode retval =
	    UA_Client_writeValueAttribute(
	    		g_client,
	        UA_NODEID_STRING(1,(char*)"Temperature"),
	        &value
	    );

	printf("write ret = %d\n",retval);
}

void Wcmn::wMAsyncWorker2_ref_cb(uint16_t code, LvEvent e) {
    if(!opc_connected)
    {
        initOpcClient();
        return;
    }

    readOpcTemperature();

    if (hmiApp->isWrite){
    	writeOpcTemperature();
    	hmiApp->isWrite = !hmiApp->isWrite;
    }
}
