Sunday, July 6, 2014

Fletcher Checksum Calculator in Bash

Bash is quite a powerful scripting language and all UNIX machines have it.   The main problem with it is that it was initially designed to work in text mode, making it awkward to process numbers, which tend to be unexpectedly converted back to text strings.

If you need to debug a serial RS232/RS422 avionics device with control messages that end in a checksum or CRC, then it can be hard to generate the checksums.  This example calculates the Fletcher checksum of a hexadecimal message and prints the message out, so that you can copy and paste it into a serial terminal such as cutecom, minicom or screen.

Alternatively, you could print the message directly to the serial device, provided that you initialized it with stty as shown in here: http://www.aeronetworks.ca/2014/01/crcs-and-serial-ports.html

The calculator bc and the printf statement can be used to overcome these limitations.

#! /bin/bash
echo -en "Message = "

# Calculate the Hexadecimal message checksum using bc
MESSAGE="11 22 33 44 55 66"
SUM=0
FLETCHER=0
j=0

for i in $MESSAGE
do
 j=$(echo "ibase=16;$i" | bc)
 printf "%x " "$j"

 SUM=$(echo "$SUM + $j" | bc)
 SUM=$(echo "$SUM%256" | bc)

 FLETCHER=$(echo "$FLETCHER + $SUM" | bc)
 FLETCHER=$(echo "$FLETCHER%256" | bc)
done
printf "%x " "$SUM"
printf "%x\n" "$FLETCHER"



Serial Port Tips

www.aeronetworks.ca/2015/01/serial-port-io.html
www.aeronetworks.ca/2014/10/serial-ports-revisited.html
www.aeronetworks.ca/2014/01/crcs-and-serial-ports.html
www.aeronetworks.ca/2013/10/serial-port-tricks.html
www.aeronetworks.ca/2013/05/usb-serial-device-with-unknown-ids.html
www.aeronetworks.ca/2015/10/reading-and-parsing-data-from-serial.html
www.aeronetworks.ca/2013/05/compile-moxa-serial-widget-device.html


La voila!

Herman

No comments:

Post a Comment

On topic comments are welcome. Junk will be deleted.