#!/bin/sh
#CAN Bus loopback test script
#Gregory Dias
#Last modified 5/14/2014
#Updated 6/12/24 - Joshua Bourgeot

echo

echo "Test 1: mcu_mcan1 -> mcu_mcan0"

echo "============================"

#read from mcu_mcan0, write from mcu_mcan1

candump mcu_mcan0 > mcu_mcan0.out &
CAN0_PID=$!

for i in {1..15}
do
	cansend mcu_mcan1 000#11.22.33.44.55.66.77.88
	sleep 2
done

for i in {1..15}
do
	cansend mcu_mcan1 088#88.77.66.55.44.33.22.11
	sleep 2
done

kill $CAN0_PID

WC=`wc -l mcu_mcan0.out | awk '{print $1}'`

LOOP1COUNT=0

LOOP2COUNT=0

while read LINE
do
	if [ "$LINE" == "mcu_mcan0  000   [8]  11 22 33 44 55 66 77 88" ]
	then
		LOOP1COUNT=`expr $LOOP1COUNT + 1`
	fi

	if [ "$LINE" == "mcu_mcan0  088   [8]  88 77 66 55 44 33 22 11" ]
	then
		LOOP2COUNT=`expr $LOOP2COUNT + 1`
	fi

done < mcu_mcan0.out

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

if [ $WC -eq 0 ]
then
	CAN0R="FAIL"
	CAN1W="FAIL"
fi

echo
echo "Test 2: mcu_mcan0 -> mcu_mcan1"
echo "============================"

#read from mcu_mcan1, write from mcu_mcan0
candump mcu_mcan1 > mcu_mcan1.out &

CAN1_PID=$!

for i in {1..15}
do
	cansend mcu_mcan1 0FF#FF.99.AA.BB.CC.DD.EE.FF.00
	sleep 2
done

for i in {1..15}
do
	cansend mcu_mcan1 088#22.00.FF.EE.DD.CC.BB.AA.99 
	sleep 2
done

kill $CAN1_PID


WC=`wc -l mcu_mcan1.out | awk '{print $1}'`

LOOP1COUNT=0

LOOP2COUNT=0

while read LINE

do
        if [ "$LINE" == "mcu_mcan1  0FF   [8]  FF 99 AA BB CC DD EE FF" ]
        then
                LOOP1COUNT=`expr $LOOP1COUNT + 1`
        fi

        if [ "$LINE" == "mcu_mcan1  0FF   [8]  FF 99 AA BB CC DD EE FF" ]
        then
                LOOP2COUNT=`expr $LOOP2COUNT + 1`
        fi

        if [ "$LINE" == "<0x033> [0]" ]
        then
                WC=`expr $WC - 2`
        fi
done < mcu_mcan1.out

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

if [ $WC -eq 0 ]
then
	CAN1R="FAIL"
	CAN0W="FAIL"
fi

echo 
echo "Test results:"
echo "mcu_mcan0: Read - $CAN0R | Write - $CAN0W"
echo "mcu_mcan1: Read - $CAN1R | Write - $CAN1W"

#cleanup
rm mcu_mcan0.out
rm mcu_mcan1.out
echo
echo done.

