// UartMode.cpp : Defines the entry point for the console application.
/* V2201-W7E 
   First release by Sean Hsieh 2015.03.05
*/
#include "stdafx.h"
#include <windows.h>
#include "mxsp.h"

#define MAX_SERIAL_PORT_NUMBER 2


int _tmain(int argc, _TCHAR* argv[])
{
	char	*interface_array[] = { "RS485-2W", "RS422", "RS232" }; //{RS232, RS485-2W, RS485-4W, RS485-4W}
	HANDLE	hSerial;
	int		port_no;
	int		nRet = 0;
	int		port = 0, mode = 0;
	int		n=0;

	int port_index = 0 ,port_interface = 0;
	WCHAR sin,smode;

	printf("Serial Interface Test Program\n");
    printf("\t (0) Exit Program\n");
    printf("\t (1) Display Serial Interface\n");
   	printf("\t (2) Set Serial Interface\n");

	sin=getwchar();
	n=_wtoi(&sin);
	
	do
    {
        switch (n)
        {
            // if char == '1', display the serial interface
            case 1:
				//Open serial port
				hSerial = mxsp_open();

				for(int i=0;i<MAX_SERIAL_PORT_NUMBER;i++)
				{
					//Get serial interface
					port_no = i ;
					port_interface = mxsp_get_interface(hSerial,port_no);
					printf("COM%d = %s\n",port_no+1, interface_array[port_interface]);
				}

				//Close DIO
                mxsp_close();
                break;

			 // if char == '2', Set the serial interface
            case 2:
             
				//Get Port Number
				getwchar();
				printf("Input the Port Number (1 ~ %d) = \n",MAX_SERIAL_PORT_NUMBER);
				smode = getwchar();
				port_index =_wtoi(&smode);
			
				
				if( (port_index >(MAX_SERIAL_PORT_NUMBER)) || (port_index < 1) ){
					printf("The port value you input must betwwen 1 ~ %d ",MAX_SERIAL_PORT_NUMBER);
					break;
				}

				//Get Value
				getwchar();
				printf("Input the value (0:RS485-2W, 1:RS422, 2:RS232 ) = ");
				smode = getwchar();
				port_interface = _wtoi(&smode);		

				if( (port_interface >2) || (port_interface < 0) ){
					printf("The mode value you input must betwwen 0 ~ 2 ");
					break;
				}

				//Open serial port
				hSerial = mxsp_open();
				
				//Set serial interface
				nRet = mxsp_set_interface(hSerial,port_index-1 ,port_interface);
				
				
				if(nRet == -1)
				{
					printf("Set serial interface fail!\n");
				}
				else
				{
					printf("Set serial interface success!\n");
				}

				//Close serial port
				mxsp_close();
                break;

			
        }
		getwchar();
		printf("Serial Interface Test Program\n");
		printf("\t (0) Exit Program\n");
		printf("\t (1) Display Serial Interface\n");
		printf("\t (2) Set Serial Interface\n");
        sin = getwchar();
        n = _wtoi(&sin);
    } while (n != 0);
	return 0;
}

