#!/bin/bash

DEVICE=/dev/ttyOUT2
BAUD=115200

# Setup device
stty -F $DEVICE cs8 $BAUD ignbrk -brkint -icrnl -imaxbel -opost -onlcr -isig -icanon -iexten -echo -echoe -echok -echoctl -echoke noflsh -ixon -crtscts

# Main loop
echo -e "\033[0;36mType 'exit' to end the session.\033[0m"
while true; do
    echo -en "\033[0;36mEnter AT Command: \033[0m"
    read user_input

    # Exit condition
    if [[ "$user_input" == "exit" ]]; then
        echo -e "\033[0;32mExiting...\033[0m"
        break
    fi

    # Send command to device
    echo -e "$user_input\r" > $DEVICE &

    # Read output in the background
    (cat $DEVICE > /tmp/response & PID=$!
        # Wait for "OK" or "ERROR" to appear in the output
        while ! grep -qe "OK" -e "ERROR" /tmp/response; do
            sleep 0.5
        done

        # Print the response in green
        echo -en "\033[0;32m"
        cat /tmp/response
        echo -en "\033[0m"

        # Cleanup
        > /tmp/response
    ) &
    wait $!
done
