/*  Copyright (C) MOXA Inc. All rights reserved.

    This software is distributed under the terms of the
    MOXA License.  See the file COPYING-MOXA for details.
*/
#include "stdafx.h"
#include <windows.h>
#include <commctrl.h>
#include "mxgpio.h"
/*
	index[n]: 0  ; BIT 0
			  1  ; BIT 1
	          2  ; BIT 2
	          3  ; BIT 3
			  ....
	data[n]: 0  ; Digital LOW
	         1  ; Digital HIGH
	         
*/

#define MAX_LED_PORT_NUMBER	 2
#define LED_INDEX	 2

typedef struct _LEDMAP{
	int input;
	int output;
}LEDMAP, *PLEDMAP;

int _tmain(int argc, _TCHAR* argv[])
{
	HANDLE	hMxLED;
	int port_no=0;
	int	nLED = 0;
	int port = 0,mode = 0;
	int n = 0;
	int on = 1;
	int data=0;
	int	input=0,output=0;
    int LedMapIndex[MAX_LED_PORT_NUMBER];
	LedMapIndex[0] = 1;
	LedMapIndex[1] = 0;

	WCHAR sin,smode;
	printf("LED Test Program\n");
    printf("\t (0) Exit Program\n");
    printf("\t (1) Display LED\n");
    printf("\t (2) Set LED value\n");

	sin=getwchar();
	n=_wtoi(&sin);
	
	do
    {
        switch (n)
        {
            // if char == '1', display the digital input
            case 1:
				//Open LED
				hMxLED=mxgpio_open();

				for(int i=0;i<MAX_LED_PORT_NUMBER;i++)
				{
					//Get digital input
					port_no=LED_INDEX + LedMapIndex[i];
					input=mxgpio_get_data(hMxLED,port_no);
					printf("LED%d = %d\n",i,input);
				}

				//Close LED
                mxgpio_close(hMxLED);
                break;
			case 2:

				//Get Port Number
				getwchar();
				printf("Input the Port Number (0 ~ %d) = \n",MAX_LED_PORT_NUMBER-1);
				smode=getwchar();
				
				if( ( _wtoi(&smode) > (MAX_LED_PORT_NUMBER-1) ) || ( _wtoi(&smode) <0 ) ){
					printf("Input the Port Number must between 0 ~ %d !\n",MAX_LED_PORT_NUMBER-1);
					system("pause");
					return 0;
				}
				
				port_no=LedMapIndex[_wtoi(&smode)]+LED_INDEX;
			
				//Get Value
                getwchar();
                printf("Input the value (0 or 1) = ");
				smode=getwchar();
				data=_wtoi(&smode);

				if( ( data > 1 ) || (data <0 ) ){
					printf("Input the value must between 0 ~ 1 !\n");
					//system("pause");
					break;
				}
				
		
				//Open LED
				hMxLED=mxgpio_open();

				//Set LED
				output=mxgpio_set_data(hMxLED, port_no, data);
				
				if(output==-1)
				{
					printf("Set LED fail!\n");
				}
				else
				{
					//printf("%d\n",port_no);
					printf("Set LED success!\n");
				}

				//Close LED
				mxgpio_close(hMxLED);
                
				
				break;

			default:
				printf("Exit Program\n");
				return 0;
        }
		printf("\n");
		printf("LED Test Program\n");
		printf("\t (0) Exit Program\n");
		printf("\t (1) Display LED\n");
		printf("\t (2) Set LED value\n");

		getwchar();
        sin = getwchar();
        n = _wtoi(&sin);
    } while (n != 0);
	

	return 0;
}

