/*  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.
*/
/*
   2011-05-05 Epson Chiang
		new release
		
*/
#include "stdafx.h"
#include <windows.h>
#include <winioctl.h>
#include "gpioctl.h"
#include "mxdk02.h" /* prototype */

#define IOCTL_SET_SLOT IOCTL_GPIO_SET
#define IOCTL_GET_SLOT IOCTL_GPIO_GET

/**
 * Power on /off a slot's USB interface in EPM-DK02 module
 * @param fd the file descriptor of device
 * @param slot_num the slot number to be control
 * @param on 1: power on the slot, 0: power off the slot
 * @return  0 on success, otherwise returns a negative value
 */
int
mxdk02_set_slot( unsigned int fd, int slot_num, int on) 
{
	UCHAR ret=0x2F;
	DWORD dwBackSize=0;

	struct slot_info si = {slot_num, on};
	if(DeviceIoControl((HANDLE)fd, IOCTL_SET_SLOT, (void*)&si, sizeof(slot_info), (void*)&ret, sizeof(UCHAR), &dwBackSize, NULL)){
		return 0;
	}
	else{
		return (-1);
	}
}

/**
 * Get a slot's USB interface status in EPM-DK02 module
 * @param fd the file descriptor of device
 * @param slot_num the slot number to be control
 * @return  0: power off 1:power on , otherwise returns a negative value
 */
int	mxdk02_get_slot(unsigned int fd, int slot_num)
{
	UCHAR	ret=0x2F;
	DWORD	dwBackSize = 0;
	int		slot_status = 0;
	struct	slot_info si = {slot_num, 1};

	if(DeviceIoControl((HANDLE)fd, IOCTL_GET_SLOT, (void*)&si, sizeof(slot_info), (void*)&si, sizeof(slot_info), &dwBackSize, NULL)==0){
		return (-1);
	}

	/*If slot number is not specified, then we return the register value*/
	if(slot_num == 0){
		slot_status = si.value;
	}
	else{
		/*Return 1 if the slot is set*/
		slot_status = si.value & (1 << (slot_num -1 + 4)); 
		if(slot_status > 0){
			slot_status = 1;
		}
	}
	return slot_status;
}

/**
 * Open the Moxa EPM-DK02 device 
 * @return  0 on failure, otherwise return fd
 */
unsigned int
mxdk02_open()
{
	HANDLE hnd;
	unsigned int fd;
	hnd = CreateFile ( "\\\\.\\mxdk02", GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
	
	if (hnd == INVALID_HANDLE_VALUE) {
		fd = 0; /* return 0 for fail */
	}
	else{
		fd = (unsigned int)hnd;
	}

	return fd;
}

/**
 * Close the fd of Moxa EPM-DK02 device
 * @param fd the file descriptor of device
 * @return  0 on success, otherwise returns a negative value
 */
int 
mxdk02_close(unsigned int fd)
{
	if(CloseHandle((HANDLE)fd)){
		return 0;
	}
	else{
		return (-1);
	}
}