Skip to content
genFromTemplates.py 12 KiB
Newer Older
Gino Tosti's avatar
Gino Tosti committed
from Cheetah.Template import Template
from datetime import date
from GenDevice.excelIcd import excelIcd
import sys,os
import shutil as sh
from GenDevice.acsUtils import *
from GenDevice.createEmptyCDB import *

#OPC-UA:[ACS class,format,min value,max value, , ,Java object class]
datatype={"BOOLEAN":["boolean","b","0","1","boolean","boolean","Boolean"],
          "DOUBLE":["double","9.4lf","-1e50","1e50","double","double","Double"],
          "FLOAT":["float","9.4f","-1e20","1e20","float","float","Float"],
		  "INT16":["long","2d","-2147483648","2147483647","int","long","Integer"],
		  "INT32":["long","2d","-2147483648","2147483647","int","long","Integer"],
		  "INT64":["longLong","2d","-2147483648","2147483647","long","long long","Long"],
		  "STRING":["string","s","0","0","String","string","String"],
		  "BYTESTRING":["string","s","0","0","String","string","String"],
		  "BYTE":["long","2d","-127","127","int","long","Integer"],
		  "SBYTE":["long","2d","-127","127","int","long","Integer"],
		  "UINT16":["long","2d","-2147483648","2147483647","int","long","Integer"],
		  "UINT32":["longLong","2d","-2147483648","2147483647","long","long long","Long"],
		  "UINT64":["uLongLong","2d","-2147483648","2147483647","long","unsigned long long","Long"],

          "BOOLEAN[]":["booleanSeq","b","0","1","boolean","boolean","boolean[]"],
          "DOUBLE[]":["doubleSeq","9.4lf","-1e50","1e50","double","double","double[]"],
          "FLOAT[]":["floatSeq","9.4f","-1e20","1e20","float","float","Float"],
          "INT16[]":["longSeq","2d","-2147483648","2147483647","int","long","int[]"],
          "INT32[]":["longSeq","2d","-2147483648","2147483647","int","long","int[]"],
          "INT64[]":["longSeq","2d","-2147483648","2147483647","long","long long","long[]"],
          "STRING[]":["stringSeq","s","0","0","String","string","String"],
          "BYTESTRING[]":["stringSeq","s","0","0","String","string","String"],
          "BYTE[]":["longSeq","2d","-127","127","int","long","int[]"],
          "SBYTE[]":["longSeq","2d","-127","127","int","long","int[]"],
          "UINT16[]":["longSeq","2d","-2147483648","2147483647","int","long","int[]"],
          "UINT32[]":["longSeq","2d","-2147483648","2147483647","int","long","int[]"],
          "UINT64[]":["longSeq","2d","-2147483648","2147483647","long","long","long[]"]
         }

archive=["0","15"]


class genFromTemplates:
	def __init__(self, bookfile,prefix="astri",module="tcs", basedir="./tmp"):
		self.bookfile =bookfile
		self.basedir=basedir
		wbook=excelIcd(bookfile)
		self.wb=wbook
		self.gendir=os.environ["PYGEN"]
		if self.gendir=="":
			print("PYGEN is not defined")
			exit(2)
		self.templFiles=[self.gendir+"/templates/BaseIDL.tmpl",
	    	self.gendir+"/templates/CDBSchema.tmpl",
            self.gendir+"/templates/CDBInstance.tmpl",
            self.gendir+"/templates/CDBComponent.tmpl",
            self.gendir+"/templates/BaseJavaIDL.tmpl",
            self.gendir+"/templates/deviceIDL.tmpl",
            self.gendir+"/templates/makefile.tmpl",
	    self.gendir+"/templates/javaImpl.tmpl",
	    self.gendir+"/templates/ComponentHelper.tmpl",
	    self.gendir+"/templates/ComponentBaseHelper.tmpl",
	    self.gendir+"/templates/initpy.tmpl",
	    self.gendir+"/templates/TCLBaseDevice.tmpl",
	    self.gendir+"/templates/AddSQLDevice.tmpl",
	    self.gendir+"/templates/server.tmpl",
            self.gendir+"/templates/GUIMainApp1.tmpl",
            self.gendir+"/templates/GUIBridgeController1.tmpl",
            self.gendir+"/templates/GUIBridgeComponent1.tmpl",
            self.gendir+"/templates/GUIBridge1.tmpl",
	    self.gendir+"/templates/Makefile1.tmpl"]
		self.genFile=[wbook.MainSheet["Component Name"][0]+"Base.midl",
                      wbook.MainSheet["Component Name"][0]+"Base.xsd",
                      wbook.MainSheet["Component Name"][0]+".xml",
                      wbook.MainSheet["Component Name"][0]+"_component.xml",
                      wbook.MainSheet["Component Name"][0]+"BaseImpl.java",
                      wbook.MainSheet["Component Name"][0]+".idl", "Makefile",
                      wbook.MainSheet["Component Name"][0]+"Impl.java",
                      wbook.MainSheet["Component Name"][0]+"Server.txt",
                      wbook.MainSheet["Component Name"][0]+"Main.java",
                      wbook.MainSheet["Component Name"][0]+"GUIBridgeController.java",
                      wbook.MainSheet["Component Name"][0]+"GUIBridgeComponent.java",
                      wbook.MainSheet["Component Name"][0]+"GUIBridge.fxml", "MakefileGui"]
		self.genFileNoGUI=[wbook.MainSheet["Component Name"][0]+"Base.midl",
                      wbook.MainSheet["Component Name"][0]+"Base.xsd",
                      wbook.MainSheet["Component Name"][0]+".xml",
                      wbook.MainSheet["Component Name"][0]+"_component.xml",
                      wbook.MainSheet["Component Name"][0]+"BaseImpl.java",
                      wbook.MainSheet["Component Name"][0]+".idl", "Makefile",
	              wbook.MainSheet["Component Name"][0]+"Impl.java",
	              wbook.MainSheet["Component Name"][0]+"ComponentHelper.java",
	              wbook.MainSheet["Component Name"][0]+"BaseComponentHelper.java",
Gino Tosti's avatar
Gino Tosti committed
		      "__init__.py",
		      wbook.MainSheet["Component Name"][0]+"Base.py",
		      ('AddSQL_'+wbook.MainSheet["Component Name"][0]+".sql")]		
                      #'AddSQL_'+wbook.MainSheet["Component Name"][0]+'.sql']
                      #wbook.MainSheet["Component Name"][0]+"Server.txt",
                      #wbook.MainSheet["Component Name"][0]+"Main.java",
                      #wbook.MainSheet["Component Name"][0]+"GUIBridgeController.java",
                      #wbook.MainSheet["Component Name"][0]+"GUIBridgeComponent.java",
                      #wbook.MainSheet["Component Name"][0]+"GUIBridge.fxml", "MakefileGui"]
Gino Tosti's avatar
Gino Tosti committed
		today = date.today()
		self.service =[1,2,3,4,5]
		self.devdir=self.wb.MainSheet["Component Name"][0]
Gino Tosti's avatar
Gino Tosti committed
		self.outdir=os.path.join(basedir,self.devdir)
		self.nameSpace = {'Author': "Gino Tosti", "Date":today.strftime("%y/%m/%d"),
                          'Description':wbook.MainSheet["Description"][0],'Component Name':wbook.MainSheet["Component Name"][0],
Gino Tosti's avatar
Gino Tosti committed
                          'URL':wbook.MainSheet["OPC UA address"][0],'prefix':prefix,'module':module,
                          'Assembly': wbook.MainSheet["Component Name"][0], 'x': wbook,'y':datatype}
Gino Tosti's avatar
Gino Tosti committed
		self.nameSpacePy = {'Author': "Gino Tosti", "Date":today.strftime("%y/%m/%d"),
		'Description':wbook.MainSheet["Description"][0],
		'Filename': self.genFileNoGUI[11],
		'Assembly': wbook.MainSheet['Component Name'][0],
Gino Tosti's avatar
Gino Tosti committed
		'x': wbook.GetSheet,'y':wbook.SetSheet,'z':wbook.MainSheet,'c':wbook.CmdSheet,'m':wbook.ModeSheet}
		self._dirs={}
		self.__dirs()
	def __dirs(self):
		self._dirs['config']=self.outdir+'/config/'
		self._dirs['schemas'] = self._dirs['config']+'CDB/schemas/'
		self._dirs['src']=(self.outdir+'/src/')
		self._dirs['test']=self.outdir+"/test/"
		self._dirs['idl']=self.outdir+"/idl/"
		self._dirs['tcl']=self._dirs['src']+'TCL/'
		self._dirs['prefix']=self._dirs['src']+'/'+self.nameSpace['prefix']
		self._dirs['module']=self._dirs['prefix']+'/'+self.nameSpace['module']
		self._dirs['Impl']=self._dirs['module']+'/'+self.nameSpace['Component Name']+'Impl/'
		self._dirs['BaseImpl']=self._dirs['module']+'/'+self.nameSpace['Component Name']+'BaseImpl/'
Gino Tosti's avatar
Gino Tosti committed
	def generateFiles(self):
		for i in range(0,len(self.genFile)):
			print ("Generating file:",self.genFile[i],self.templFiles[i])
			t = Template(file=self.templFiles[i], searchList=[self.nameSpace])
			#print t
			ff=open(self.genFile[i],"w")
			ff.write(str(t))
			print (date.today().strftime("%y/%m/%d")," >>>Done!")
	def generateFilesNoGUI(self):
			
		for i in range(0,len(self.genFileNoGUI)):
			print ("Generating file:",self.genFileNoGUI[i],self.templFiles[i])
			t = Template(file=self.templFiles[i], searchList=[self.nameSpace])
			#print t
			ff=open(self.genFileNoGUI[i],"w")
			ff.write(str(t))
			print (date.today().strftime("%y/%m/%d")," >>>Done!")
	
	def generateconfigFiles(self):
		
		print (date.today().strftime("%y/%m/%d"),":Generating Config file:")
		self._generateFile(1,self._dirs['schemas'])

	def generatemakeFiles(self):
		
		print (date.today().strftime("%y/%m/%d"),":Generating Makefile file:")
		self._generateFile(6,self._dirs['src'])
	
	def generateidlFiles(self):
		
		print (date.today().strftime("%y/%m/%d"),":Generating idl files:")
		self._generateFile(0,self._dirs['idl'])
		self._generateFile(5,self._dirs['idl'])
	
	def generatepyFiles(self):
		
		print (date.today().strftime("%y/%m/%d"),":Generating TCL python files:")
		self._generatepyFile(10,self._dirs['tcl'])
		self._generatepyFile(11,self._dirs['tcl'])
	
	def generatesqlFiles(self):
		
		print (date.today().strftime("%y/%m/%d"),":Generating sql files:")
		self._generatepyFile(12,self._dirs['config'])
	
	def generatesrcFiles(self):
		
		print (date.today().strftime("%y/%m/%d"),":Generating java files:")
		self._generateFile(7,self._dirs['Impl'])
		self._generateFile(8,self._dirs['Impl'])
		self._generateFile(4,self._dirs['BaseImpl'])
		self._generateFile(9,self._dirs['BaseImpl'])
		
	def _generateFile(self,idx,odir,filename=None):
		if filename==None:
			fil=odir+self.genFileNoGUI[idx]
		else:
			fil=odir+filename
		t = Template(file=self.templFiles[idx], searchList=[self.nameSpace])
		ff=open(fil,"w")
		ff.write(str(t))
		print (date.today().strftime("%y/%m/%d")," >>>Done!")
	
	def _generatepyFile(self,idx,odir,filename=None):
		if filename==None:
			fil=odir+self.genFileNoGUI[idx]
		else:
			fil=odir+filename
		t = Template(file=self.templFiles[idx], searchList=[self.nameSpacePy])
		ff=open(fil,"w")
		ff.write(str(t))
		print (date.today().strftime("%y/%m/%d")," >>>Done!")


	def _createtestCDB(self):
		#estdir=self.outdir+"/test"
		createCBDBaseDir(self._dirs['test'])
		setCDBEnvVar(self._dirs['test'])
		createCDBDirs()
		createManagerXml()
		createJavaContXml("frodoContainer") 
		cdbdir=self._dirs['test']+"CDB"
		# install the component.xml file
		cdirMaci=os.path.join(cdbdir,"MACI/Components")
		print (cdirMaci)
		#os.chdir(cdirMaci)
		xmldir=os.path.join(cdbdir,"alma/"+self.nameSpace['Component Name'])
Gino Tosti's avatar
Gino Tosti committed
		if not os.path.exists(xmldir):
				os.mkdir(xmldir)
		else:
				print ("Directory:", xmldir," already exists")	
		self._generateFile(2,xmldir+"/")
		
		compdir=os.path.join(cdirMaci,self.nameSpace['Component Name'])
Gino Tosti's avatar
Gino Tosti committed
		if not os.path.exists(compdir):
				os.mkdir(compdir)
		else:
				print ("Directory:", compdir," already exists")
		xmfil=self.genFileNoGUI[3].replace("_component","")
		self._generateFile(3,compdir+"/",xmfil)

	def checkIfExists(self):
		if os.path.exists(self.outdir):
			return True
		else:
			return False

	def _createDirs(self):

		print (date.today().strftime("%y/%m/%d"),":Generating directory structure!")
		if not os.path.exists(self.basedir):
			os.mkdir(self.basedir)
		
		if createACSDir(self.basedir,self.devdir):
			print (date.today().strftime("%y/%m/%d"),":....All done!")
		else:
			print (date.today().strftime("%y/%m/%d"),":ERROR: check your input args!")
			exit()
		
		if not os.path.exists(self._dirs['tcl']):
			os.mkdir(self._dirs['tcl'])

		if not os.path.exists(self._dirs['prefix']):
			os.mkdir(self._dirs['prefix'])
		
		if not os.path.exists(self._dirs['module']):
			os.mkdir(self._dirs['module'])
		
		if not os.path.exists(self._dirs['Impl']):
			os.mkdir(self._dirs['Impl'])
		if not os.path.exists(self._dirs['BaseImpl']):
			os.mkdir(self._dirs['BaseImpl'])
		
	def generateFileInDir(self):
		pwd=os.getcwd()
		
		self._createDirs()
		self._createtestCDB()
		self.generateconfigFiles()
		self.generateidlFiles()
		self.generatemakeFiles()
		self.generatesrcFiles()
		self.generatepyFiles()
		self.generatesqlFiles()
		sh.copyfile(self.bookfile,self._dirs['config']+(self.bookfile.split("/"))[-1])
		#print (mygen.genFile)		
		print (date.today().strftime("%y/%m/%d"),":file generated in:",self.outdir)
		os.chdir(pwd) 

if __name__=="__main__":
	bookfile = sys.argv[1]
	print (bookfile)
	mygen=genFromTemplates(bookfile,prefix="astri",module="tcs",basedir="./tmp")
	#print (os.path.abspath(mygen._dirs['config']))
	mygen.generateFileInDir()