#!/usr/bin/python3

import time
import serial
import sys

def reset():
	ser.dtr = True
	ser.rts = False
	time.sleep(0.05)
	ser.dtr = True
	ser.rts = True

def enter_bootloader():
	ser.dtr = True
	ser.rts = False
	time.sleep(0.05)
	ser.dtr = False
	ser.rts = True

if __name__ == '__main__':

	ser = serial.Serial ('/dev/ttyUSB0', 115200)

	try:
		ser.open()
	except:
		ser.close()
		ser.open()

	if 0:
		ser.timeout = 1.000
		while(True):
			print(ser.readline().decode('utf-8'), end='')

	if 1:
		ser.timeout = 1.000
		print("Start firmware update")
		enter_bootloader()
		ser.readline()

		ser.flushInput()
		with open("HendiCtrl.srec", 'r') as fp:
			while(True):
				s = fp.readline()
				if s == '':
					break
				data = s.encode()
				ser.write(data)
				ack = ser.read()
				sys.stdout.write(ack.decode('utf-8'))
				
				sys.stdout.flush()
				
		ser.readline()
		ser.flushInput()
		reset()
		print("\nStart application")
		print(ser.readline().decode('utf-8'))

	ser.close()

	print ("End of program.")

