#! /bin/env python
#-------------------------------------------------------------------
#
#  File:     RmMotorFrame.py
#  Purpose:  Motor Display Frame
#  Created:  June 22, 2000
#  Author:   Lionel PEYRICHOUX
#
#-------------------------------------------------------------------

from Tkinter import *
from CaChannel import *
from Dialog import Dialog
from ConfigMotor import *
from Canvas import *
 
 
#===============================================================
# 
# Description of each detector :
# 	* Name,
#	* Position : Top, Bottom, Inside or Outside
#	* Rack Monitor Output : 1,2,3,4,11,12,13 or 14
#	* Connector Output : 1 (P08) or 2 P(02)
#	* Rack Monitor Input : 1,2,3,4,11,12,13 or 14
#	* Connector Input : 0 (P03) or 3 (P07)
#	* Channel Input : 0 (1 to 7) or 1 (8 to 14)
#	* Rack Monitor LVDT : 1,2,3,4,11,12,13 or 14
#	* Channel LVDT  : 32, 33, 34 or 35
#	* key
 
#----------------------------------------------------
# 
#	Modification de la configuration des pots
#	afin d'eviter les erreurs de communication 
#	avec les racks monitors
#
#	Les dipoles D1,D2 sont correctement configures.
#
#	Les quadrupoles A1 et A2 ne sont pas encore 
#	installes. La configuration sera la meme que
#	pour les quadrupoles P1 et P2.
#
#	Le quadrupole P1 sera connecte au prochain
#	shutdown (09/28/00). P2 n'etant pas pret, on 
#	utilisera la configuration de P1.
#
#	LES MAUVAISES CONFIGURATIONS SONT MARQUEES PAR #
#
#----------------------------------------------------

Pot = (('D2',  'Inside',  1, 1, '01', 3, 0,  1, 33,  0),
       ('D1',  'Inside',  1, 2, '01', 3, 1,  1, 32,  1),
       ('A2',     'Top', 11, 1, '11', 1, 0, 11, 32,  2), #
       ('A2',  'Bottom', 11, 2, '11', 1, 1, 11, 33,  3), #
       ('A2', 'Outside', 12, 1, '12', 3, 1, 11, 34,  4), #
       ('A2',  'Inside', 12, 2, '12', 1, 1, 11, 35,  5), #
       ('A1',     'Top', 11, 1, '11', 1, 0, 11, 32,  6), #
       ('A1',  'Bottom', 11, 2, '11', 1, 1, 11, 33,  7), #
       ('A1', 'Outside', 12, 1, '12', 0, 0, 11, 34,  8), #
       ('A1',  'Inside', 12, 2, '12', 1, 1, 11, 35,  9), #
       ('P1',     'Top', 11, 1, '11', 3, 0, 11, 32, 10),
       ('P1',  'Bottom', 11, 2, '11', 3, 1, 11, 33, 11),
       ('P1', 'Outside', 12, 1, '12', 3, 0, 11, 34, 12),
       ('P1',  'Inside', 12, 2, '12', 3, 1, 11, 35, 13),
       ('P2',     'Top', 11, 1, '11', 3, 0, 11, 32, 14), #
       ('P2',  'Bottom', 11, 2, '11', 3, 1, 11, 33, 15), #
       ('P2', 'Outside', 12, 1, '12', 3, 0, 11, 34, 16), #
       ('P2',  'Inside', 12, 2, '12', 3, 1, 11, 35, 17)) #

# End of configuration of each detector
#
#=============================================================== 

#===============================================================
#
# Description of each Rack Monitor :
# 	* Name

#----------------------------------------------------
# 
#	Modification de la configuration pour eviter
#       les messages d'erreurs des rack monitors non
#	connectes (03,04,13,14)
#
#	LES MAUVAISES CONFIGURATIONS SONT MARQUEES PAR #
#
#----------------------------------------------------

RackMonitor =  ('CTL_RM_02-01',  
		'CTL_RM_02-01', #
		'CTL_RM_02-01', #
		'CTL_RM_02-01', #
		'CTL_RM_02-11', 
		'CTL_RM_02-12', 
		'CTL_RM_02-11', #
		'CTL_RM_02-12', #
		'CTL_RM_02-05', # Smoke Detector to the Dipoles
		'CTL_RM_02-15') # Smoke Detector to P1

# End of the description of each Rack Monitor
#
#=============================================================== 

#===============================================================
#
# Drawing Pot

DrPot = ((67,380, 87,390),	# D2 Inside
	(139,344,159,354),	# D1 Inside
	(226,223,236,243),	# A2 Top
	(226,323,236,343),	# A2 Bottom
	(171,278,191,288),	# A2 Outside
	(271,278,291,288),	# A2 Inside
	(322,175,332,195),	# A1 Top
	(322,275,332,295),	# A1 Bottom
	(267,230,287,240),	# A1 Outside
	(367,230,387,240),	# A1 Inside
	(490, 91,500,111),	# P1 Top
	(490,191,500,211),	# P1 Bottom
	(435,146,455,156),	# P1 Outside
	(535,146,555,156),	# P1 Inside
	(586, 43,596, 63),	# P2 Top
	(586,143,596,163),	# P2 Bottom
	(531, 98,551,108),	# P2 Outside
	(631, 98,651,108))	# P2 Inside

# End of Drawing Pot 
#
#=============================================================== 

#===============================================================
#
# ErrorRackMonitor : 
#	* size = 8
#	* association ErrorRackMonitor[i]:
#		- i=0 => CTL_RM_02-01
#		- i=1 => CTL_RM_02-02
#		- i=2 => CTL_RM_02-03
#		- i=3 => CTL_RM_02-04
#		- i=4 => CTL_RM_02-11
#		- i=5 => CTL_RM_02-12
#		- i=6 => CTL_RM_02-13
#		- i=7 => CTL_RM_02-14
#	* ErrorRackMonitor[]=0 => Rack monitor ok
#	* ErrorRackMonitor[]=1 => error of communication or 
#				error status of the rack monitor

ErrorRackMonitor=[]

# End of ErrorRackMonitor
#
#=============================================================== 

#===============================================================
#
# ErrorInput :
#	* size = 18 (motors) * 3 (errors/motors)
#	* ErrorInput[i]=1 =>
#	* ErrorInput[i+1]=1 =>
#	* ErrorInput[i+2]=1 =>

ErrorInput=[]

# End of ErrorInput
#
#=============================================================== 

#===============================================================
#
# TestOneMotor :
#	* size = 18

TestOneMotor=[]

# End of TestOneMotor
#
#=============================================================== 

#===============================================================
#
# OutputRM :
#	* size = 18

OutputRM=[]

# End of OutputRM
#
#=============================================================== 

#===============================================================
#
# Canvas Class

class CanvasDisplay:


	def __init__(self,parent):
			
		self.display=Canvas(parent,width=640,height=480,relief=GROOVE,bd=4)
		
		self.item=[]
		self.beam=[]
		
		for i in range(len(DrPot)):
		
			self.item.insert(i,self.display.create_rectangle(DrPot[i][0],DrPot[i][1],DrPot[i][2],DrPot[i][3],fill='red',outline='black'))
		
		for i in range(30):
			self.beam.insert(i*2,self.display.create_polygon(7+i*12,389-i*6,13+i*12,386-i*6,16+i*12,392-i*6,14+i*12,398-i*6,8+i*12,401-i*6,10+i*12,395-i*6,fill='blue'))
			self.beam.insert(i*2+1,self.display.create_polygon(13+i*12,386-i*6,19+i*12,383-i*6,22+i*12,389-i*6,20+i*12,395-i*6,14+i*12,398-i*6,16+i*12,392-i*6,fill='black'))

		for j in range(30,45):
			i=j-30
			self.beam.insert(i*2,self.display.create_polygon(631-i*12,77+i*6,637-i*12,74+i*6,634-i*12,80+i*6,636-i*12,86+i*6,630-i*12,89+i*6,628-i*12,83+i*6,fill='brown'))
			self.beam.insert(i*2+1,self.display.create_polygon(625-i*12,80+i*6,631-i*12,77+i*6,628-i*12,83+i*6,630-i*12,89+i*6,624-i*12,92+i*6,622-i*12,86+i*6,fill='black'))
		
		self.display.create_text(410,195,text='D0')
			
		self.display.bind("<Button-1>",self.ChoicePot)
		
		self.display.pack(side=TOP)
		self.NumInput = 0
		self.beam_color=0

		return
			
	def update(self):

#		for i in range(20):
#			if self.beam_color == 0:
#				self.display.itemconfigure(self.beam[i*2],fill='blue')
#				self.display.itemconfigure(self.beam[i*2+1],fill='black')
#				self.display.itemconfigure(self.beam[20+i*2],fill='brown')
#				self.display.itemconfigure(self.beam[20+i*2+1],fill='black')
#			else:
#				self.display.itemconfigure(self.beam[i*2],fill='black')
#				self.display.itemconfigure(self.beam[i*2+1],fill='blue')
#				self.display.itemconfigure(self.beam[20+i*2],fill='black')
#				self.display.itemconfigure(self.beam[20+i*2+1],fill='brown')

		if self.beam_color==0:
			self.beam_color=1
		else:
			self.beam_color=0
		
		
		for i in range(len(Pot)):
			
			if Pot[i][7]>10:
				NumRM = Pot[i][7] - 10
			else:
				NumRM = Pot[i][7]

			if ErrorRackMonitor[NumRM] == 0:

				self.__AD=CaChannel()
				self.__AD.searchw('CTL_RM_02-' + str('%02d' % NumRM) + '.AD')

				g=self.__AD.getw()

				if (Pot[i][1]=='Top'):
					x=0
					y=(0.0048828125*float(g[Pot[i][8]]) + 10)*1.5
				elif (Pot[i][1]=='Bottom'):
					x=0
					y=-(0.0048828125*float(g[Pot[i][8]]) + 10)*1.5
				elif (Pot[i][1]=='Inside'):
					x=-(0.0048828125*float(g[Pot[i][8]]) + 10)*1.5
					y=0
				else:
					x=(0.0048828125*float(g[Pot[i][8]]) + 10)*1.5
					y=0

				del g

				self.display.coords(self.item[i],DrPot[i][0]+x,DrPot[i][1]+y,DrPot[i][2]+x,DrPot[i][3]+y)
		
			if (ErrorInput[i*3] + ErrorInput[i*3+1] + ErrorInput[i*3+2]) != 0:
				color='red'
			else:
				if TestOneMotor[i].get() == 1:
					color='green'
				else:
					color='orange'
								
			self.display.itemconfigure(self.item[i],fill=color,outline='black')

		return self.NumInput
		
	def ChoicePot(self,event):

		try:
			tag=self.display.find_withtag('current')[0]-1
		except:
			return
		
		if tag<len(Pot):
			self.NumInput = Pot[tag][9]
		
		return
 
class ErrorFrame(Frame):

	def __init__(self,
		     parent):

		Frame.__init__(self,parent,relief=GROOVE,bd=4)

		self.parent=parent

		self.error=0
		
		for i in range(len(RackMonitor)):
			ErrorRackMonitor.insert(i,0)

		for i in range(len(Pot)):
			ErrorInput.insert(i*3,0)
			ErrorInput.insert(i*3+1,0)
			ErrorInput.insert(i*3+2,0)
			OutputRM.insert(i,0)
							
	def Dialog_Failure(self):
	
		top=self.top=Toplevel(self.parent)
		
		self.Dialog_Failure_text = self.Dialog_Failure_text + chr(13)

 		Label(top,text=self.Dialog_Failure_text).pack()
		
 #  		Dialog(self, title = 'Failures',
#	   		text  = self.Dialog_Failure_text,
#	   		bitmap= 'error', default=0, strings=('OK',))
 
		Button(top,text='OK', command=self.ok).pack()
 
    		return

	def ok(self):
	
		self.top.destroy()
		
		return


	def update(self):
	
		self.error=0
		self.Dialog_Failure_text=''

		for i in range(len(RackMonitor)):

			self.__DSTAT=CaChannel()
			self.__DSTAT.searchw(RackMonitor[i] + '.DSTAT')

			d=self.__DSTAT.getw()
			
			if (d != 0):
				if ErrorRackMonitor[i] == 0:
					self.error=1
					ErrorRackMonitor[i]=1
					self.Dialog_Failure_text=self.Dialog_Failure_text + 'Error accessing Rack Monitor : ' + RackMonitor[i] + chr(13)
			else:
				ErrorRackMonitor[i]=0
			del d

		for i in range(len(Pot)):
		
			if int(Pot[i][4]) < 10:
				NumPot = int(Pot[i][4])-1
			else:
				NumPot = int(Pot[i][4])-7
			
			if ErrorRackMonitor[NumPot] == 0:
			
				NameRM = 'CTL_RM_02-' + Pot[i][4] + '.BIN'
		
				self.Dialog_Failure_Pot_text = ''

				self.__BIN=CaChannel()
				self.__BIN.searchw(NameRM)
				
				g=self.__BIN.getw()
				
				if Pot[i][6] == 0:
					InputData=g[Pot[i][5]] & 0x007f
				else:
					InputData=(g[Pot[i][5]] & 0x3f80) / 0x007f
		
				if ((InputData & 0x0010) == 16):
					if ErrorInput[i*3+1] == 0:
						self.error=1
						ErrorInput[i*3+1]=1
						self.Dialog_Failure_Pot_text = self.Dialog_Failure_Pot_text + '   Mechanical Failure' + chr(13)
						OutputRM[i]=0
				else:
					ErrorInput[i*3+1]=0
		
				if ((InputData & 0x0001) == 1):
					if ErrorInput[i*3] == 0:
						self.error=1
						ErrorInput[i*3]=1
						self.Dialog_Failure_Pot_text = self.Dialog_Failure_Pot_text + '   Cable Failure' + chr(13)
						OutputRM[i]=0
				else:
					ErrorInput[i*3]=0

				if ((InputData & 0x0020) != 32):
					if ErrorInput[i*3+2] == 0:
						self.error=1
						ErrorInput[i*3+2]=1
						self.Dialog_Failure_Pot_text = self.Dialog_Failure_Pot_text + '   Driver Failure' + chr(13)
						OutputRM[i]=0
				else:
					ErrorInput[i*3+2]=0
		
				del g

				if (self.Dialog_Failure_Pot_text != ''):
					self.Dialog_Failure_text = self.Dialog_Failure_text + Pot[i][0] + ' ' + Pot[i][1] + chr(13) + self.Dialog_Failure_Pot_text
				 
			else:
				ErrorInput[i*3]=1
				ErrorInput[i*3+1]=1
				ErrorInput[i*3+2]=1
				OutputRM[i]=0

		if (self.error==1):
			self.Dialog_Failure()
			self.error=0

		return
 
class InfoFrame(Frame):
	
	__Connector = ('P03','P08','P02','P07')
	
	def __init__(self,parent,NumInput=None):
	
		Frame.__init__(self,parent,relief=GROOVE,bd=4)
		
		self.__CreateFrame()
 		
		return
		
	def __CreateFrame(self):
		
		f = Frame(self)
		
		l = Label(f, text='INPUT').grid(row=0, column=0, sticky=W)
		
		l = Label(f, text='  RM:').grid(row=1, column=0, sticky=W)		
		self.__RMInput=Label(f,relief=GROOVE,width=14)
		self.__RMInput.grid(row=1, column=1, sticky=W)

		l = Label(f, text='  Connector:').grid(row=2, column=0, sticky=W)
		self.__ConnectorInput=Label(f,relief=GROOVE,width=14)
		self.__ConnectorInput.grid(row=2, column=1, sticky=W)

		l = Label(f, text='  Channel:').grid(row=3, column=0, sticky=W)
		self.__ChannelInput=Label(f,relief=GROOVE,width=14)
		self.__ChannelInput.grid(row=3, column=1, sticky=W)

		l = Label(f, text='OUTPUT').grid(row=4, column=0, sticky=W)

		l = Label(f, text='  RM:').grid(row=5, column=0, sticky=W)
		self.__RMOutput=Label(f,relief=GROOVE,width=14)
		self.__RMOutput.grid(row=5, column=1, sticky=W)		

		l = Label(f, text='  Connector:').grid(row=6, column=0, sticky=W)
		self.__ConnectorOutput=Label(f,relief=GROOVE,width=14)
		self.__ConnectorOutput.grid(row=6, column=1, sticky=W)

		l = Label(f, text='LVDT').grid(row=7, column=0, sticky=W)

		l = Label(f, text='  RM:').grid(row=8, column=0, sticky=W)
		self.__RMLVDT=Label(f,relief=GROOVE,width=14)
		self.__RMLVDT.grid(row=8, column=1, sticky=W)		

		l = Label(f, text='  Channel:').grid(row=9, column=0, sticky=W)
		self.__ChannelLVDT=Label(f,relief=GROOVE,width=14)
		self.__ChannelLVDT.grid(row=9, column=1, sticky=W)
	
		f.pack()
	
		return
		
	def update(self,NumInput=None):
	
		self.__RMInput.config(text='CTL_RM_02-' + Pot[NumInput][4])
		self.__ConnectorInput.config(text=self.__Connector[Pot[NumInput][5]])
		if Pot[NumInput][6]==0:
			self.__ChannelInput.config(text='1 to 7')
		else:
			self.__ChannelInput.config(text='8 to 14')
		self.__RMOutput.config(text='CTL_RM_02-' + ('%02d' % Pot[NumInput][2]))
		self.__ConnectorOutput.config(text=self.__Connector[Pot[NumInput][3]])
		self.__RMLVDT.config(text='CTL_RM_02-' + str('%02d' %Pot[NumInput][7]))
		self.__ChannelLVDT.config(text=Pot[NumInput][8])
		
		return

class InputFrame(Frame):

	def __init__(self,
		     parent):
		     
		Frame.__init__(self,parent,relief=GROOVE,bd=4)
		
		self.failure = 0
		
		self.__CreateFrame()	
		
		return
			
	def __CreateFrame(self):
	
		f = Frame(self)
		
		l = Label(f, text='Name').grid(row=0, column=0, sticky=W)
		self.__NameLabel=Label(f,relief=GROOVE,width=11)
		self.__NameLabel.grid(row=0, column=1, sticky=W)

		l = Label(f, text='Orientation').grid(row=1, column=0, sticky=W)
		self.__OrientationLabel=Label(f,relief=GROOVE,width=11)
		self.__OrientationLabel.grid(row=1, column=1, sticky=W)

		l = Label(f, text='Status').grid(row=2, column=0, sticky=W)
		self.__StatusLabel=Label(f,relief=GROOVE,width=11)
		self.__StatusLabel.grid(row=2, column=1, sticky=W)

		l = Label(f, text='POSITION').grid(row=3, column=0, sticky=W)

		l = Label(f, text='  Current').grid(row=4, column=0, sticky=W)
		self.__PositionLabel=Label(f,relief=GROOVE,width=11)
		self.__PositionLabel.grid(row=4, column=1, sticky=W)		

		l = Label(f, text='  Home').grid(row=5, column=0, sticky=W)
		self.__HomePosLabel=Label(f,relief=GROOVE,width=11)
		self.__HomePosLabel.grid(row=5, column=1, sticky=W)

		l = Label(f, text='  In').grid(row=6, column=0, sticky=W)
		self.__InPos=Label(f,relief=GROOVE,width=11)
		self.__InPos.grid(row=6, column=1, sticky=W)

		l = Label(f, text='FAILURES').grid(row=7, column=0, sticky=W)
		
		l = Label(f, text='  Cable').grid(row=8, column=0, sticky=W)
		self.__CabFailure=Label(f,relief=GROOVE,width=11)
		self.__CabFailure.grid(row=8, column=1, sticky=W)

		l = Label(f, text='  Driver').grid(row=9, column=0, sticky=W)
		self.__DrFailure=Label(f,relief=GROOVE,width=11)
		self.__DrFailure.grid(row=9, column=1, sticky=W)

		l = Label(f, text='  Mechanical').grid(row=10, column=0, sticky=W)
		self.__MecFailure=Label(f,relief=GROOVE,width=11)
		self.__MecFailure.grid(row=10, column=1, sticky=W)

		f.pack()

		return
	
	def update(self,
		   NumInput = None):
				
		self.__BIN=CaChannel()
		self.__BIN.searchw('CTL_RM_02-' + Pot[NumInput][4] + '.BIN')

		g=self.__BIN.getw()
		
		if Pot[NumInput][6] == 0:
			InputData=g[Pot[NumInput][5]] & 0x007f
		else:
			InputData=(g[Pot[NumInput][5]] & 0x3f80) / 0x007f
		self.__NameLabel.config(text=Pot[NumInput][0])
		self.__OrientationLabel.config(text=Pot[NumInput][1])


		if ((InputData & 0x0001) == 1):
			self.__CabFailure.config(text='YES')
		else:
			self.__CabFailure.config(text='NO')
		
		if ((InputData & 0x0002) == 2):
			self.__HomePosLabel.config(text='YES')
		else:
			self.__HomePosLabel.config(text='NO')
		
		if ((InputData & 0x0004) == 4):
			self.__InPos.config(text='YES')
		else:
			self.__InPos.config(text='NO')
		
		if ((InputData & 0x0008) == 8):
			self.__StatusLabel.config(text='RUN')
		else:
			self.__StatusLabel.config(text='STOP')
		
		if ((InputData & 0x0010) == 16):
			self.__MecFailure.config(text='YES')
		else:
			self.__MecFailure.config(text='NO')
		
		if ((InputData & 0x0020) != 32):
			self.__DrFailure.config(text='YES')
		else:
			self.__DrFailure.config(text='NO')
		
		del g
		
		self.__AD=CaChannel()
		self.__AD.searchw('CTL_RM_02-' + str('%02d' %Pot[NumInput][7]) + '.AD')

		g=self.__AD.getw()

		self.__PositionLabel.config(text=str('%6.2f' %((0.0048828125*float(g[Pot[NumInput][8]])+10)*2)))
							
		del g

		
#		import shelve
#		
#		dbase=shelve.open('databaseMotor','c')
#		
#		print ctime(time())
							
		return	
		
	def destroy(self):
		
		del self.__BIN
		Frame.destroy(self)
		
		return
 
class OutputFrame(Frame):

	__SpeedParams = ('Low ','High')

	def __init__(self,
		     parent,NumInput=None):
		     				
		Frame.__init__(self,parent,relief=GROOVE,bd=4)
				
		self.textOneMotorButton=StringVar()
		self.textOneMotorButton.set("One motor")
		self.__CreateFrame()
		self.NewPosition = '0'
		self.HomePosition = 0
		self.__SpeedChoice.set(self.__SpeedParams[0])
		self.NumInput=NumInput
		
		for i in range(len(Pot)):
			TestOneMotor.insert(i,IntVar())
			TestOneMotor[i].set(0)
		
		return
	
	def __NewValue(self,event):
	
		self.NewPosition = event.widget.get()
				
		self.__UnlockValue(event)
		
		return
		
	def __LockValue(self, event):
	
		self.__NewPos.lock = 1
		self.__NewPos.config(bg = 'lightgoldenrod1')
		
		return
		
	def __UnlockValue(self, event):
	
		self.__NewPos.lock = 0
		self.__NewPos.config(bg = 'lightgray')
	
		return
	
	def __CreateFrame(self):
	
		f = Frame(self)
		
		l = Label(f,text='New Position :').grid(row=0, column=0, sticky=W)
		self.__NewPos = Entry(f,relief=GROOVE,width=11)
		self.__NewPos.lock=0
#		self.__NewPos.bind("<Double-Button-1>",self.__b1Callback)
		self.__NewPos.bind('<FocusIn>', self.__LockValue)
		self.__NewPos.bind('<FocusOut>', self.__UnlockValue)
		self.__NewPos.bind('<Return>',self.__NewValue)
		self.__NewPos.grid(row=0, column=1, sticky=W)
		
		l = Label(f,text='Speed :').grid(row=1, column=0, sticky=W)
		self.__SpeedIndex=IntVar()
		self.__SpeedChoice=StringVar()
		b=OptionMenu(f,self.__SpeedChoice, "0")
		b.config(relief=GROOVE)
		b.grid(row=1, column=1, sticky=W)
		m = Menu(b)
		m.add_radiobutton(label=self.__SpeedParams[0],variable=self.__SpeedIndex,
				  value=0,command=self.__SpeedSet)
		m.add_radiobutton(label=self.__SpeedParams[1],variable=self.__SpeedIndex,
				  value=1,command=self.__SpeedSet)
		self.__SpeedLabel = b
		self.__SpeedMenu = m
		b['menu'] = m
	
		f.pack()
	
		f = Frame(self,relief=GROOVE)
	
		b = Button(f,text='Run',command=self.Run)
		b.pack(side=LEFT,expand=YES)

		b = Button(f,text='Stop',command=self.StopMotor)
		b.pack(side=RIGHT,expand=YES)

		f.pack(side=TOP,expand=YES,fill=X)
		f = Frame(self,relief=GROOVE)

		b = Button(f,text='Home',command=self.Home)
		b.pack()
		self.__HomeButton=b
	
#		self.__TestOneMotorButton = Button(f,textvariable=self.textOneMotorButton,command=self.Test)
#		self.__TestOneMotorButton.pack(side=LEFT)

		f.pack(side=TOP,expand=YES,fill=X)

		return	
		
	def __SpeedSet(self):
	
		MenuChoice = self.__SpeedIndex.get()
		self.__SpeedChoice.set(self.__SpeedParams[MenuChoice])
		
		return

	
#	def Test(self):
#
#		TestOneMotor[0]=0
#		
#		if self.textOneMotorButton.get()=='One motor':
#			self.textOneMotorButton.set('All motors')
#			TestOneMotor[0] = self.NumInput
#		else:
#			self.textOneMotorButton.set('One motor')
#				
#		return
	
	def StopMotor(self):

		word = 0
		val = word & 0xffff
		
		for i in range(len(Pot)):
			OutputRM[i]= val 
		
		self.HomePosition = 0

		return

	def Run(self):
		
		try:
			int(self.NewPosition)
		except:
			if (self.NewPosition == ''):
 				text = 'You must enter a position'
			else:
				text = 'The new position must be an integer.'
			Dialog(self,
			       title = 'Error',
			       text = text,
			       bitmap = 'error',
			       strings=  ('OK',),
			       default = 0)
			self.NewPosition = ''
			self.__NewPos.delete(0,'end')
			return

		if (int(self.NewPosition) > 8191):
		
			Dialog(self,
			       title = 'Error',
			       text = 'New position > 8191 mm',
			       bitmap = 'error',
			       strings=  ('OK',),
			       default = 0)
			       
			return
		
		if (int(self.NewPosition) < 0):
		
			Dialog(self,
			       title = 'Error',
			       text = 'New position < 0',
			       bitmap = 'error',
			       strings=  ('OK',),
			       default = 0)
			       
			return
				
			
		if self.HomePosition == 1:
			word=self.HomePosition * 32768 + self.__SpeedIndex.get()*16384
		else:
			word = self.__SpeedIndex.get()*16384  + 8192 + int(self.NewPosition) #*1000*3/25
			
		if (self.NewPosition == '0'):
			text = 'Home Position'
		else:
			text = 'New Position : %d mm' %(int(self.NewPosition))
		
		for i in range(len(Pot)):
			if TestOneMotor[i].get() == 1:
			
				text=text + chr(13) + '   ' + Pot[i][0] + ' ' + Pot[i][1]
			
		ans = Dialog(self,
			     title = 'New Position',
			     text = text,
			     bitmap = 'question',
			     strings=('YES','NO'),default=0)
			
		if ans.num == 0:

			for i in range(len(Pot)):
				if TestOneMotor[i].get() == 1:
			
					if (ErrorInput[i*3] + ErrorInput[i*3+1] + ErrorInput[i*3+2]) == 0:
						val=word & 0xffff
						OutputRM[i]=val
						print val
				
			self.HomePosition = 0
		return

	def Home(self):
        
		self.HomePosition=1
		self.NewPosition = '0'
		self.Run()
		return

	def destroy(self):

		Frame.destroy(self)
		return

	def update(self,NumInput=None):
					
		for i in range(len(Pot)):
			
			if Pot[i][2]>10:
				NumRM = Pot[i][2] - 10
			else:
				NumRM = Pot[i][2]
			
			if ErrorRackMonitor[NumRM] == 0:
				pv=CaChannel()
				pv.searchw('CTL_RM_02-' + ('%02d' % Pot[i][2]) + '.BIN' + ('%02d' % Pot[i][3]))
				pv.putw(OutputRM[i])

				del pv
				
		return

class ChoiceMotorFrame(Frame):
	
	
	def __init__(self,parent):
	
		Frame.__init__(self,parent,relief=GROOVE,bd=4)
		
		self.textButton=StringVar()
		self.textButton.set("Run")
		
		self.__CreateFrame()

		return
		
	def __CreateFrame(self):
	
		f = Frame(self)
		f.pack(side=TOP,fill=X)
		
		Label(f,text='D2 :').grid(row=0, column=0, sticky=W)
		Label(f,text='Inside :').grid(row=0, column=1, sticky=W)
		self.D1I= Checkbutton(f,variable=TestOneMotor[0],
					selectcolor='green').grid(row=0, column=2, sticky=W)

		Label(f,text='D1 :').grid(row=1, column=0, sticky=W)
		Label(f,text='Inside :').grid(row=1, column=1, sticky=W)
		self.D2I= Checkbutton(f,variable=TestOneMotor[1],
					selectcolor='green').grid(row=1, column=2, sticky=W)

		
		Label(f,text='A2 :').grid(row=2, column=0, sticky=W)

		Label(f,text='Top :').grid(row=2, column=1, sticky=W)
		self.A2T= Checkbutton(f,variable=TestOneMotor[2],
					selectcolor='green').grid(row=2, column=2, sticky=W)
		Label(f,text='Bottom :').grid(row=3, column=1, sticky=W)
		self.A2B= Checkbutton(f,variable=TestOneMotor[3],
					selectcolor='green').grid(row=3, column=2, sticky=W)
		Label(f,text='Outside :').grid(row=4, column=1, sticky=W)
		self.A2O= Checkbutton(f,variable=TestOneMotor[4],
					selectcolor='green').grid(row=4, column=2, sticky=W)
		Label(f,text='Inside :').grid(row=5, column=1, sticky=W)
		self.A2I= Checkbutton(f,variable=TestOneMotor[5],
					selectcolor='green').grid(row=5, column=2, sticky=W)


		Label(f,text='A1 :').grid(row=6, column=0, sticky=W)

		Label(f,text='Top :').grid(row=6, column=1, sticky=W)
		self.A1T= Checkbutton(f,variable=TestOneMotor[6],
					selectcolor='green').grid(row=6, column=2, sticky=W)
		Label(f,text='Bottom :').grid(row=7, column=1, sticky=W)
		self.A1B= Checkbutton(f,variable=TestOneMotor[7],
					selectcolor='green').grid(row=7, column=2, sticky=W)
		Label(f,text='Outside :').grid(row=8, column=1, sticky=W)
		self.A1O= Checkbutton(f,variable=TestOneMotor[8],
					selectcolor='green').grid(row=8, column=2, sticky=W)
		Label(f,text='Inside :').grid(row=9, column=1, sticky=W)
		self.A1I= Checkbutton(f,variable=TestOneMotor[9],
					selectcolor='green').grid(row=9, column=2, sticky=W)

		
		Label(f,text='P1 :').grid(row=10, column=0, sticky=W)

		Label(f,text='Top :').grid(row=10, column=1, sticky=W)
		self.D1T= Checkbutton(f,variable=TestOneMotor[10],
					selectcolor='green').grid(row=10, column=2, sticky=W)
		Label(f,text='Bottom :').grid(row=11, column=1, sticky=W)
		self.D1B= Checkbutton(f,variable=TestOneMotor[11],
					selectcolor='green').grid(row=11, column=2, sticky=W)
		Label(f,text='Outside :').grid(row=12, column=1, sticky=W)
		self.D1O= Checkbutton(f,variable=TestOneMotor[12],
					selectcolor='green').grid(row=12, column=2, sticky=W)
		Label(f,text='Inside :').grid(row=13, column=1, sticky=W)
		self.D1I= Checkbutton(f,variable=TestOneMotor[13],
					selectcolor='green').grid(row=13, column=2, sticky=W)


		Label(f,text='P2 :').grid(row=14, column=0, sticky=W)

		Label(f,text='Top :').grid(row=14, column=1, sticky=W)
		self.D2T= Checkbutton(f,variable=TestOneMotor[14],
					selectcolor='green').grid(row=14, column=2, sticky=W)
		Label(f,text='Bottom :').grid(row=15, column=1, sticky=W)
		self.D2B= Checkbutton(f,variable=TestOneMotor[15],
					selectcolor='green').grid(row=15, column=2, sticky=W)
		Label(f,text='Outside :').grid(row=16, column=1, sticky=W)
		self.D2O= Checkbutton(f,variable=TestOneMotor[16],
					selectcolor='green').grid(row=16, column=2, sticky=W)
		Label(f,text='Inside :').grid(row=17, column=1, sticky=W)
		self.D2I= Checkbutton(f,variable=TestOneMotor[17],
					selectcolor='green').grid(row=17, column=2, sticky=W)
		
		return
		
	def update (self):
	
		return
		
class MenuFrame(Frame):

	def __init__(self, parent,quitCallback=None):
	
		Frame.__init__(self,parent,relief=GROOVE,bd=4)
		
		self.__CreateFrame(quitCallback)

		return

	def __CreateFrame(self,quitCallback):
	
		f = Frame(self)
		f.pack(side=TOP,fill=X)

		m = self.__actionMenu(self,quitCallback)
    		m.pack(side=LEFT)

    		m = self.__helpMenu(self)
    		m.pack(side=RIGHT)

		return	

  	def destroy(self):
    
    		Frame.destroy(self)
    		
		return

  	def __actionMenu(self,
		   parent,
		   quitCallback):

    		b = Menubutton(parent, text='Actions', underline=0, relief=GROOVE)
    		m = Menu(b)
   		m.add_command(label='Configuration',command= self.passwordFrame)
   		m.add_command(label='Quit', command=quit)
    		b['menu'] = m
    		return b

	def passwordFrame(self):
	
		top=self.top=Toplevel()

		top.grab_set()
		self.top.title('Password')
		
		Label(top,text="PassWord").pack()		

		self.e = Entry(top,show='*')
		self.e.pack(padx=5)
		
		b=Button(top,text="OK",command=self.okpassword)
		b.pack(pady=5)

	def okpassword(self):
	
		self.password=self.e.get()
	
		self.top.grab_release()
		self.top.destroy()

		self.__configmotor()	

		return
	

	def __configmotor(self):
			
		dbase = shelve.open('DataMotor')
		ConfigMotor(self,dbase,self.password)
	
		return

  	def __helpMenu(self,
		 	parent):

    		b = Menubutton(parent, text='Help', underline=0, relief=GROOVE)
    		m = Menu(b)        
    		m.add_command(label='Help', command=self.__help)
    		b['menu'] = m
    		return b
         
  	def __help(self):

    		Dialog(self, title = 'Not implemented',
	   		text  = '"The Gods help those who help themselves"',
	   		bitmap= 'error', default=0, strings=('OK',))
    		return


class InfoMotorFrame(Frame):

	def __init__(self,parent):
	
		Frame.__init__(self,parent)

		self.__CreateFrame()

		return

	def __CreateFrame(self):
	
		f = Frame(self)
		f.pack(side=TOP,expand=YES,fill=X)
		
		self.__inputFrame = InputFrame(self)
    		self.__inputFrame.pack(side=TOP, fill=X, expand=YES)
		
		self.__infoFrame = InfoFrame(self)
		self.__infoFrame.pack(side=TOP, fill=X, expand=YES)
 		
	def update(self,
		   NumInput = None):
	
		self.__inputFrame.update(NumInput)
		self.__infoFrame.update(NumInput)

class IOFrame(Frame):

	def __init__(self,parent):
	
		Frame.__init__(self,parent)

		self.__CreateFrame()

		return

	def __CreateFrame(self):
	
		f = Frame(self)
		f.pack(side=TOP,expand=YES,fill=X)
		
		self.__outputFrame = OutputFrame(self)
	    	self.__outputFrame.pack(side=TOP, fill=X, expand=YES)
		
		self.__choicemotorFrame = ChoiceMotorFrame(self)
		self.__choicemotorFrame.pack(side=TOP, fill=X, expand=YES)
		
		self.__errorFrame = ErrorFrame(self)
 		
	def update(self,
		   NumInput = None):
	
		self.__errorFrame.update()
		self.__outputFrame.update(NumInput)
		self.__choicemotorFrame.update()
		
		
class RmMotorFrame(Frame): 


  def __init__(self,
	       parent):

    	Frame.__init__(self, parent)        # Initialize the base class
	
	title = 'FPD - CTL_RM_02'
	self.master.title(title)

    	try:
		self.__createFrames(self) # Create component frames
    	except:
      		self.destroy()
      		raise
    	
	return
        
  def destroy(self):

	Frame.destroy(self)
	
	return

  def __createFrames(self,
		     parent):

	self.__MenuFrame = MenuFrame(parent)
	self.__MenuFrame.pack(side=TOP, fill=X)

	self.__ioframe = IOFrame(parent)
    	self.__ioframe.pack(side=LEFT, fill=X)

	self.__infomotorframe = InfoMotorFrame(parent)
	self.__infomotorframe.pack(side=RIGHT, fill=X)
	
	self.__canvasdisplay = CanvasDisplay(parent)	

	return

  def update(self):

	Num_Input = self.__canvasdisplay.update()
	self.__ioframe.update(Num_Input)
	self.__infomotorframe.update(Num_Input)

    	return



def quit():

  	global rmFrame, menuBar
  	
	ans = Dialog(title = 'Exit',
		     text = 'Are you sure you want to quit?',
		     bitmap = 'question',
		     strings = ('Yes','No',),default = 0)
		    
	if ans.num == 0:
	  	frame.destroy()
	
		exit()
		
	return

# Integrated test procedure

if (__name__== '__main__'): 


  	from sys import *

  	UpdatePeriod = 1000  # 1 second

  	def update():

    		global frame

    		frame.update()
    		frame.after(UpdatePeriod, update)
		
		return


	global frame
   	base = Tk()
	    	
	try:
		frame = RmMotorFrame(base)
	except:
		print 'Error Accessing Power PC: CTL_RM_02 (D0OLCTL02)'
		exit()

	frame.pack(fill=X, expand=YES,ipadx=0,ipady=0)       # Pack into topmost widget
	update()
	base.mainloop()