#!/bin/bash

HOST=192.168.xxx.xxx
PORT=4223
tUID=XXX

###################################################################################
ALPHABET="123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"
BASECOUNT=`expr length $ALPHABET`
DECODED=0
MULTI=1
for ((i=`expr length $tUID - 1` ; i > -1 ; i--))
  do
    VALUE=${tUID:$i:1}
    DECODEDVALUE=`expr index $ALPHABET $VALUE`
    DECODEDVALUE=`expr $DECODEDVALUE - 1`
    DECODED=`expr $DECODED + $MULTI \* $DECODEDVALUE`
    MULTI=`expr $MULTI \* $BASECOUNT`
  done
HEXDECODEDSTR=""
HEXDECODED=`printf "%08x" $DECODED`
for i in {6,4,2,0}
  do
    DIGIT=${HEXDECODED:$i:2}
    HEXDECODEDSTR=$HEXDECODEDSTR"\x"$DIGIT
  done
###################################################################################
SENDPACKET=$HEXDECODEDSTR"\x08\x01\x18\x00"

RECEIVEPATTERN=`echo -n -e $HEXDECODEDSTR"\x0c\x01\x18\x00" | od -A n -t x1 | tr -d " "`
RECEIVEPACKET=`echo -n -e "$SENDPACKET" | nc -w1 $HOST $PORT | xxd -p`

#DEBUG
#echo -n -e "$RECEIVEPACKET" | xxd -r -p > /home/tinker/RECEIVEPACKET.airpressure.`date "+%Y%m%d_%H%M%S"`

FOUNDSTART=`echo -e -n $RECEIVEPACKET | xxd -r -p | od -w16384 -A n -t x1 | tr -d " " | grep -o -F $RECEIVEPATTERN -b | cut -f1 -d ":"`

if [[ "$FOUNDSTART" != "" ]] ; then
   FOUNDSTART=`expr $FOUNDSTART + 17`
   FOUNDEND=`expr $FOUNDSTART + 7`
   AIRPRESSURE1=`echo -e -n $RECEIVEPACKET | xxd -r -p | od -w16384 -A n -t x4 | tr -d " " | cut -b $FOUNDSTART-$FOUNDEND | tr "[:lower:]" "[:upper:]"`
   AIRPRESSURE2=`echo "scale=2 ; ibase=16; $AIRPRESSURE1 / 3E8" | bc`

   if [ "$1" = "x" ] ; then echo "`date +%Y%m%d_%H:%M:%S';'%s`;$AIRPRESSURE2"
      else
        echo -e "\nDer Luftdruck betraegt: $AIRPRESSURE2 mbar.\nParameter x gibt Logfileoutputformat.\n"
   fi
   else
     echo "No Packet machted" >&2
     echo "`date +%Y%m%d_%H:%M:%S';'%s`;"
fi

# DATAFORMAT: 20120514_08:42:02;1336977722;20.62


