import socket
import serial
import time
import sys
import getopt
import signal
import select
import twill
from twill.commands import *
import os
import thread

response = ''
#############################################
#             Main function.				#
#	Handle arguments and default values.	#
#############################################

def main(argv):
	inputfile = ''
	address = '192.168.50.33'
	port = 5002
	global FILE
	global TCP_IP
	global TCP_PORT
	try:
		opts, args = getopt.getopt(argv,"hi:a:p:",["ifile=","add=","port="])
	except getopt.GetoptError:
		print 'tcp_upload.py -i <inputfile> -a <address> -p<port>'
		sys.exit(2)
	for opt, arg in opts:
		if opt == '-h':
			print 'tcp_upload.py -i <inputfile> -a <address> -p<port>'
			sys.exit()
		elif opt in ("-i", "--ifile"):
			inputfile = arg
		elif opt in ("-a", "--add"):
			address = arg
		elif opt in ("-p", "--port"):
			port = int(arg)
	FILE= inputfile
	TCP_IP= address
	TCP_PORT= port
	
#############################################
#             Gracefull Shutdown			#
#############################################
	
def Exit_gracefully(signal, frame):
	s.shutdown(1)
	s.close()
	sys.exit(0)
			

if __name__ == "__main__":
   main(sys.argv[1:])
   signal.signal(signal.SIGINT, Exit_gracefully)


#############################################
# 				  Reset						#
#############################################
k=open(os.devnull,"w")
twill.set_output(k)
def reset():	
	go('http://'+ TCP_IP)
	fv("1","pwd","WIZ127SR")
	submit("None")
	go('http://'+ TCP_IP +'/gpio.html')
	fv("1","LED1","ON")
	fv("1","LED2","OFF")
	submit("None")
	print "Reseting node"
	time.sleep(0.5)
	go('http://'+ TCP_IP +'/gpio.html')
	fv("1","LED1","OFF")
	fv("1","LED2","OFF")
	submit("None")
	return

#############################################
# 				Handshake					#
#############################################
def handshake():
	while True:
		global s
		s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		s.connect((TCP_IP, TCP_PORT))
		response = ''
		while len(response) != 4:
			s.send(bytearray([0xB2, 0xA5, 0x65, 0x4B]))
			rlist, wlist, elist = select.select( [s], [], [], 0.2 )
			if [rlist, wlist, elist] == [ [], [], [] ]:
				print "Sending Request\n"
			else:
				response2 = s.recv(4)	
				if ord(response2[0]) == 105 or ord(response2[0]) == 211 or ord(response2[0]) == 210 or ord(response2[0]) == 38:
					response = response + response2
		if response == bytearray([0x69, 0xD3, 0xD2, 0x26]): 
			print ("Handshake CONF received!")
			break
		else:
			print ("Received invalid data!")
		
def upload():
#############################################
# 			Reading SREC file				#
#  		Converting first 2 bytes to HEX.	#
#############################################
	f = open(FILE, "r")
	sprava=f.readline()
	firstpart=bytearray.fromhex(sprava[0].encode("hex") + sprava[1].encode("hex"))
	secondpart=bytearray.fromhex(sprava[2:].rstrip('\r\n'))
	together = firstpart + secondpart
	s.send(together)
#############################################################
#          				Main loop.							#
#  Sending line and confirming line by line from SREC file.	#
#############################################################
	while sprava != "":
			response = ''
			while len(response) != 4:
				rlist, wlist, elist = select.select( [s], [], [], 0.2 )
				if [rlist, wlist, elist] == [ [], [], [] ]:
					#s.send(together)
					print "sending again"
				else:
					response2 = s.recv(4)
					if ord(response2[0]) == 77 or ord(response2[0]) == 90 or ord(response2[0]) == 154 or ord(response2[0]) == 180 or ord(response2[0]) == 45 or ord(response2[0]) == 89 or ord(response2[0]) == 178:
						response = response + response2
			if response == bytearray([0x4D, 0x5A, 0x9A, 0xB4]):
				print"#",
				if sprava[1]=='7' or sprava[1]=='8' or sprava[1]=='9':
					print ('')
					print('Upload complete !')
					s.close()
					break
				sprava=f.readline()
				firstpart=bytearray.fromhex(sprava[0].encode("hex") + sprava[1].encode("hex"))
				secondpart=bytearray.fromhex(sprava[2:].rstrip('\r\n'))
				together = firstpart + secondpart
				s.send(together)
			elif response == bytearray([0x2D, 0x59, 0x5A, 0xB2]):
					print ("Received NACK! Aborting.")
					break
			elif response == "":
				print('No ACK. Sending again.')
				s.send(together)
			else:
				print("ERROR")
				s.close()
				break

reset()		
handshake()	
upload()						
