;connects, erases and downloads hexfile into P89V51RD2
;usage: ttpmacro sendhex.ttl hexfile.hex [logfile.log]


strlen param2
if result=0 then
  messagebox 'Usage: ttpmacro sendhex.ttl hexfile.hex [logfile.log]' 'Error: missing hexfile name'
  end
endif


;prepare a nice title
title = 'Downloading ' 
strconcat title param2
strconcat title ' to P89V51RD2'

;assumes, that the default teraterm.ini is set correctly fo COMx, correct baudrate, 8N1, some delay after lines
connect ''

;first attempt to connect using 'U'
;timeout is too long so we try to send 1 sec 'U' then wait 1 sec... sometimes it works, sometimes not... obviously there is no way of finding out what the ... is in the buffer
settitle 'Connecting to P89V51RD2... Reset the target now.'
timeout=1
:connecting
flushrecv
gettime oldtime

:loopsend
send 'U'
gettime newtime
strcompare oldtime newtime
if result=0 goto loopsend

setecho 1
send '.'
setecho 0
wait 'U' '.'
if result<>1 goto connecting

;by here, the P89V51RD2 is in the bootloader mode

;start logging
strlen param3
if result>0 then
  logopen param3 0 0
endif

;send line for erasing
settitle 'Erasing the P89V51RD2...'
sendln ':0100000301FB'

;send the hexfile itself
settitle title
sendfile param2 0

;waiting until end - assuming the hexfile contains the end record
flushrecv
result=1
timeout=1	
while result=1	
  recvln
  strcompare inputstr ':00000001FF.'
  if result<>0 then
    result=1
  endif
endwhile

sendln ':020000050002F7'
recvln
strcompare inputstr ':020000050002F705.'
version5=result

;send the reset string - only version 5!!!!!
if version5=0 then
  settitle 'Resetting...'
  sendln ':0000000BF5'
  result=1
  timeout=1	
  while result=1	
    recvln
    strcompare inputstr ':0000000BF5.'
    if result<>0 then
      result=1
    endif
  endwhile
endif


strlen param3
if result>0 then
  logclose
endif


closett

end

