import getopt
from os.path import isfile
import re
import struct
import sys
import time
sys.path.append('../../prc/run')
from ether import c_ether
from  configuration.jtag import jtag, xilinx_bitfile_parser,xilinx_virtex_5,xilinx_spartan_6,xilinx_kintex_7,xilinx_virtex_7
from configuration.spi import spi
# sys.path.append("/home/ghuang/work/SLAC/lcls2llrf/lcls2_llrf/firmware/BMB7/examples")

#sys.path.append("../../prc/run/")
import bmb7_spartan
from mem_gateway import c_mem_gateway

class c_bmb7:
	def __init__(self, ip, port=50006, regmappath='./live_prc_regmap.json',
			bitfilepath=None, reset=False, clk_freq=1320e6/14.0,
			use_spartan=True,powercycle=False):
		self.ip = ip
		self.interface=c_ether(ip,port)

		self.use_spartan = use_spartan
		if self.use_spartan:  # can force backward compatibility with old Spartan bitfile
			self.chain = jtag.chain(ip=ip, stream_port=50005, input_select=1, speed=0)
			for i in range(0, self.chain.num_devices()):
				print hex(self.chain.idcode(i))+' - '+ self.chain.idcode_resolve_name(self.chain.idcode(i))

			[self.spartan_interface,self.carrier_rev]=self.spartan(self.ip)
			if self.spartan_interface==None:
				exit(2)
		else:
			self.spartan_interface = None
			self.carrier_rev = 1
		self.fmc_prom_address = 0x50

		if reset:
			print('Starting reset')
			if self.spartan_interface:
				if not self.sn_init():
					print("ERROR: Couldn't find serial number")
					exit(2)
			else:
				print "Digitizer serial number read disabled"
			if bitfilepath:
				if powercycle:
					self.spartan_power_cycle()
					self.spartan_power_all_enabled()
				if (self.carrier_rev == 2) != ('sesqui' in bitfilepath):
					print "Bitfile name interlock failed"
					exit(2)
				print('Trying to program')
				self.program_direct_kintex_7(bitfilepath=bitfilepath, device_choices=None)
			sys.stdout.flush()
		else:
			self.sn = self.sn_read()
			if use_spartan and not self.sn:
				print("ERROR: Couldn't find serial number")
				exit(2)
		print self.sn
	def spartan(self,ip):
		spartan_interface=None
		carrier_rev = 1
		try:
			spartan_interface = bmb7_spartan.interface(ip)
		except ValueError as ev:
			if ev.message==bmb7_spartan.ERROR:
				try:
					# Not ready for general use
					sys.path.append("/home/ldoolitt/bmb7/r1.5")
					import qf2_pre_spartan
					print("Attempting qf2_pre fallback")
					spartan_interface = qf2_pre_spartan.interface(self.ip)
					carrier_rev = 2
				except:
					print("Can't find Spartan")
			else:
				print('caught this error: ' + repr(error))
		except Exception as error:
				print('caught this error: ' + repr(error))
		return [spartan_interface,carrier_rev]

	def sn_init(self):
		if self.use_spartan:
			snread = self.sn_read()
			if not snread:
				print "sn_read() failed"
				return False
			print snread
			self.sn = snread
			m = re.match('LBNL DIGITIZER V1.0 SN  (\d+)', snread)
			if not m:
				try:
					import qrtools
					a = qrtools.QR()
					print a.data
					a.decode_webcam()
					self.sn_write(a.data)
				except:
					pass
					print "Error: Failed to get QR code or write to EEPROM"
					return False
		return True


	def sn_write(self, write_string):
		for ix in range(len(write_string)):
			if self.spartan_interface:
				self.spartan_interface.write_at24c32d_prom(self.fmc_prom_address, ix, ord(write_string[ix]))
		pass

	def sn_read(self, count=27, start_ix=0):
		r_ascii = ""
		for i in range(count):
			if self.spartan_interface:
				try:
					v = self.spartan_interface.read_at24c32d_prom(self.fmc_prom_address, start_ix+i)
					# print "read_at24c32d_prom got", v
					if v >= 32 and v < 127:
						r_ascii += chr(v)
				except:
					print "Error: Failure reading FMC EEPROM"
					return False
		return r_ascii


#
#
##!/bin/env python
#
#from socket import *
#import string,argparse
#import time
#import sys
#import bmb7_spartan
#import sys, time
#
	def spartan_power_all_enabled(self):

		self.spartan_interface.kintex_vccint_enable()
		self.spartan_interface.main_1p8v_enable()
		self.spartan_interface.main_3p3v_enable()

# GTX
		self.spartan_interface.spartan_1p2v_gtx_enable()
		self.spartan_interface.kintex_1p2v_gtx_enable()
		self.spartan_interface.kintex_1p0v_gtx_enable()
		self.spartan_interface.kintex_1p8v_gtx_enable()

# FMC
		self.spartan_interface.set_bottom_fmc_3p3v_resistor(0x0)
		self.spartan_interface.set_top_fmc_3p3v_resistor(0x0)
		self.spartan_interface.set_bottom_fmc_vadj_resistor(0x0)
		self.spartan_interface.set_top_fmc_vadj_resistor(0x0B)  # 2.5V instead of 3.3V

		self.spartan_interface.fmc_top_12v_enable()
		self.spartan_interface.fmc_bot_12v_enable()

		self.spartan_interface.fmc_top_vadj_enable()
		self.spartan_interface.fmc_bot_vadj_enable()
		self.spartan_interface.fmc_top_3p3v_enable()
		self.spartan_interface.fmc_bot_3p3v_enable()

#
##!/usr/bin/env python
#
	def program_direct_kintex_7(self,bitfilepath,device_choices=None):
# Parse the bitfile and resolve the part type
		print 'Loading bitfile:', bitfilepath
		bitfile = xilinx_bitfile_parser.bitfile(bitfilepath)

		print 'Design name:', bitfile.design_name()
		print 'Device name:', bitfile.device_name()
		print 'Build date:', bitfile.build_date()
		print 'Build time:', bitfile.build_time()
		print 'Length:', bitfile.length(), 'bits'

		print

		matching_devices = list()
		for i in range(0, self.chain.num_devices()):
				if bitfile.match_idcode(self.chain.idcode(i)):
						matching_devices.append(i)

		if len(matching_devices) == 0:
				print 'No devices matching bitfile found in JTAG chain'
				exit()

# Default to first (and only) entry
		device_choice = matching_devices[0]

# Override choice from argument line if there's more than one device
		if len(matching_devices) > 1:
				if not device_choices:
						print 'More than one matching FPGA in device chain - you must add a chain ID to the arguments'
						exit()

				choice_made = False
				for i in matching_devices:
						if i == int(device_choices):
								device_choice = i
								choice_made = True

				if choice_made == False:
						print 'No matching device selection found that corresponds to JTAG chain'
						exit()
		else:
				print 'Defaulting device selection in chain from IDCODE'

		print 'Device selected for programming is in chain location:',str(device_choice)

		if str('Xilinx Virtex 5') in self.chain.idcode_resolve_name(self.chain.idcode(device_choice)):
				print 'Xilinx Virtex 5 interface selected'
				interface = xilinx_virtex_5.interface(self.chain)
		elif str('Xilinx Spartan 6') in self.chain.idcode_resolve_name(self.chain.idcode(device_choice)):
				print 'Xilinx Spartan 6 interface selected'
				interface = xilinx_spartan_6.interface(self.chain)
		elif str('Xilinx Kintex 7') in self.chain.idcode_resolve_name(self.chain.idcode(device_choice)):
				print 'Xilinx Kintex 7 interface selected'
				interface = xilinx_kintex_7.interface(self.chain)
		elif str('Xilinx Virtex 7') in self.chain.idcode_resolve_name(self.chain.idcode(device_choice)):
				print 'Xilinx Virtex 7 interface selected'
				interface = xilinx_virtex_7.interface(self.chain)
		else:
				print 'Not able to program this device'
				exit()

		print 'Programming...'
		print

# Load the bitfile
		interface.program(bitfile.data(), device_choice)



	def spartan_power_cycle(self):
# FMC
		self.spartan_interface.fmc_top_12v_disable()
		self.spartan_interface.fmc_bot_12v_disable()
		self.spartan_interface.fmc_top_vadj_disable()
		self.spartan_interface.fmc_bot_vadj_disable()
		self.spartan_interface.fmc_top_3p3v_disable()
		self.spartan_interface.fmc_bot_3p3v_disable()

		time.sleep(1.5)
		self.spartan_interface.fmc_top_12v_enable()
		self.spartan_interface.fmc_bot_12v_enable()
		self.spartan_interface.fmc_top_vadj_enable()
		self.spartan_interface.fmc_bot_vadj_enable()
		self.spartan_interface.fmc_top_3p3v_enable()
		self.spartan_interface.fmc_bot_3p3v_enable()


#
#	def fletcher(self,data):
#
#		sum1 = 0xAA
#		sum2 = 0x55
#
#		for i in data:
#			sum1 = sum1 + int(i)
#			sum2 = sum1 + sum2
#
#		sum1 = sum1 % 255
#		sum2 = sum2 % 255
#
#		return bytearray([sum1, sum2])
#
#	def fletcher_check(self,data):
#
#		v = self.fletcher(data)
#
#		sum1 = 0xFF - ((int(v[0]) + int(v[1])) % 255)
#		sum2 = 0xFF - ((int(v[0]) + sum1) % 255)
#
#		return bytearray([sum1, sum2])
#	def program_spartan_6_configuration(self,boardmac,new_boardaddr,current_boardaddr="192.168.1.127",sha256=None):
#
#		print 'start program_spartan_6_configuration'
#		CONFIG_ADDRESS = 23 * 65536
## Initialise the interface to the PROM
#		prom = spi.interface(self.chain) #jtag.chain(ip=current_boardaddr, stream_port=50005, input_select=0, speed=0, noinit=True))
#
## Read the VCR and VECR
#		print 'PROM ID (0x20BA, Capacity=0x19, EDID+CFD length=0x10, EDID (2 bytes), CFD (14 bytes)',
#
#		print 'VCR (should be 0xfb by default):',hex(prom.read_register(spi.RDVCR, 1)[0])
#		print 'VECR (should be 0xdf):',hex(prom.read_register(spi.RDVECR, 1)[0])
#
#		if prom.prom_size() != 25:
#			print 'PROM size incorrect, read',prom.prom_size()
#			exit()
#
#		print 'PROM size: 256Mb == 500 x 64KB blocks'
#
#		print 'Programming Spartan-6 configuration settings'
#
#		pd = prom.read_data(CONFIG_ADDRESS, 87)
#
#		x = bytearray(85)
#		x = pd[0:85]
#
## Multicast MAC
#		x[0] = 0x01
#		x[1] = 0x00
#		x[2] = 0x5E
#		x[3] = 0x73
#		x[4] = 0x47
#		x[5] = 0x01
#
## Multicast IP
#		x[6] = 0xE0
#		x[7] = 0xF3
#		x[8] = 0x47
#		x[9] = 0x01
#
## Multicast port
#		x[10] = 0x04
#		x[11] = 0xEC
#
## Board MAC
#		if (boardmac != None):
#			mac = boardmac.split(':')
#			if (len(mac) != 6):
#				print 'Bad board MAC address'
#				sys.exit(1)
#			for i in range(0, 6):
#				x[12+i] = int(mac[i], 16)
#
## Board IP
#		if (new_boardaddr != None):
#			board = new_boardaddr.split('.')
#			if (len(board) != 4):
#				print 'Bad board IP address'
#				sys.exit(1)
#			for i in range(0, 4):
#				x[18+i] = int(board[i], 10)
#
## SHA256 for Kintex-7 bitstream
#		if (sha256 != None):
#			hash = sha256.split(' ')
#			if (len(hash) != 32):
#				print 'Bad Kintex7 hash'
#				sys.exit(1)
#			for i in range(0, 32):
#				x[i+22] = int(hash[i], 16)
#
#		x[61] = 0x00
#		x[62] = 0x01
#		x[63] = 0x3F
#		x[64] = 0x01
#		x[65] = 0x00
#		x[66] = 0x0E
#		x[67] = 0x02
#		x[68] = 0xBB
#
#		x[69] = 0xEA
#		x[70] = 0xD4
#		x[71] = 0x9B
#		x[72] = 0x03
#		x[73] = 0x00
#		x[74] = 0x04
#		x[75] = 0x01
#		x[76] = 0xB2
#
#		x[77] = 0x01
#		x[78] = 0xB2
#		x[79] = 0x7F
#		x[80] = 0xFF
#		x[81] = 0xFF
#		x[82] = 0xFF
#		x[83] = 0x01 # [0] == POWER BURST MODE ENABLE
#		x[84] = 0xFF
#
#		v = self.fletcher_check(x)
#		x += v
#
##for i in x:
##    print hex(i),
##print
#
#		if ( x == pd ):
#			print 'Values already programmed'
#			exit()
#
#		x += bytearray(256 - len(x))
#
#		prom.subsector_erase(CONFIG_ADDRESS)
#		prom.page_program(x, CONFIG_ADDRESS)
#
#		pd = prom.read_data(CONFIG_ADDRESS, 87)
#
#		if ( x[0:87] != pd ):
#			print 'Update failed'
#
#
#if __name__=="__main__":
#	readdress=True
#	if readdress:
#		parser = argparse.ArgumentParser(description='Write BMB-7 Spartan6 flash memory.', formatter_class=argparse.ArgumentDefaultsHelpFormatter)
#		parser.add_argument('-a', '--addr', default='192.168.1.127', help='IP address of board')
#		parser.add_argument('-b', '--board', help='New IP address to be written into flash')
#		parser.add_argument('-m', '--mac', help='New MAC address to be written into flash')
#		parser.add_argument('-s', '--hash', help='New Kintex7 bootstrap SHA256 hash')
#		args = parser.parse_args()
#		carrier=c_bmb7(args.addr,readdress=True)
#		carrier.program_spartan_6_configuration(boardmac=args.mac,new_boardaddr=args.board,current_boardaddr=args.addr,sha256=args.hash)
#	else:
#		ip="192.168.21.11"
#		bitfilepath="../prc.bit"
#		device_choice=None
#		if (len(sys.argv)>1):
#			ip=sys.argv[1]
#		if (len(sys.argv)>2):
#			bitfilepath=sys.argv[2]
#		if (len(sys.argv)>3):
#			device_choice=sys.argv[3]
#
#		carrier=c_bmb7(ip)
#		carrier.spartan_power_cycle()
#		carrier.spartan_power_all_enabled()
#		carrier.program_direct_kintex_7(bitfilepath=bitfilepath,device_choices=None)
#
#def usage():
#	print "python prc.py -a $IP [-r [-b bitfile] ]"
#
#if __name__ == "__main__":
#	opts, args = getopt.getopt(sys.argv[1:], 'ha:p:rb:m:s:', ['help', 'addr=', 'port=', 'reset', 'scan='])
#	ip_addr = '192.168.21.11'
#	port = 50006
#	reset = False
#	regmappath = './live_prc_regmap.json'
#	bitfilepath = None
#	do_scan = False
#	for opt, arg in opts:
#		if opt in ('-h', '--help'):
#			usage()
#			sys.exit()
#		elif opt in ('-a', '--address'):
#			ip_addr = arg
#		elif opt in ('-p', '--port'):
#			port = int(arg)
#		elif opt in ('-r', '--reset'):
#			reset = True
#		elif opt in ('-b', '--bitfile'):
#			bitfilepath = arg
#		elif opt in ('-m', '--regMapfile'):
#			regmappath = arg
#		elif opt in ('-s', '--scan'):
#			do_scan = True
#			scan_incr = int(arg)
#	prc = c_prc(ip_addr, 50006, regmappath=regmappath, bitfilepath=bitfilepath, reset=reset)
#	if do_scan:
#		prc.pntest3(scan_incr)
#	onewire_status(prc, 0x150000, "Upconverter  ")
#	onewire_status(prc, 0x151000, "Downconverter")
#
#
if __name__=="__main__":
	b=c_bmb7(ip='192.168.165.41',port=50006,reset=False,powercycle=True,bitfilepath='')#../gun.bit')
