// 7K87K_dio.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "stdio.h"
#include "PACSDK.h"
#include "conio.h"

int main(int argc, char* argv[])
{
		BOOL err,bQuit;
		char strErr[32];
		DWORD lDI_Value = 0;
		DWORD lDO_Value = 0;
		char connectionstring[32];
		int iAddr=1,iCom=2;
		int iDOChannels=8,iDIChannels=8,iNum=0;
		
		printf("ICPDAS (R) SDK Demo for XP-8000\n\n");
		printf("This demo is for remote 87K and 7K modules.\n\n");
	
		//Get com port
		printf("Input com's connectionstring(like\"COM2,9600,N,8,1\"):");
		scanf("%s",connectionstring);
		//Open com port except COM1,COM1 is for local.
		//This demo is for remote 87K and 7K modules.		
		HANDLE hPort = uart_Open(connectionstring);
		if(hPort == INVALID_HANDLE_VALUE)
		{
			pac_GetErrorMessage(pac_GetLastError(), strErr);
			printf("Open Error: %s. The error code is %x\n", strErr, pac_GetLastError());
			return 0;
		}	
		
		//Get address
		printf("Input address(hex):");
		scanf("%x",&iAddr);
		//Get DO total channels
		printf("Input DO total channels:");
		scanf("%d",&iDOChannels);
		//Get DI total channels
		printf("Input DI total channels:");
		scanf("%d",&iDIChannels);

		bQuit=false;
        while(!bQuit){
			printf(
				"\n1.Write DO value\n"
				"2.Read DI and DO value\n"
				"3.exit\n"
				"Input number:"
			);
			scanf("%d",&iNum);
			switch(iNum){
			case 1:	 
				printf("Input DO value(hex):");
		  		scanf("%x",&lDO_Value);			   
				pac_WriteDO(hPort,PAC_REMOTE_IO(iAddr),iDOChannels,lDO_Value);
				printf("Write DO value 0x%x\n",lDO_Value);
				printf("Press any key to continue...");
				getch();
            break;
            case 2:			  
				err = pac_ReadDIO(hPort, PAC_REMOTE_IO(iAddr), iDIChannels, iDOChannels, &lDI_Value, &lDO_Value);					
				printf("The DI's value is %d\n", lDI_Value);
				printf("The DO's value is %d\n", lDO_Value);
				printf("Press any key to continue...");
				getch();
            break;
			   case 3:
			      bQuit=true;
			   break;
      		}
			fflush(stdin);
		}
		
		err = uart_Close(hPort);
		if(err == FALSE)
		{
			pac_GetErrorMessage(pac_GetLastError(), strErr);
			printf("Close Error: %s. The error code is %x\n", strErr, pac_GetLastError());
			return 0;
		}	
	
	return 0;
}
