#!/bin/bash

SER="ttyS0"
USB="ttyUSB0"

uart_info()
{
    TX=$(grep -oP '16550.*tx:\K[0-9]*' /proc/tty/driver/serial)
    RX=$(grep -oP '16550.*rx:\K[0-9]*' /proc/tty/driver/serial)
    if cmp --silent /tmp/d16_0 /tmp/d16
    then
	FLAG="----"
    else
	FLAG="||||"
	git --no-pager diff /tmp/d16_0 /tmp/d16
    fi
    echo "$(date)   ${FLAG}   tx:${TX}   rx:${RX}   $1   Delta: $(( 16384 - $(stat -c %s /tmp/d16) ))"
}

uart_send__socat()
{
    socat -T0.25 -u "$1",b115200,raw,echo=0 OPEN:/tmp/d16,creat=1,trunc=1 &
    RX_PID=$!
    stty sane								# better results
    socat -U "$2",b115200,raw,echo=0 OPEN:/tmp/d16_0			# blocked during TX
    wait $RX_PID
    uart_info "$3"
}

uart_send__cat()
{
    cat < "$1" > /tmp/d16 &
    RX_PID=$!
    cat /tmp/d16_0 > "$2"
    stty sane								# better results
    kill $RX_PID
    wait $RX_PID
    uart_info "$3"
}

# Cleanup after ^C
trap 'echo -e "Killing Rx programm.. $RX_PID"; kill $RX_PID 2>/dev/null; exit 0' SIGINT SIGTERM SIGHUP

# Disable 'getty' service
systemctl status serial-getty@$SER.service
systemctl stop   serial-getty@$SER.service

# Be sure there are no orphan 'cat' or 'socat' commands
pkill -SIGKILL cat   2>/dev/null
pkill -SIGKILL socat 2>/dev/null
rm -f /tmp/d16*

# Data to send
DATA_59B="abcdefghijklmnopqrstuvwxyz_ABCDEFGHIJKLMNOPQRSTUVWXYZ_01234"
DATA_16K=$(printf "%s\n" {000..255}_${DATA_59B})
echo "$DATA_16K" > /tmp/d16_0

# stty init
stty -F /dev/$SER 115200 raw -echo
stty -F /dev/$USB 115200 raw -echo

while true
do
    uart_send__cat /dev/$SER /dev/$USB "u->s"
    uart_send__cat /dev/$USB /dev/$SER "s->u"
    #uart_send__socat /dev/$SER /dev/$USB "u->s"
    #uart_send__socat /dev/$USB /dev/$SER "s->u"
done
