#!/bin/bash

# Flash Upgrade Script. Copyright, GPL by Robert Olsson <robert@herjulf.se>
# Script to upgrade mote firmware on unix 
# needs tty_talk in sensd, avrdude, stty 

FIRMWARE=s1.hex
FPATH=.
DEV=/dev/ttyUSB2
BAUD=38400

function usb_flash
{
   avrdude -p m128rfa1 -c avr109 -P $DEV -b $BAUD -e -U flash:w:$FPATH/$FIRMWARE 
}

function usb_flash_init
{
    RES=$( { tty_talk -$BAUD $DEV upgr; } 2>&1 )
    OK=$(echo $RES | cut -d\  -f2)
    [ "$OK" = OK ]
}

function upgrade_flash
{
    for (( c=0; c<=10; c++ ))
    do
	if usb_flash_init; then
	    usb_flash
	    break
	fi
    done
}

function write_bootloader_and_flash
{
    avrdude  -p atmega128rfa1 -c jtag2isp   -P usb -e -U flash:w:main.hex
    sleep 3
    avrdude  -p atmega128rfa1 -c jtag2isp   -P usb  -U hfuse:w:0x9c:m -U lfuse:w:0x62:m
    sleep 2
    avrdude -p m128rfa1 -c avr109 -P $DEV -b $BAUD -e -U flash:w:$FPATH/$FIRMWARE
}

stty -F  $DEV sane
upgrade_flash

#write_bootloader_and_flash
#/home/robert/tz-label/sensor-id-labelprint-6mm
