#!/bin/bash
#
# Reads the signal strength from a DVB-c/s/t tuner
#
# (c) 2009 i.dobson@planet-ian.com
#
# 24.11.2009 Version 1.1 added support for multiple tuners
# 22.11.2009 Version 1.0 added check that femon iinstalled
# 21.11.2009 Version 0.9 added adapter number
# 20.11.2009 Version 0.8 first version
#
# Magic markers (optional):
#%# family=auto
#%# capabilities=autoconf suggest

#Starting point for tuner to watch
Tuner=0

case $1 in
    autoconf|detect)
       REQ=`which femon`
       if [ "$REQ" = "" ]; then
          echo "no (femon not installed)"
          exit 1
       fi

       if [ -e  /dev/dvb/adapter$Tuner/ ]; then
          echo yes
          exit 0
       else
          echo "no (dvb tuner $Tuner not found)"
          exit 1
       fi;;

    config)
      echo "graph_title  DVB signal strength"
      echo 'graph_args --base 1000 -l 0'
      echo 'graph_vlabel Signal Strength %'
      echo 'graph_category tv'
      echo 'graph_scale no'
      while [ -e  /dev/dvb/adapter$Tuner/ ]; do
         Tuner=$[$Tuner+1]
      done

      TunerLoop=0
      while [ $TunerLoop -lt $Tuner ] ; do
        echo "signal$TunerLoop.label Signal strength for tuner $TunerLoop"
        echo "signal$TunerLoop.draw LINE1"
        echo "signal$TunerLoop.min 0"
        TunerLoop=$[$TunerLoop+1]
      done

      TunerLoop=0
      while [ $TunerLoop -lt $Tuner ] ; do
        echo "snr$TunerLoop.label Signal to noise for tuner $TunerLoop"
        echo "snr$TunerLoop.draw LINE1"
        echo "snr$TunerLoop.min 0"
        TunerLoop=$[$TunerLoop+1]
      done

      TunerLoop=0
      while [ $TunerLoop -lt $Tuner ] ; do
        echo "ber$TunerLoop.label Bit error rate for tuner $TunerLoop"
        echo "ber$TunerLoop.draw LINE1"
        echo "ber$TunerLoop.min 0"
        echo "ber$TunerLoop.max 200"
        TunerLoop=$[$TunerLoop+1]
      done

      TunerLoop=0
      while [ $TunerLoop -lt $Tuner ] ; do
        echo "unc$TunerLoop.label Uncorrectable errors for tuner $TunerLoop"
        echo "unc$TunerLoop.draw LINE1"
        echo "unc$TunerLoop.min 0"
        echo "unc$TunerLoop.max 200"
        TunerLoop=$[$TunerLoop+1]
      done
    exit 0;;
esac
  echo "" > /tmp/dvb-signal.text
  echo "" > /tmp/dvb-signal1.text
  Tuner=0
  while [ -e  /dev/dvb/adapter$Tuner/ ] ; do
    check=`femon -c 1 -a $Tuner | grep signal `
    echo $check $Tuner| awk '{printf ("signal%.0f.value %.1f\nsnr%.0f.value %.1f\nber%.0f.value %.2f\nunc%.0f.value %.4f\n#raw values Tuner %.0f  %.0f %.0f %.0f %.0f \n",$17,strtonum("0x"$5)/655,$17,strtonum("0x"$8)/655,$17,strtonum("0x"$11),$17,strtonum("0x"$14),$17,strtonum("0x"$5),strtonum("0x"$8),$11,$14)}' >> /tmp/dvb-signal.text
    echo  $check >>  /tmp/dvb-signal1.text
    Tuner=$[$Tuner+1]
  done
  cat /tmp/dvb-signal.text | grep signal
  cat /tmp/dvb-signal.text | grep snr
  cat /tmp/dvb-signal.text | grep ber
  cat /tmp/dvb-signal.text | grep unc
  cat /tmp/dvb-signal.text | grep raw
exit 0
