#!/bin/bash
# Bash script to call wspr_g0etp WSPR modulation generator and pass
# samples to Linux sound device. Also handles WSPR slot skipping
# according to density probability provided.
# You should ideally have the PC clock locked to NTP.
# Needs rigctld running on localhost to key/de-key the transmitter
# Needs wspr_g0etp executable to be on the path or provide a symlink 
# G0ETP April 2024
# License: Free to use and modify but please retain the credit.

# USB dial freqs for 1.5kHz centre-band:
# 0.136, 0.4742, 1.8366, 3.5686, 5.2872, 5.3647, 7.0386, 10.1387, 13.5539, 14.0956, 18.1046
# 21.0946, 24.9246, 28.1246, 50.293, 70.091, 144.489, 432.300

# Command line parameter = decimal fraction of 2-minute frames to Tx on
TX_PROB=${1:-0.2}	# Default value 0.2

CALLSIGN="g0etp"	# Up to 6 digits
LOCATOR="jo02"		# 4 digits
POWER=30		# dBm



# Bash cant do float multiply so we have to use the horrible 'bc' 
PROB=$(bc -l <<< "($TX_PROB * 65536)")
PROB=${PROB%%.*} # Take integer result (bc even makes this hard)
#echo $PROB


while true
do

	# Get the date and split it into separate fields (output as string array)
	now=(`date +"%M %S"`)
	
	# Numbers with leading 0 are treated as octal and cause problems
	# Suppress any leading zero using parameter expansion:
	min=${now[0]#0}
	sec=${now[1]#0}
	#echo $min $sec

	# Check for 2 min boundaries (WSPR slot start times)
	if [ $sec -eq 0 ] && [ $((min & 1)) -eq 0 ]
	then
		# Compute whether we Tx in this slot or not according to specified probability
		if [ $RANDOM -lt $PROB ]
		then
			# Emit a timestamp for this transmission
			echo -n $(date) # suppresses new line
			echo ' - WSPR transmission'

			# Key the transmitter
			echo 'T 1' | netcat -N localhost 4532

			# Launch the WSPR emitter and pass STDOUT to sound device
			wspr_g0etp -q -c$CALLSIGN -l$LOCATOR -p$POWER -f90 | aplay -q -r12000 -traw -c1 -fS16_LE

			# De-key the transmitter
			echo 'T 0' | netcat -N localhost 4532

			# Wait till almost the next slot
			sleep 9
		else
			echo -n $(date) # suppresses new line
			echo ' - WSPR slot skipped'

			# Just sleep until almost the next slot
			sleep 119
		fi
	fi

	# Fine-sleep as next slot time approaches
	sleep 0.1
done

