#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <signal.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <termios.h>

#define UART_DEVICE     "/dev/ttyS1" //uart device name

FILE *fp = NULL;
int fd = -1;

void signalHandler(int signo)
{
    switch (signo)
    {
        case SIGINT:
            {
				printf("ctrl+c detected, exit now!\n");

                if (fd > 0)
                    close(fd);

                if (fp)
                    fclose(fp);

            }
			break;
        default:
            break;
    }

    exit(0);
}

int main(int argc, char *argv[])
{
    int res;
    struct termios  oldtio, newtio;
    char  ch;
    char buf[256] = {0};

	signal(SIGINT, signalHandler);

	fp = fopen("/mnt/save_log", "w+");
	if (!fp)
	{
		printf("open file fail!\n");
		return -1;
	}

    //open uart dev file, not set O_NONBLOCK attr
    fd = open(UART_DEVICE, O_RDWR | O_NOCTTY);
    if (fd < 0) {
		fclose(fp);
        perror(UART_DEVICE);
        exit(1);
    }
    else
    printf("Open %s successfully\n", UART_DEVICE);

    //get current operation parameter
    tcgetattr(fd, &oldtio);

	// printf termios setting
	printf("termios default setting:\n");
	printf("c_iflag:%08x, c_oflag:%08x, c_cflag:%08x, c_lflag:%08x\n", oldtio.c_iflag,
			oldtio.c_oflag, oldtio.c_cflag, oldtio.c_lflag);
	printf("ispeed:%o, ospeed:%o\n", oldtio.c_ispeed, oldtio.c_ospeed);

	memcpy(&newtio, &oldtio, sizeof(struct termios));

	// set baud rate
	printf("\nset baud rate:%08x ..., c_cflag:%08x\n", B460800, newtio.c_cflag);
	cfsetispeed(&newtio, B460800);  // 010004 -> 0x1004
	cfsetospeed(&newtio, B460800);
	printf("\nset baud rate success ..., c_cflag:%08x\n", newtio.c_cflag);

	// set c_iflag
	printf("\nset c_iflag ...\n");
	newtio.c_iflag |= IGNPAR;				// 忽略奇偶校验错误
	newtio.c_iflag &= ~(ICRNL | IXON);		// 不将输入中回车符转成换行符 和 不开启输入流控
	printf("c_iflag:%08x\n", newtio.c_iflag);

	// set c_oflag
	printf("\nset c_oflag ...\n");
	newtio.c_oflag &= ~(OPOST | ONLCR);		// 禁用输出处理，数据原样发送 和 不将输出中换行符转换为回车加换行
	printf("c_oflag:%08x\n", newtio.c_oflag);

	// set c_cflag
	printf("\nset c_cflag ...\n");
	newtio.c_cflag &= ~CSIZE;				// 清除位数设定
	newtio.c_cflag |= CS8;					// 设置数据位数为8位
	printf("c_cflag:%08x\n", newtio.c_cflag);

	// set c_lflag
	printf("\nset c_lflag ...\n");
	newtio.c_lflag &= ~(ISIG | ECHO | IEXTEN);		// 特殊字符按普通字符处理 和 关闭回显 和 不启用扩展输入处理
	//newtio.c_lflag |= ICANON;				// 设置为规范模式，不设置默认为规范模式
	newtio.c_lflag &= ~ICANON;				// 设置为非规范模式
	printf("c_lflag:%08x\n", newtio.c_lflag);

	// set c_cc
	printf("\nset c_cc ...\n");				// 在非规范模式下时设置VTIME 和 VMIN 来设置read函数的返回
	newtio.c_cc[VTIME] = 0;					// 设置读取超时实际，当接收字符数不足VMIN，read等待VTIME时间后返回，单位为1/10s
	newtio.c_cc[VMIN] = 0;					// 设置最小读取字符数，达到设置字符数时，read函数返回

	tcflush(fd, TCIFLUSH);
	tcsetattr(fd, TCSANOW, &newtio);

    //receive data from uart
    while(1)
    {
        //wait to receive data from uart
		memset(buf, 0, sizeof(buf));
        res = read(fd, buf, 255);
        if (res == 0)
            continue;

#if 0
        printf("res = %d, buf:", res);//print the received char
		for (int i = 0; i < res; i++)
		{
			if (!(i % 16))
				printf("\n");
			
			printf("%02X ", buf[i]);
		}
		printf("\n");
#endif
		fwrite(buf, res, 1, fp);
    }

    //close uart dev file and recover the old parameter
    close(fd);
    printf("Close %s\n", UART_DEVICE);
    tcsetattr(fd, TCSANOW, &oldtio);

	fclose(fp);

    return 0;
}

//arm-linux-gnueabihf-gcc -o uart_sigma uart_sigma.c
