#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>

#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <sys/sysmacros.h>

#define LED_MAJOR_NUMBER	504
#define LED_MINOR_NUMBER	100
#define LED_DEV_PATH_NAME	"/dev/uart_ioctl"

#define IOCTL_MAGIC_NUMBER 'l'
#define IOCTL_CMD_DIRECTION		_IOWR(IOCTL_MAGIC_NUMBER, 0, int)
#define IOCTL_CMD_RECEIVE		_IOWR(IOCTL_MAGIC_NUMBER, 1, int)
#define IOCTL_CMD_TRANSMIT		_IOWR(IOCTL_MAGIC_NUMBER, 2, int)

int main(void)
{
	// dev_t led_ioctl;
	int fd;
	int txrx;
	char buf[1024];
	char cbuf = '\0';
		
	// led_ioctl = makedev(LED_MAJOR_NUMBER, LED_MINOR_NUMBER);
	// mknod(LED_DEV_PATH_NAME, S_IFCHR|0666, led_dev);
	
	fd = open(LED_DEV_PATH_NAME, O_RDWR);
	
	if(fd < 0){
		printf("fail to open led\n");
		return -1;
	}
	
	printf("rx: 0, tx: 1. enter parameter: ");
	scanf("%d", &txrx);
	ioctl(fd, IOCTL_CMD_DIRECTION, &txrx);
	
	if(txrx == 0){
		printf("now RPi keep reading..\n");
		while(1){
			ioctl(fd, IOCTL_CMD_RECEIVE, &cbuf);
			printf("%c",cbuf);
		}
	}else if(txrx == 1){
		printf("now RPi keep writing..\n");
		while(1){
			printf("Input string: ");
			scanf("%1023s",buf);
			ioctl(fd, IOCTL_CMD_TRANSMIT, &buf);
		}
	}else{
		printf("invalid parameter. program shutdown\n");
	}
	
	close(fd);
	
	return 0;
}