#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 : wMAsyncWorker1         -----------------------------*/
	wMAsyncWorker1 = new STTAsyncWorker(p_rt, this, "wMAsyncWorker1");
	wMAsyncWorker1->setPeriod(1000);
	wMAsyncWorker1->onActionHandler(this, (EHandler) &Wcmn::wMAsyncWorker1_ref_cb);
	wMAsyncWorker1->start();

	/*called after widget created.*/

	return; //createParts END
}

void Wcmn::onLoad() {

}

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

void Wcmn::onDispose() {

}
static UA_Server *g_server = NULL;
static UA_Boolean g_running = true;
static pthread_t opcua_thread;
void* opcuaServerThread(void* arg)
{
    g_server = UA_Server_new();

    UA_ServerConfig *config = UA_Server_getConfig(g_server);
    UA_ServerConfig_setDefault(config);

    /* 创建变量 */
    UA_VariableAttributes attr = UA_VariableAttributes_default;

    UA_Double initValue = 25.0;
    UA_Variant_setScalar(&attr.value, &initValue, &UA_TYPES[UA_TYPES_DOUBLE]);

    attr.displayName = UA_LOCALIZEDTEXT((char*)"en-US",(char*)"Temperature");
    attr.dataType = UA_TYPES[UA_TYPES_DOUBLE].typeId;
    attr.accessLevel = UA_ACCESSLEVELMASK_READ | UA_ACCESSLEVELMASK_WRITE;

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

    UA_Server_addVariableNode(
        g_server,
        nodeId,
        UA_NODEID_NUMERIC(0,UA_NS0ID_OBJECTSFOLDER),
        UA_NODEID_NUMERIC(0,UA_NS0ID_ORGANIZES),
        name,
        UA_NODEID_NUMERIC(0,UA_NS0ID_BASEDATAVARIABLETYPE),
        attr,
        NULL,
        NULL
    );

    printf("OPC UA Server started\n");

    UA_StatusCode ret = UA_Server_run(g_server,&g_running);

    UA_Server_delete(g_server);

    return NULL;
}
void startOpcuaServer()
{
    pthread_create(&opcua_thread,NULL,opcuaServerThread,NULL);
}
void Wcmn::wMAsyncWorker1_ref_cb(uint16_t code, LvEvent e) {
    static bool init=false;

    if(!init)
    {
        startOpcuaServer();
        init=true;
    }

}
