#
# Hardware Setup required to run this script
#  - one host connected via serial line (cfg-file section "host", application "wibohost")
#  - at least one node as Wibo (cfg-file section "node1", "node2", ... application "wibo"+"xmpl_wibo"
#
#

import time
import ConfigParser
import os

import sys
sys.path.append('../Src/App/WiBo/PyHost')
# sys.path.append('./install/wibo')

import wibohost
# import nodeaddr

def flash():
	""" flash necessary files """
	dudeargs='-cjtag2 -Pusb' # common for all

	fname=instdir+'wibohost_'+cfg.get('host', 'boardname')+'.hex'
	dudecmdlines = ['avrdude -U'+(fname)+' '+dudeargs+' '+cfg.get('host', 'dudeargs').strip("'")]

	for n in nodes:
		fname=instdir+'wibo_'+n['boardname']+'.hex'
		dudecmdlines.append('avrdude -U'+(fname)+' '+dudeargs+' '+n['dudeargs'].strip("'"))

	for ln in dudecmdlines:
		os.system(ln)

		waittime=3.0
		print "Waiting %d seconds for avrdude..."%waittime
		# on Windows, avrdude de-enumerates after flashing, takes some time to re-enumerate
		time.sleep(waittime)


if __name__ == '__main__':
	instdir = '../install/bin/'

	cfg=ConfigParser.ConfigParser()
	cfg.read('env_wibo_daniel.cfg')

	nodes=[dict(cfg.items(i)) for i in cfg.sections() if dict(cfg.items(i))['type']=='node']

	whost=wibohost.WIBONetwork(port=cfg.get('host', 'port'), baudrate=cfg.get('host', 'baudrate'), timeout=1.0)
	time.sleep(0.1)

	teststr = "Thequickbrownfoxjumpsoverthelazydog"
	print "Connecting to WiboHost ...",
	ret=whost.echo(teststr)
	print ret['code']
	if ret['data'] != teststr:
		raise Exception("Cannot connect to host")

	print "Pinging nodes ..."
	for n in nodes:
		print n['short_addr'],
		print whost.ping(int(n['short_addr'], 16))['code']

	print "Jumping to bootloader ..."
	for n in nodes:
		print n['short_addr'],
		whost.jbootl(int(n['short_addr'], 16))['code']
		if whost.ping(int(n['short_addr'], 16))['data']['appname'] == 'wibo':
			print 'OK'
		else:
			print 'FAIL'

	print "Finding board groups ..."
	boards = {}
	for n in nodes:
		p=whost.ping(int(n['short_addr'], 16))
		if p['data']['boardname'] not in boards:
			boards[p['data']['boardname']] = [p['data']['short_addr']]
		else:
			boards[p['data']['boardname']].append(p['data']['short_addr'])
	for b,ns in boards.iteritems():
		print b, ns
		
	print "Flashing applications ..."
	for b, ns in boards.iteritems():
		appname = "../install/bin/xmpl_wibo_%s.hex"%(b)
		print b, appname
		[whost.target(int(n['short_addr'], 16), 'X') for n in nodes]
		[whost.target(n, 'F') for n in boards[b]]
		whost.flashhex(0xFFFF, appname)
		
	print "Jump to application ..."
	whost.exit(0xFFFF)

# EOF
