#!/bin/sh
#CAN Bus echo test script
#Gregory Dias
#Last modified 5/22/2014

if [ $# -lt 1 ]
then
	echo "Please specify a bitrate (bits/second)"
	exit 1
fi

case $1 in
    ''|*[!0-9]*) echo "Please specify an integer bitrate";exit 1;;
    *) BITRATE=$1 ;;
esac

#BITRATE=$1

if [[ $BITRATE -lt 10000 && $BITRATE -gt 1000000 ]]
then
	echo "Please specify a bitrate in the range of 10Kbits to 1Mbits"
	echo "in a numerical format. (EX: 500Kbits is 500000)"
	exit 1
fi

echo "CAN Bus echo test script - V1"
echo
echo "Configuring can0 with bitrate $BITRATE..."
echo
canconfig $2 stop

canconfig $2 bitrate $BITRATE

canconfig $2 start

echo
echo "Testing can1..."
echo "============================"
#using canecho on another devkit (or similar device) this script
#will be witing to see identical messages with an incremented id

#set up canread for file output
candump $2 > can1.out &
CAN1_PID=$!

sleep 1

cansend $2 -i 0x00 0x11 0x22 0x33 0x44 0x55 0x66 0x77 0x88 --loop=15
sleep 2
cansend $2 -i 0x88 0x88 0x77 0x66 0x55 0x44 0x33 0x22 0x11 --loop=15
sleep 2

kill $CAN1_PID

#send one last message to ensure candump is closed (odd,
#canread must block when waiting for a read)
cansend $2 -i 0xAA

WC=`wc -l can1.out | awk '{print $1}'`
let WC=($WC-2)/2
LOOP1COUNT=0
LOOP2COUNT=0

while read LINE
do
	if [ "$LINE" == "<0x001> [8] 11 22 33 44 55 66 77 88" ]
	then
		LOOP1COUNT=`expr $LOOP1COUNT + 1`
	fi
	if [ "$LINE" == "<0x089> [8] 88 77 66 55 44 33 22 11" ]
	then
		LOOP2COUNT=`expr $LOOP2COUNT + 1`
	fi
done < can1.out

echo $WC
echo $LOOP1COUNT $LOOP2COUNT

if [ $WC -eq `expr $LOOP1COUNT + $LOOP2COUNT` ]
then
	CAN1="PASS"
else
	CAN1="FAIL"
fi

echo "Test results:"
echo "can1: $CAN1"

#cleanup
#rm can1.out

echo
echo done.

