#!/bin/sh
# usals_mon v0.20 by Zak
# based on diseqc_mon - diseqc 1.2 monitoring script v.080510 by bbjs
#
# Check for channel change every second, autosend diseqc command when:
# satellite has changed
# Uses new 5 byte diseqcsend from chriwi and Konfetti
# includes awk from aaf 1.5 image
# includes a new curchan that actually works (version 0.52)
# This program uses the position that is in the channel list.
# The program understands the following formats in the channel list:
# -5.4 5.4
# 5.4E 5.4W
# E5.4 W5.4
#
settings=/data/bin/usals.conf
sleep 1
cursat=`/data/bin/curchan -sat`
/data/bin/curchan -satname
# echo $cursat
	while :
	do
		sleep 1
		newsat=`/data/bin/curchan -sat`
		if [ "$newsat" != "$cursat" ] ; then 
			# read lat and lon from config file.
			# strip indicators for north/south
			# for e/w, east is negative
			# also accept o for east (ost or oost)
			LAT=`/data/bin/awk -F '[ |^t|=]' ' { input = $NF }
				{ value = input }
				{ gsub(/-|n|N|s|S|z|Z/,"",value) }
				/LAT.*=/ { print value } ' <$settings`
			LON=`/data/bin/awk -F '[ |^t|=]' ' { input = $NF }
				{ value = input }
				{ gsub(/-|e|E|o|O|w|W/,"",value) }
				input ~ /-|e|E|o|O/ { value = -value }
				/LON.*=/ { print value } ' <$settings`
			export LAT
			export LON
			cursat=$newsat
			/data/vfdctl "> `/data/bin/curchan -satname |
				cut -b 6-`"
			pos=`/data/bin/curchan -satname | /data/bin/awk '
				# get $LAT and $LON from environment
				{ lat = ENVIRON["LAT"] }
				{ lon = ENVIRON["LON"] }
				# last field on stdin is the satellite position
				{ pos = $NF }
				# remove characters to create numeric part
				{ satpos = pos }
				{ gsub(/-|e|E|o|O|w|W/,"",satpos) }
				# put the sign in
				pos ~ /-|e|E|o|O/ { satpos = -satpos }
				# relative sat position
				{ satpos = satpos - lon }
				# approximation to trig functions for azimuth
				# our awk doesnt do trig
				# error is <0.5 degree from -50 to +50
				# motor rotation I hope
				lat<=0  { lat = -lat }
				lat<=90 { fac = 1.0437 }
				lat<=70 { fac = 1.0731 }
				lat<=60 { fac = 1.1014 }
				lat<=50 { fac = 1.1275 }
				lat<=40 { fac = 1.1502 }
				lat<=30 { fac = 1.1684 }
				lat<=20 { fac = 1.1852 }
				{ azimuth = fac * satpos }
				# convert to values for diseqc
				{ byte1 = 208 }
				# angle is negative
				azimuth<0 { byte1 = 224 ; azimuth = -azimuth}
				# split into high and low bytes
				{ posh = int(azimuth/16) }
				{ posl = int((azimuth-16*posh)*16) }
				{ print byte1+posh, posl }
			'`
			/data/bin/diseqcsend1.3 224 49 110 $pos
		fi
	done

