/*  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.
*/
/* V2201-W7E 
   First release by Sean Hsieh 2015.03.05
*/
#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	 1
#define LED_INDEX	 0
#define LED_ON	 1
#define LED_OFF	 0

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;

	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
					input=mxgpio_get_data(hMxLED, LED_INDEX+i);
					if( input == LED_OFF){
						printf("LED%d is off\n",i+1);
					}else if( input == LED_ON){
						printf("LED%d is on\n",i+1);
					}
				}

				//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();
				port_no=0+LED_INDEX;
			
				//if( (_wtoi(&smode) >(MAX_LED_PORT_NUMBER-1)) || (_wtoi(&smode) < 0) ){
				//	printf("The port value you input must betwwen 0 ~ %d ",MAX_LED_PORT_NUMBER-1);
				//	break;
				//}

				//Get Value
                getwchar();
                printf("Input 0 or 1 (%d = Off, %d = On) = ", LED_OFF, LED_ON);
				smode=getwchar();
				data=_wtoi(&smode);
		
				if( (data!=0) && (data!=1) ){
					printf("The value you input must be 0 or 1. ");
					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("Set LED success!\n");
				}

				//Close LED
				mxgpio_close(hMxLED);
                
				
				break;
        }
		getwchar();
		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);
    } while (n != 0);
	

	return 0;
}

