EI-Agent Sample Client

From ESS-WIKI
Revision as of 08:15, 18 May 2017 by Scott68.chang (talk | contribs) (add core_action_response)
Jump to: navigation, search

Advantech provides a WISE-PaaS 2.0 EI-Agent Sample to demonstrate how to implement a custom application to connect to WISE-PaaS 2.0 Server.

WISECore APIs

List

bool core_initialize(char* strTenantID, char* strClientID, char* strHostName, char* strMAC, void* userdata);
Description
  • General initialization of the WISECore API. Prior to calling any WISECore API functions, the library needs to be initialized by calling this function.
  • The result for all WISECore API function will be false unless this function is called.

Parameters

  • strTenantID[POINTER]
    • the tenant ID string in UUID format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.
  • strClientID[POINTER]
    • the client ID string in UUID format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.
  • strHostName[POINTER]
    • the host name string as device recognize name.
  • strMAC[POINTER]
    • first MAC address of the device.
  • userdata[POINTER]
    • the unstructured pointer to reference to user data.

Return Values

  • true/false

Example

Reference to core_account_bind().



void core_uninitialize();
Description
  • General function to uninitialize the WISECore API library that should be called before program exit.

Parameters

  • None

Return Values

  • None

Example

Reference to core_account_bind().



bool core_product_info_set(char* strSerialNum, char* strParentID, char* strVersion, char* strType, char* strProduct, char* strManufacture);
Description
  • Assign the basic information to identify the device.

Parameters

  • strSerialNum[POINTER]
    • the serial number string of target device.
  • strParentID[POINTER]
    • the parent device ID string in UUID format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx, used to point out the EIS or Gateway device ID if the taget device connect to server through an EIS or Gateway device.
  • strVersion[POINTER]
    • the applicatin version string.
  • strType[POINTER]
    • the applicatin type string, default is "IPC" for general usage.
  • strProduct[POINTER]
    • the target device product name.
  • strManufacture[POINTER]
    • the target device manufacture name.

Return Values

  • true/false

Example

Reference to core_account_bind().



bool core_tag_set(char* strTag);
Description
  • Assign the tag to markup the support product, for example: "RMM" for RMM product.

Parameters

  • strManufacture[POINTER]
    • the target device supported function set.

Return Values

  • true/false

Example

Reference to core_account_bind().



bool core_account_bind(char* strLoginID, char* strLoginPW);
Description
  • Bind the device to a specific user account automatically.

Parameters

  • strLoginID[POINTER]
    • Account ID.
  • strLoginPW[POINTER]
    • Account Password, need to encrypt with AgentEncrypt application.

Return Values

  • true/false.

Example

#include "WISECore.h"
 
int main (int argc, char *argv[])
{
    int iRet = 0;
    /*Initialize WISECore*/
    if(!core_initialize("general", "00000001-0000-0000-0000-305A3A77B1CC", "TestClient", "305A3A77B1CC", NULL))
    {
        printf("Unable to initialize WISECore.\n");
        goto EXIT;
    }
    printf("Agent Initialized\n");
    /*Setup device identify information*/
    core_product_info_set("305A3A77B1CC", NULL/*no parent ID*/, "2.0.1", "IPC", "test", "test"); 
    /*Setup support function tag*/
    core_tag_set("RMM");
    /*binding to a specific account*/
    core_account_bind("admin","GP25qY7TjJA=");
EXIT:
    /*Release WISECore*/
    core_uninitialize();
    return iRet;
}


bool core_tls_set(const char *cafile, const char *capath, const char *certfile, const char *keyfile, const char *password);
Description
  • Configure the client for certificate based SSL/TLS support. Must be called before <core_connect>.
  • Cannot be used in conjunction with <core_tls_psk_set>.
  • Define the Certificate Authority certificates to be trusted (ie. the server certificate must be signed with one of these certificates) using cafile. If the server you are connecting to requires clients to provide a certificate, define certfile and keyfile with your client certificate and private key. If your private key is encrypted, provide a password callback function.

Parameters

  • cafile[POINTER]
    • path to a file containing the PEM encoded trusted CA certificate files.
    • Either cafile or capath must not be NULL.
  • capath[NUMBER]
    • path to a directory containing the PEM encoded trusted CA certificate files. See mosquitto.conf for more details on configuring this directory.
    • Either cafile or capath must not be NULL.
  • certfile[POINTER]
    • path to a file containing the PEM encoded certificate file for this client.
    • If NULL, keyfile must also be NULL and no client certificate will be used.
  • keyfile[POINTER]
    • path to a file containing the PEM encoded private key for this client.
    • If NULL, certfile must also be NULL and no client certificate will be used.
  • password[POINTER]
    • if keyfile is encrypted, set the password to allow your client to pass the correct password for decryption.
    • need to encrypt with AgentEncrypt application.

Return Values

  • true/false

Example

#include "WISECore.h"
int main (int argc, char *argv[]) 
{
    int iRet = 0; /*Initialize WISECore*/ if(!core_initialize("general", "00000001-0000-0000-0000-305A3A77B1CC", "TestClient", "305A3A77B1CC", NULL))
    {
        printf("Unable to initialize WISECore.\n");
        goto EXIT;
    }
    printf("Agent Initialized\n");
    /*Setup TLS*/
    core_tls_set( "server.crt", NULL, "ca.crt", "ca.key", "123456");
    /*Connect to Server*/
    core_connect("127.0.0.1",1883,"admin","123456");

    /*Disconnect*/
    core_disconnect(false);

EXIT:
    /*Release WISECore*/
    core_uninitialize();
    return iRet; 
}


bool core_tls_psk_set(const char *psk, const char *identity, const char *ciphers); 
Description
  • Configure the client for pre-shared-key based TLS support. Must be called before <wc_connect>.
  • Cannot be used in conjunction with <core_tls_set>.

Parameters

  • psk [POINTER]
    • the pre-shared-key in hex format with no leading "0x".
  • identity[POINTER]
    • the identity of this client. May be used as the username depending on the server settings.
  • ciphers[POINTER]
    • a string describing the PSK ciphers available for use. See the "openssl ciphers" tool for more information.
    • If NULL, the default ciphers will be used.

Return Values

  • true/false

Example

#include "WISECore.h"
int main (int argc, char *argv[]) 
{
    int iRet = 0; /*Initialize WISECore*/ if(!core_initialize("general", "00000001-0000-0000-0000-305A3A77B1CC", "TestClient", "305A3A77B1CC", NULL))
    {
        printf("Unable to initialize WISECore.\n");
        goto EXIT;
    }
    printf("Agent Initialized\n");
    /*Setup PSK*/
    core_tls_psk_set("05155853", "00000001-0000-0000-0000-305A3A77B1CC", NULL);
    /*Connect to Server*/
    core_connect("127.0.0.1",1883,"admin","123456");

    /*Disconnect*/
    core_disconnect(false);

EXIT:
    /*Release WISECore*/
    core_uninitialize();
    return iRet; 
}


bool core_connect(char* strServerIP, int iServerPort, char* strConnID, char* strConnPW);
Description
  • Connect to server that defined in Configuration data of lite_initialize parameters.

Parameters

  • strServerIP[POINTER]
    • remote server URL or IP address.
  • iServerPort[NUMBER]
    • connection protocol listen port.
  • strConnID[POINTER]
    • connection protocol access id
  • strConnPW[POINTER]
    • connection protocol access password

Return Values

  • true/false

Example

Reference to core_tls_set().



void core_disconnect(bool bForce);
Description
  • Disconnect from server.

Parameters

  • bForce[BOOLEAN]
    • Is force to disconnect.

Return Values

  • None

Example

Reference to core_tls_set().



bool core_connection_callback_set(CORE_CONNECTED_CALLBACK on_connect, CORE_LOSTCONNECTED_CALLBACK on_lostconnect, CORE_DISCONNECT_CALLBACK on_disconnect, CORE_MESSAGE_RECV_CALLBACK on_msg_recv);
Description
  • Register the callback function to handle the connection event.

Parameters

  • on_connect[POINTER]
    • Function Pointer to handle connect success event.
  • on_lost_connect[POINTER]
    • Function Pointer to handle lost connect event.
    • The SAClient will reconnect automatically, if left as NULL.
  • on_disconnect[POINTER]
    • Function Pointer to handle disconnect event.
  • on_msg_recv[POINTER]
    • Function Pointer to handle message receive event.

Return Values

  • true/false

Example

#include "WISECore.h"
void on_connect_cb(void* userdata)
{
    printf("CB_Connected \n");
}

void on_lostconnect_cb(void* userdata)
{
    printf("CB_Lostconnect %s\n", core_error_string_get());
}

void on_disconnect_cb(void* userdata)
{
    printf("CB_Disconnect \n");
}

void on_msgrecv(const char* topic, const void *pkt, const long pktlength, void* userdata)
{
    printf("Packet received:\n [%s],\n %s\n", topic, pkt);
}

int main (int argc, char *argv[]) 
{
    int iRet = 0; /*Initialize WISECore*/ if(!core_initialize("general", "00000001-0000-0000-0000-305A3A77B1CC", "TestClient", "305A3A77B1CC", NULL))
    {
        printf("Unable to initialize WISECore.\n");
        goto EXIT;
    }
    printf("Agent Initialized\n");
    /*Setup connection callback function*/
    core_connection_callback_set(on_connect_cb, on_lostconnect_cb, on_disconnect_cb, on_msgrecv);

    /*Connect to Server*/
    core_connect("127.0.0.1",1883,"admin","123456");

    /*Disconnect*/
    core_disconnect(false);

EXIT:
    /*Release WISECore*/
    core_uninitialize();
    return iRet; 
}


bool core_action_callback_set(CORE_RENAME_CALLBACK on_rename, CORE_UPDATE_CALLBACK on_update);
Description
  • Register the callback function to handle the action event.

Parameters

  • on_rename[POINTER]
    • Function Pointer to handle rename event.
  • on_update[POINTER]
    • Function Pointer to handle update event.

Return Values

  • true/false

Example

#include "WISECore.h"
void on_rename(const char* name, const int cmdid, const char* sessionid, const char* tenantid, const char* devid, void* userdata)
{
    printf("rename to: %s\n", name);
    /*Send action response*/
    core_action_response(cmdid, sessionid, true, tenantid, devid);
    return;
}

void on_update(const char* loginID, const char* loginPW, const int port, const char* path, const char* md5, const int cmdid, const char* sessionid, const char* tenantid, const char* devid, void* userdata)
{
    printf("Update: %s, %s, %d, %s, %s\n", loginID, loginPW, port, path, md5);
    /*Send action response*/
    core_action_response(cmdid, sessionid, true, tenantid, devid);
    return;
}

int main (int argc, char *argv[]) 
{
    int iRet = 0; /*Initialize WISECore*/ if(!core_initialize("general", "00000001-0000-0000-0000-305A3A77B1CC", "TestClient", "305A3A77B1CC", NULL))
    {
        printf("Unable to initialize WISECore.\n");
        goto EXIT;
    }
    printf("Agent Initialized\n");
    /*Setup action callback function*/
    core_action_callback_set(on_rename, on_update);

    /*Connect to Server*/
    core_connect("127.0.0.1",1883,"admin","123456");

    /*Disconnect*/
    core_disconnect(false);

EXIT:
    /*Release WISECore*/
    core_uninitialize();
    return iRet; 
}


bool core_action_response(const int cmdid, const char * sessoinid, bool success, const char* tenantid, const char* devid);
Description
  • Send rename, update or heartbeat rate update action response back to server.

Parameters

  • cmdid[NUMBER]
    • command ID of request action.
  • sessionid[POINTER]
    • session ID of request action.
  • success[BOOLEAN]
    • result of request action.
  • tenantid[POINTER]
    • tenant ID of request device.
  • devid[POINTER]
    • device ID of request device.

Return Values

  • true/false

Example

Reference to core_action_callback_set().

Callback Function

typedef void (*SACLIENT_MESSAGE_RECV_CALLBACK)(char* topic, susiaccess_packet_body_t *pkt, void *pRev1, void* pRev2);

Description

  • define the message receive callback function.

Parameters

  • topic[POINTER]
    • MQTT topic string
  • pkt[POINTER]
    • the packet structure pointer.
  • pRev1[POINTER]
    • preserved pointer.
  • pRev2[POINTER]
    • preserved pointer.

Return Values

  • None.


typedef void (*SACLIENT_CONNECTED_CALLBACK)();

Description

  • define the on connected callback function.

Parameters

  • None

Return Values

  • None.


typedef void (*SACLIENT_LOSTCONNECT_CALLBACK)();

Description

  • define the on lost connect callback function.

Parameters

  • None

Return Values

  • None.


typedef void (*SACLIENT_DISCONNECT_CALLBACK)();

Description

  • define the on disconnect callback function.

Parameters

  • None

Return Values

  • None.

Client Sample Code

#include "stdafx.h"
#include <SAClient.h>
#include <Windows.h>
#include <Log.h>
/*agent connected callback function*/
void on_connect_cb()
{
	SUSIAccessAgentLog(Normal, "CB_Connected ");
}

/*agent lost connect callback function*/
void on_lost_connect_cb()
{
	SUSIAccessAgentLog(Normal, "CB_Lostconnect ");
}

/*agent disconnect callback function*/
void on_disconnect_cb()
{
	SUSIAccessAgentLog(Normal, "CB_Disconnect ");
}

/*agent received message callback function*/
void on_msgrecv(char* topic, susiaccess_packet_body_t *pkt, void *pRev1, void* pRev2)
{
	/*user can process received command here*/
	SUSIAccessAgentLog(Normal, "Packet received, %s\r\n", pkt->content);
}

int main(int argc, char *argv[])
{
	int iRet = 0;
	char moudlePath[MAX_PATH] = {0};
	
	/*agent configuration structure: define how does the agent connect to Server*/
	susiaccess_agent_conf_body_t config;

	/*agent profile structure: define agent platform information*/
	susiaccess_agent_profile_body_t profile;

	memset(moudlePath, 0 , sizeof(moudlePath));
	util_module_path_get(moudlePath);
		
	// Initialize Log Library
	SUSIAccessAgentLogHandle = InitLog(moudlePath);
	SUSIAccessAgentLog(Normal, "Current path: %s", moudlePath);

	// Pre-set Agent Config struct
	memset(&config, 0 , sizeof(susiaccess_agent_conf_body_t));
	strcpy(config.runMode,"remote"); //runMode default is remote. There are no other mode in WISE Agent version 3.x
	strcpy(config.autoStart,"True"); //autoStart default is True. The Agent will reconnect to server automatically.
	strcpy(config.serverIP,"dev-wisepaas.eastasia.cloudapp.azure.com"); //serverIP indicate the server URL or IP Address
	strcpy(config.serverPort,"1883"); //serverPort indocate the server (MQTT Broker) listen port, default is 1883 in WISE Agent version 3.1 or later, WISE Agent version 3.0 is 10001.
	strcpy(config.serverAuth,"fENl4B7tnuwpIbs61I5xJQ=="); //serverAuth is the server (MQTT Broker) authentication string. the string is encode from <ID>:<PASS>. It only worked on SSL Mode.
	config.tlstype = tls_type_none; //tlstype define the TLS (SSL) mode
	switch(config.tlstype)
	{
	case tls_type_none: //disable TLS (SSL).
		break;
	case tls_type_tls: //setup TLS with certificate file.
		{
			strcpy(config.cafile, "ca.crt");
			strcpy(config.capath, "");
			strcpy(config.certfile, "server.crt");
			strcpy(config.keyfile, "server.key");
			strcpy(config.cerpasswd, "123456");
		}
		break;
	case tls_type_psk: //setup TLS with pre share key.
		{
			strcpy(config.psk, "");
			strcpy(config.identity, "SAClientSample");
			strcpy(config.ciphers, "");
		}
		break;
	}

	// Pre-set Agent Profile struct
	memset(&profile, 0 , sizeof(susiaccess_agent_profile_body_t));
	snprintf(profile.version, DEF_VERSION_LENGTH, "%d.%d.%d.%d", 3, 1, 0, 0);  //version indicate the version fo the application.
	strcpy(profile.hostname,"SAClientSample"); //hostname indicate the name of target device ro agent.
	strcpy(profile.devId,"000014DAE996BE04"); //devId is the Unique ID of the target device or agent.
	strcpy(profile.sn,"14DAE996BE04"); //sn indicate the device serial number.
	strcpy(profile.mac,"14DAE996BE04"); //mac indicate the MAC Address of first ethernet or wireless card.
	strcpy(profile.type,"IPC"); //type indicate the agent type, defualt is IPC. User can define their own type for customization.
	strcpy(profile.product,"Sample Agent"); //produce indicate the product name
	strcpy(profile.manufacture,"test"); //manufacture indicate the manufacture name
	strcpy(profile.osversion,"NA"); //osversion indicate the OS version of target device
	strcpy(profile.biosversion,"NA"); //biosversion indicate the BIOS version of target device
	strcpy(profile.platformname,"NA"); //platformname indicate the platform (board) name of target device
	strcpy(profile.processorname,"NA"); //processorname indicate the processor name of target device
	strcpy(profile.osarchitect,"NA"); //osarchitect indicate the OS architecture name of target device
	profile.totalmemsize = 40832; //totalmemsize indicate the OS recognized total memory size of target device
	strcpy(profile.maclist,"14DAE996BE04"); //maclist list all the ethernet and wireless card MAC Address.
	strcpy(profile.localip,"172.21.73.151"); //localip indicate the local IP of target device
	strcpy(profile.account,"anonymous"); //account bind the device or anget to the sepcific account, default is anonymous.
	strcpy(profile.passwd,""); //passwd indicate the encrypted password of account.
	strcpy(profile.workdir, moudlePath); //workdir indicate current executable binary file location.


	/*Initialize SAClient with Agent Configure and Profile structure, and the Log File Handle*/
	iRet = saclient_initialize(&config, &profile, SUSIAccessAgentLogHandle);

	if(iRet != saclient_success)
	{
		SUSIAccessAgentLog(Error, "Unable to initialize AgentCore.");
		goto EXIT;
	}

	SUSIAccessAgentLog(Normal, "Agent Initialized");

	/*register the conect, lost connect and disconnect callback function*/
	saclient_connection_callback_set(on_connect_cb, on_disconnect_cb, on_disconnect_cb);

	SUSIAccessAgentLog(Normal, "Agent Set Callback");
	
	/*start connect to server, server is defined in agent config*/
	iRet = saclient_connect();

	if(iRet != saclient_success){
		SUSIAccessAgentLog(Error, "sampleagent Unable to connect to broker.");
		goto EXIT;
	} else {
		SUSIAccessAgentLog(Normal, "sampleagent Connect to broker: %s", config.serverIP);
	}
	
	{
		
		char topicStr[128] = {0};
		susiaccess_packet_body_t pkt;

		/* Add  subscribe topic Callback*/
		sprintf(topicStr, "/cagent/admin/%s/testreq", profile.devId);
		saclient_subscribe(topicStr, 0, on_msgrecv);
		
		/*Send test packet to specific topic*/
		strcpy(pkt.devId, profile.devId);
		strcpy(pkt.handlerName, "Test");
		pkt.requestID = 0;
		pkt.cmd = 0;
		pkt.content = (char*)malloc(strlen("{\"Test\":100}")+1);
		memset(pkt.content, 0, strlen("{\"Test\":100}")+1);
		strcpy(pkt.content, "{\"Test\":100}");
		saclient_publish(topicStr, 0, false, &pkt);
		free(pkt.content);
	}

EXIT:
	printf("Click enter to exit");
	fgetc(stdin);

	/*disconnect from server*/
	saclient_disconnect();
	SUSIAccessAgentLog(Normal, "Send Client Info: disconnect");
	/*release SAClient resource*/
	saclient_uninitialize();
	SUSIAccessAgentLog(Normal, "Agent Uninitialize");
	/*release log resource*/
	UninitLog(SUSIAccessAgentLogHandle);

	return iRet;
}