#if _MSC_VER > 1500 
#include <stdint.h>
#else 
#include "stdint.h"
#endif
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>

#include <Windows.h>

#include "bcap_client.h"

/* *** Please change IP,Controller to the target IoTDS  *** */ 
#define TARGET_IOTDS_IP	"127.0.0.1"
#define TARGET_IOTDS_CONTROLLER_NAME	L"CTRL1"
#define TARGET_IOTDS_ITEM_NAME			L"ITEM1"

int main()
{
	int fd;
	uint32_t hCtrl, hItem;
	BSTR bstr1, bstr2, bstr3, bstr4;
	HRESULT hr;

	printf("Enter any key to start.\n");
	getch();

	/* Open connection. specify the IP address of bCapServer */
	printf("Open connection to tcp:%s\n", TARGET_IOTDS_IP);
	hr = bCap_Open_Client("tcp:" TARGET_IOTDS_IP, 1000, 3, &fd);

	if(SUCCEEDED(hr)){
		/* Send SERVICE_START packet */
		bCap_ServiceStart(fd, NULL);

		bstr1 = SysAllocString(L"IoTDS");                    /* Name */
		bstr2 = SysAllocString(L"CaoProv.DENSO.IoTDS");   /* Provider */
		bstr3 = SysAllocString(L"");					/* Machine */
		bstr4 = SysAllocString(L"Controller=" TARGET_IOTDS_CONTROLLER_NAME);					/* Option */

		/* Connect to IoTDS */
		hr = bCap_ControllerConnect(fd, bstr1, bstr2, bstr3, bstr4, &hCtrl);

		SysFreeString(bstr1);
		SysFreeString(bstr2);
		SysFreeString(bstr3);
		SysFreeString(bstr4);

		/* Access ITEM1. */
		if(SUCCEEDED(hr)){
			BSTR bstrItem;

			bstrItem = SysAllocString(TARGET_IOTDS_ITEM_NAME);	// Name

			bstr2 = SysAllocString(L"");		// Option

			/* Get ITEM1 variable handle */
			hr = bCap_ControllerGetVariable(fd, hCtrl, bstrItem, bstr2, &hItem);

			SysFreeString(bstr2);

			if(SUCCEEDED(hr)){
				VARIANT vValue;

				VariantInit(&vValue);

				/* Get value of ITEM1 */
				hr = bCap_VariableGetValue(fd, hItem, &vValue);
				if(SUCCEEDED(hr)){

					/* Change value type to string type. */
					hr = VariantChangeType(&vValue, &vValue, 0, VT_BSTR);
					if(SUCCEEDED(hr)){
						printf("%S value = %S\n", bstrItem, vValue.bstrVal);
					}

					/* Release memory of vValue */
					VariantClear(&vValue);
				}

				/* Release variable handle of ITEM1 */
				bCap_VariableRelease(fd, &hItem);


			}
			SysFreeString(bstrItem);
		}

		/* Disconnect IoTDS */
		bCap_ControllerDisconnect(fd, &hCtrl);

		/* Send SERVICE_STOP packet */
		bCap_ServiceStop(fd);

		/* Close connection */
		bCap_Close_Client(&fd);
	}

	return hr;
}
