/*
 * testing uart tx gap issue
 * e2e: https://e2e.ti.com/f/1045/t/1646711
 */

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <termios.h>

int main(int argc, char** argv)
{
	char *dev = "/dev/ttyS5";
	struct termios options;
	char buff[] = { 0x62, 0, 0x4a };
	unsigned long loops = -1;
	int fd, ret = 0;

	if (argc > 1) {
		loops = strtoul(argv[1], NULL, 0);
		if (!loops) {
			printf("incorrect loop number\n");
			return 1;
		}
	}

	fd = open(dev, O_RDWR | O_NOCTTY | O_NDELAY);
	if (fd < 0) {
		printf("open %s failed\n", dev);
		return 2;
	}

	fcntl(fd, F_SETFL, FNDELAY);
	cfsetispeed(&options, B3000000);
	cfsetospeed(&options, B3000000);

	options.c_cc[VTIME] = 0; /* Set timeout to 15 seconds */
	options.c_cc[VMIN] = 0;

	options.c_cflag |= ( CLOCAL | CREAD );
	options.c_iflag |= ( IGNPAR | IGNBRK );
	/* Raw input */
	options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);


	/* Software flow control is disabled */
	options.c_iflag &= ~(IXON | IXOFF | IXANY);
	/* Raw output */
	options.c_oflag &=~ OPOST;

	cfmakeraw(&options);

	ret = tcsetattr(fd, TCSANOW, &options);
	if (ret < 0) {
		printf("TCSANOW failed (%d)\n", ret);
		goto ret;
	}

	ret = tcflush(fd, TCIFLUSH);
	if (ret < 0) {
		printf("TCIFLUSH failed (%d)\n", ret);
		goto ret;
	}

	while(loops--) {
		write(fd, buff, 3);
		usleep(1000);
	}
ret:
	close(fd);
	return ret;
}
