#!/bin/bash

# Ensure null sink exists
pactl unload-module module-null-sink 2>/dev/null
pactl load-module module-null-sink sink_name=esp32 rate=16000 channels=2 format=s16le || {
    echo "Failed to create esp32 sink"
    exit 1
}

# Loop until serial device is available
while true; do
    if [ -e /dev/ttyESP32_A ]; then
        echo "Device found, starting stream..."
        /home/littlesophia/serial_audio_catcher/serial_to_stdout /dev/ttyESP32_A | \
        /usr/bin/pacat --raw --rate=16000 --channels=2 --format=s16le --device=esp32
        echo "Stream ended, retrying..."
    else
        echo "Waiting for /dev/ttyESP32_A..."
        sleep 2
    fi
done
