#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>

#include <termios.h>
#include <fcntl.h>
#include <errno.h>

#define SERIAL_PORT "/dev/ttyS1"

int open_ser();

int main(int argc, char* argv[])
{
    int fd = open_ser();
    int waiting = 1;
    char buff[32];

    while ( waiting )
    {
        write(fd, "U", 1);

        if ( read(fd, buff, 1) == 1 )
        {
            if ( buff[0] == 'U' )
            {
                waiting = 0;
                printf("Got 'U' bootloader connected\n");
            }
            else
            {
                waiting = 1;
                printf("Got '%c' still waiting to connect\n", buff[0]);
            }
        }
    }

    close(fd);

    return 0;
}

int open_ser()
{
    int fd;
    struct termios newtio;
    
    fd = open(SERIAL_PORT, O_RDWR | O_NOCTTY | O_NDELAY);
    
    if ( fd < 0 )
    {
        perror("open_ser");
        printf("ERROR Can't open the device %s (errno %d)\n",
               SERIAL_PORT, errno);

        return fd;
    }
    
    bzero(&newtio, sizeof(newtio));
    newtio.c_cflag = B38400 | CS8 | CLOCAL | CREAD;
    newtio.c_iflag = IGNPAR;
    newtio.c_oflag = 0;

    /* set input mode (non-canonical, no echo,...) */
    newtio.c_lflag = 0;
    newtio.c_cc[VTIME] = 0; /* inter-character timer unused */
    newtio.c_cc[VMIN] = 0; /* blocking read until 5 chars received */
    
    tcflush(fd, TCIFLUSH);
    tcsetattr(fd, TCSANOW, &newtio);

    return fd;
}

