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

void show_usage()
{
    fprintf( stderr, "Usage: tty2hex port baud\n" );
    fprintf( stderr, "       supported baud rates: 4800, 9600, 19200,\n"
             "                             38400, 57600, 115200, 230400\n" );
}

int speed_to_speed( char* speed )
{
    if( strncmp( speed, "4800", 5 ) == 0 ) return B4800;
    if( strncmp( speed, "9600", 5 ) == 0 ) return B9600;
    if( strncmp( speed, "19200", 6 ) == 0 ) return B19200;
    if( strncmp( speed, "38400", 6 ) == 0 ) return B38400;
    if( strncmp( speed, "57600", 6 ) == 0 ) return B57600;
    if( strncmp( speed, "115200", 7 ) == 0 ) return B115200;
    if( strncmp( speed, "230400", 7 ) == 0 ) return B230400;
    return -1;
}

int main( int argc, char **argv )
{
    if( argc < 3 )
    {
        show_usage();
        exit( -1 );
    }

    int speed = speed_to_speed( argv[2] );
    if( speed < 0 )
    {
        fprintf( stderr, "Unsupported baud rate: %s\n", argv[2] );
        show_usage();
        exit( -1 );
    }

    int fd = open( argv[1], O_RDONLY | O_NOCTTY );
    if( fd < 0 )
    {
        perror( argv[1] );
        show_usage();
        exit( -1 );
    }
    struct termios options;

    bzero( &options, sizeof( options ) );
    options.c_cflag = speed | CS8 | CLOCAL | CREAD | IGNPAR;
    tcflush( fd, TCIFLUSH );
    tcsetattr( fd, TCSANOW, &options );

    int r;
    char buf;
    while( 1 )
    {
        r = read( fd, &buf, 1 );
        if( r > 0 )
        {
            printf( "%02X", ( int )buf );
        }
    }
}
