# Panel programme
#
# Created: March 2015
#      by: Manolo Broseta at ALBA Computing Division
#

import time, sys, select, math
from paneldrv import *
from image_res import *
from alin import alindev

DEVNAME = 'a1ba:608'

class Panel():
	def __init__(self, parent=None):
		self.drv = PanelDriver()
		
		self.panel_brightness = 0
		self.panel_illumination = False
		
		self.drv.SetProtocol(32,10)
		
		
		self.device = alindev.alinDevice(DEVNAME)

		# Load binary file
			# Enable ADC 
		self.device.writeAttribute('CTL_FSM_CMD',0x01)
			
		self.ch_address = { "ch1": {'add':'ADC_CH1', 'pos':(5,17)},
							"ch2": {'add':'ADC_CH2', 'pos':(5,29)},
							"ch3": {'add':'ADC_CH3', 'pos':(5,41)},
							"ch4": {'add':'ADC_CH4', 'pos':(5,53)},
							"ch5": {'add':'ADC_CH5', 'pos':(70,17)},
							"ch6": {'add':'ADC_CH6', 'pos':(70,29)},
							"ch7": {'add':'ADC_CH7', 'pos':(70,41)},
							"ch8": {'add':'ADC_CH8', 'pos':(70,53)}
							}
		
			
	def ProcessData(self,arg):
		if arg is not None and len(arg)>0:
			if arg[0] == DC1_BYTE:	
				data_len = arg[1]
				if data_len>0:
					if DEBUG:
						print "I2C_READ_DATA= ",
						for el in arg[2:data_len]:
							print hex(el)+",",
						print
					
					if data_len>DATA_LEN: data_len=DATA_LEN
					r_data = [chr(el) for el in arg[2:data_len]]
					r_data = ''.join(r_data)
					r_data = r_data.split('\x1b')
					for data in r_data:
						try:
							if data[0] == 'H':
								if ord(data[2]) == 0x01:
									x=0
									try:
										x = ord(data[3])
									except:
										pass
									y=0
									try:
										y = ord(data[4])
									except:
										pass
									print "Press X=%s Y=%s"%(str(x),str(y))
									self.PrintPressed(x, y)
								elif ord(data[2]) == 0x00 or ord(data[2]) == 0x02:
									#self.PrintReleased()
									pass
						except:
							pass
		
		if not self.displayed_logo:
			self.drv.SendData('#ZF 2')
			self.drv.SendData('#ZB 0')
			self.drv.SendData('#ZZ 1,2')
			self.drv.SendData('#ZL 5,0, ALBA-EM\sADC\sChannels\n')	
			self.drv.SendData('#ZF 1')
			self.drv.SendData('#ZZ 1,2')
			for idx, el in self.ch_address.iteritems():
				value = self.getChannel(el['add'])
				text_val = str(value)
				text = idx+":\s"+text_val[:8]+"\n"
				x = el['pos'][0]
				y = el['pos'][1]
				text = "#ZL "+str(x)+","+str(y)+","+text
				self.drv.SendData(text)
							
	def getChannel(self, ch):
		readch = self.device.readAttribute(ch)
		if readch>0x7fffffff:
			readch-=0x100000000
		readch = round((readch*10)/131072.,6)

		return readch
		
	def PrintPressed(self, x=0,y=0):
		self.Logo_set(False)
		
	def Panel_set(self, bright=100, illumination=True):
		self.panel_brightness = bright
		self.panel_illumination = illumination
		self.drv.PanelSettings(self.panel_brightness, self.panel_illumination)		
		
	def Logo_display(self):
		self.drv.ClearScreen()
		# Delete cursor
		self.drv.SendData('#TC 0')
		# Set Panel brightness and illumination
		self.Panel_set(bright= 100)
		# Draw Alba Logo
		self.drv.DrawImage(0,0,Alba_logo)
		# Set tocuh screen area
		self.drv.SendData('#AH 0,0,127,64')
		self.drv.SendData('#AA 0')		
		self.drv.SendData('#AA 1')	
		
		self.wellcome_disp_counter = 0
		self.displayed_logo = True
		self.brightness_counter = 0	

	def Logo_set(self,status=True):
		if status and not self.displayed_logo:
			self.Logo_display()
			self.displayed_logo = True
		elif not status:
			self.Panel_set(bright=100)
			self.brightness_counter = 0
			if self.displayed_logo:
				self.drv.ClearScreen()
				#self.drv.SendData("#YS 2") # Buzzer								
				self.displayed_logo = False			
		else:
			# do nothing if:
			# - request to display Logo, but Logo already in screen
			pass
		
	def Logo_refresh_control(self):
		self.wellcome_disp_counter += 1
		self.brightness_counter += 1
		
		if self.wellcome_disp_counter > 120:
			self.wellcome_disp_counter = 0			
			self.Logo_set(True)
			
		if self.brightness_counter > 60 and self.panel_brightness > 100:
			self.Panel_set(bright=50)
		elif self.brightness_counter > 90 and self.panel_brightness > 20:
			self.Panel_set(bright=20)
		elif self.brightness_counter > 180 and self.panel_illumination:
			self.Panel_set(bright=10)
			
	def TouchQuery(self):
		self.Logo_display()		
		
		while 1:
			
			ret_val = self.drv.GetData()
			self.ProcessData(ret_val)
			
			time.sleep(1)
			self.Logo_refresh_control()

				

if __name__ == "__main__":
	
	
	import sys, select
	
	args = ' '.join(sys.argv[1:])
	
	Work = Panel()
	Work.TouchQuery()	
	sys.exit()

	
		
	
