pax_global_header 0000666 0000000 0000000 00000000064 14142737031 0014514 g ustar 00root root 0000000 0000000 52 comment=21a3f6b8044f73b282015eeb4da264559761505c
pygen-21a3f6b8044f73b282015eeb4da264559761505c/ 0000775 0000000 0000000 00000000000 14142737031 0017327 5 ustar 00root root 0000000 0000000 pygen-21a3f6b8044f73b282015eeb4da264559761505c/.gitignore 0000664 0000000 0000000 00000003763 14142737031 0021330 0 ustar 00root root 0000000 0000000 # Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
.pybuilder/
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock
# PEP 582; used by e.g. github.com/David-OConnor/pyflow
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
# pytype static type analyzer
.pytype/
# Cython debug symbols
cython_debug/
pygen-21a3f6b8044f73b282015eeb4da264559761505c/GenDevice/ 0000775 0000000 0000000 00000000000 14142737031 0021160 5 ustar 00root root 0000000 0000000 pygen-21a3f6b8044f73b282015eeb4da264559761505c/GenDevice/__init__.py 0000664 0000000 0000000 00000000001 14142737031 0023260 0 ustar 00root root 0000000 0000000
pygen-21a3f6b8044f73b282015eeb4da264559761505c/GenDevice/acsUtils.py 0000775 0000000 0000000 00000002321 14142737031 0023322 0 ustar 00root root 0000000 0000000
from datetime import date
import sys,os
import subprocess
def execACSCommand(command):
p = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
for line in p.stdout.readlines():
print (line,)
retval = p.wait()
print ("command executed:",retval)
return retval
def createACSDir(basedir,dirname):
pwd=os.getcwd()
command="getTemplateForDirectory MODROOT_WS "
print (pwd)
if basedir !="":
if not os.path.exists(basedir):
print ("Root dir:",basedir,"does not exist")
return False
else:
os.chdir(basedir)
command=command+dirname
print (command)
execACSCommand(command)
cwd=os.path.abspath(dirname)
os.chdir(pwd)
else:
print ("A null Root dir was selected")
return False
return cwd
def checkACS():
if 'ACSROOT' in os.environ:
return True
else:
return False
def stopAcs():
command="acsStop -b 0 "
exexACSCommnad(command)
def startAcs():
command="acsStart -b 0 "
exexACSCommnad(command)
def startJavaCont(name):
command="acsStartContainer -java -b 0 " +name
exexACSCommnad(command)
def stopJavaCont(name):
command="acsStopContainer -b 0 " +name
exexACSCommnad(command)
def killACS():
command="killACS "
exexACSCommnad(command)
pygen-21a3f6b8044f73b282015eeb4da264559761505c/GenDevice/createEmptyCDB.py 0000775 0000000 0000000 00000010614 14142737031 0024332 0 ustar 00root root 0000000 0000000 from GenDevice.acsUtils import *
import shutil
import os
managerxml="""
"""
javacontXml = """
"""
def setCDBEnvVar(dirname):
os.environ["ACS_CDB"]=dirname
pwd = os.getcwd()
os.chdir(dirname)
f=open("setCDB.sh","w")
f.write("export ACS_CDB="+dirname+"\n")
f.close()
os.chdir(pwd)
return
def createDir(dirname):
command="mkdir -p "
if dirname !="":
if os.path.exists(dirname):
print ("dir:",dirname," already exists")
return True
else:
command=command+dirname
print (command)
execACSCommand(command)
else:
print ("A null dirname was inserted")
return False
return True
def createCBDBaseDir(dirname):
if createDir(dirname):
print ("CDB base dir created")
return True
else:
print ("error")
return False
def createCDBDirs():
basedir=os.environ["ACS_CDB"]
templatedir=os.environ["PYGEN"]+ "/templates/CDB" #/templates/Alarms"
print (basedir)
if basedir=="":
print ("ACS_CDB variable is not defined")
return False
else:
alarmdir=basedir+"/CDB" #"/CDB/Alarms"
if os.path.exists(alarmdir):
print ("dir:",alarmdir," already exists")
else:
shutil.copytree(templatedir,alarmdir)
"""almadir = basedir+"/CDB/alma"
if createDir(almadir):
srt="directory:"+almadir+" created"
print (srt)
else:
print ("error creting directory:",almadir)
schemadir = basedir+"/CDB/schemas"
if createDir(schemadir):
print ("directory:"+schemadir+" created")
else:
print ("error creting directory:"+schemadir)
macidir = basedir +"/CDB/MACI/{Components,Containers,Managers}"
if createDir(macidir):
print ("directory:"+macidir+" created")
else:
print ("error creting directory:"+macidir)
managerdir = basedir+"/CDB/MACI/Managers/Manager"
if createDir(managerdir):
print ("directory:"+managerdir+" created")
else:
print ("error creting directory:"+managerdir)"""
def createManagerXml():
basedir=os.environ["ACS_CDB"]
managerdir = basedir+"/CDB/MACI/Managers/Manager"
managerfile=managerdir+"/Manager.xml"
f = open(managerfile,"w")
f.write(managerxml)
f.close()
def createJavaContXml(name):
basedir=os.environ["ACS_CDB"]
javacontdir = basedir +"/CDB/MACI/Containers/"+name
if createDir(javacontdir):
print ("directory:"+javacontdir+" created")
else:
print ("error creting directory:"+javacontdir)
return False
javacontfile=javacontdir+"/"+name+".xml"
f = open(javacontfile,"w")
f.write(javacontXml)
f.close()
if __name__=="__main__":
createCBDBaseDir(sys.argv[1])
setCDBEnvVar(sys.argv[1])
createCDBDirs()
createManagerXml()
createJavaContXml()
pygen-21a3f6b8044f73b282015eeb4da264559761505c/GenDevice/excelIcd.py 0000664 0000000 0000000 00000006112 14142737031 0023252 0 ustar 00root root 0000000 0000000 import pandas as pd
from datetime import date
import sys,os
from optparse import OptionParser
import openpyxl.utils.exceptions as ecc
# Read the ICD excel file
class excelIcd:
def __init__(self, excel_file=None):
self.bookfile =excel_file
self.book = None
self.nsheets=0
self.sheets={}
self.MainSheet={}
self.GetSheet={}
self.SetSheet={}
self.CmdSheet={}
self.ModeSheet={}
self.debug=False
self._getExcelWorkbook()
def setDebugModeOn(self):
debug=True
def setDebugModeOff(self):
debug=False
def _getExcelWorkbook(self):
try:
self.book = pd.ExcelFile(self.bookfile,engine='openpyxl')
except FileNotFoundError:
print("File does not exist")
except ecc.InvalidFileException:
print(" openpyxl does not support the old .xls file format\n","Trying with xlrd")
self.book = pd.ExcelFile(self.bookfile)
self.nsheets = len(self.book.sheet_names)
if(self.debug):
print(self.nsheets,self.book.sheet_names)
for sheet_name in (self.book.sheet_names):
she=(self.book.parse(sheet_name)).dropna(axis=0,how='all')
self.sheets[sheet_name]=she.dropna(axis=1,how='all')
siz=self.sheets[sheet_name].shape
if(self.debug):
print(self.sheets[sheet_name].columns,siz[0],siz[1])
self.MainSheet=self.getSheet("Main")
self.GetSheet=self.getSheet("GET")
self.SetSheet=self.getSheet("SET")
self.CmdSheet=self.getSheet("CMD")
self.ModeSheet=self.getSheet("MODE")
def getMain(self):
self.sheets["Main"].columns=self.sheets["Main"].iloc[0]
self.sheets["Main"] = self.sheets["Main"].loc[1:,self.sheets["Main"].columns]
self.MainSheet["NCols"]=(self.sheets["Main"].shape)[1]
self.MainSheet["NRows"]=(self.sheets["Main"].shape)[0]-1
self.MainSheet["Colnames"]= self.sheets["Main"].columns
#print("*******LINEA",self.sheets["Main"].iloc[0])
for colind,coname in enumerate (self.sheets["Main"]):
#print "CCC",coname
colval=[]
if(self.debug):
print("****",coname,"*****",(str(coname)).replace(' ','_'))
#colname=(str(coname)).replace(' ','_')
for idx in range(0,self.MainSheet["NRows"]):
#print "BBBBB", self.sheets["Main"].cell(idx,colind).value
colval.append(self.sheets["Main"].iat[idx+1,colind])
self.MainSheet[coname]=colval
if(self.debug):
print(coname,self.MainSheet[coname])
print("Read Sheet: Main"," from:", self.bookfile )
return self.MainSheet
def getSheet(self, name):
Sheet={}
try:
Sheet["NCols"]=(self.sheets[name].shape)[1]
Sheet["NRows"]=(self.sheets[name].shape)[0]
Sheet["Colnames"]= self.sheets[name].columns
#print(Sheet["Colnames"])
for colind,coname in enumerate (self.sheets[name]):
#coname=self.sheets["Main"].cell(1,colind).value
#print "CCC",coname
colval=[]
#colname=(str(coname)).replace(' ','_')
for idx in range(0,Sheet["NRows"]):
#print "BBBBB", self.sheets["Main"].cell(idx,colind).value
colval.append(str(self.sheets[name].iat[idx,colind]))
Sheet[coname]=colval
#print(coname,Sheet[coname])
print("Read Sheet:",name," from:", self.bookfile )
return Sheet
except:
print("sheet:",name,"does not exist")
return None
pygen-21a3f6b8044f73b282015eeb4da264559761505c/GenDevice/genDeviceGui.py 0000775 0000000 0000000 00000012123 14142737031 0024072 0 ustar 00root root 0000000 0000000 #! /usr/bin/env python
from Cheetah.Template import Template
from datetime import date
from GenDevice.excelIcd import excelIcd
import sys,os
from optparse import OptionParser
import subprocess
from GenDevice.genFromTemplates import genFromTemplates
from GenDevice.createEmptyCDB import *
from GenDevice.acsUtils import *
import PySimpleGUI as sg
fnt = 'Arial 18'
def warningWin(txt):
event, values = sg.Window('*****Warning****',
[[sg.Text(txt)],
[sg.B('OK'), sg.B('Cancel') ]], size=(400,200),font=fnt ).read(close=True)
return (event, values)
def generateFiles(opt):
mygen=genFromTemplates(opt['bookfile'], opt['prefix'],opt['module'],opt['basedir'])
if mygen.checkIfExists():
txt="The device files already exists in:\n"+str(mygen.outdir)+"\nOverride existing files?"
event, value=warningWin(txt)
if event == 'OK':
mygen.generateFileInDir()
return mygen._dirs
else:
return None
else:
mygen.generateFileInDir()
return mygen._dirs
def buildCode(dirs):
pwd=os.getcwd()
os.chdir(dirs['src'])
print ("Make Build ")
command="make clean all"
print ("Execuiting:",command)
if execACSCommand(command):
print ("ERROR executing: ",command,)
os.chdir(pwd)
def readOptions(window,values):
opt={}
if not values['-IN-']=="":
opt['bookfile']=values['-IN-']
else:
event, value=warningWin("Input file is not set")
return None
if not values['-OUT-']=="":
opt['basedir']=values['-OUT-']
else:
event, value=warningWin("Output dir is not set by user\nDefault value is : ./tmp")
if event == 'OK':
opt['basedir']="./tmp"
window['-OUT-'].update(opt['basedir'])
window.Refresh()
else:
return None
if not values['-PACK-']=="":
opt['prefix']=values['-PACK-']
else:
event, value=warningWin("Package name set by user.\nDefault value is: astri")
if event == 'OK':
opt['prefix']="astri"
window['-PACK-'].update(opt['prefix'])
window.Refresh()
else:
return None
if not values['-MOD-']=="":
opt['module']=values['-MOD-']
else:
event, value=warningWin("Module name set by user.\nDefault value is: tcs")
if event == 'OK':
opt['module']="tcs"
window['-MOD-'].update(opt['module'])
window.Refresh()
else:
return None
return opt
def myLayout():
sg.theme('DarkTeal12') # Keep things interesting for your users
layout = [[sg.T('Set Input Parameters')],
[sg.T('input ICD file',size=(15,1)),sg.I(key='-IN-', size=(60,1),), sg.Button('BrowseFile')], [sg.T('Output Dir',size=(15,1)),
sg.I(key='-OUT-',size=(60,1)), sg.Button('BrowseDir')], [sg.T('Package Prefix',size=(15,1))
,sg.I("astri",key='-PACK-',size=(20,1))], [sg.Text('Module Prefix',size=(15,1)),
sg.Input("tcs",key='-MOD-',size=(20,1))],
[sg.Button('Submit'), sg.Button('Generate'), sg.Button('Build'), sg.Exit()],
[sg.MLine(key='-ML-', size=(80,20),reroute_stdout=True)], [sg.B('Clear')]]
return layout
def myWindow(title):
layout=myLayout()
window = sg.Window(title, layout,font=fnt, location=(200,100), resizable=True, finalize=True) #size=(500,200)
return window
def mainLoop(window):
fnt = 'Arial 18'
window['Generate'].update(disabled=True)
window['Build'].update(disabled=True)
gen=False
build=False
genDirs=[]
while True: # The Event Loop
event, values = window.read()
print(event, values)
if event == sg.WIN_CLOSED or event == 'Exit':
break
if event == 'Submit':
opt=readOptions(window,values)
print(opt)
if not gen:
window['Generate'].update(disabled=False)
window.Refresh()
gen=True
if event == 'BrowseFile':
fname=sg.popup_get_file('Select ICD file',font=fnt, file_types=(('ALL Files', '*.*'),('old excel Files', '*.xls'),('excel Files', '*.xlsx')),no_window=True)
window['-IN-'].update(fname)
if event == 'BrowseDir':
dname=sg.popup_get_folder('Select Output Base Directory', no_window=True)
window['-OUT-'].update(dname)
window.Refresh()
if event == 'Generate':
if not opt==None:
print(opt)
genDirs=generateFiles(opt)
if not build:
window['Build'].update(disabled=False)
window.Refresh()
Build=True
else:
print("Parameters are not set")
if event == 'Build':
if not genDirs==None:
try:
buildCode(genDirs)
except Exception as ex:
print(ex)
if event == 'Clear':
window['-ML-']('')
if __name__ =="__main__":
pwd=os.getcwd()
gendir=os.environ["PYGEN"]
if gendir=="":
print ("Please set the env variable PYGEN = the Geneartor root directory")
exit()
if not checkACS():
print ("ACS Enviroment is not set")
exit()
introot = os.environ["INTROOT"]
if introot=="":
print("INTROOT variable is not set")
exit()
os.chdir(gendir)
window=myWindow('Device Code Generator v1.0 by GT@astri')
mainLoop(window)
window.close()
os.chdir(pwd)
"""
command ="make install"
if execACSCommand(command):
print ("ERROR executing: ",command)
os.chdir(pwd)
exit()
os.chdir(pwd)
command="cdbChecker"
if execACSCommand(command):
print ("ERROR executing: ",command)
exit()
"""
print ("ALL Done")
pygen-21a3f6b8044f73b282015eeb4da264559761505c/GenDevice/genFromTemplates.py 0000775 0000000 0000000 00000027751 14142737031 0025025 0 ustar 00root root 0000000 0000000 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, wbook,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",
"__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"]
today = date.today()
self.service =[1,2,3,4,5]
self.devdir=self.wb.MainSheet["Component Name"][0]
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],
'URL':wbook.MainSheet["OPC UA address"][0],'prefix':prefix,'module':module,
'Assembly': wbook.MainSheet["Component Name"][0], 'x': wbook,'y':datatype}
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],
'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/'
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'])
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'])
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()
pygen-21a3f6b8044f73b282015eeb4da264559761505c/GenDevice/genSimpleJavaComp3.py 0000775 0000000 0000000 00000005064 14142737031 0025171 0 ustar 00root root 0000000 0000000 from Cheetah.Template import Template
from datetime import date
from GenDevice.genSimpleJavaCompFiles import *
from GenDevice.createEmptyCDB import *
from GenDevice.acsUtils import *
import sys,os
from optparse import OptionParser
def copyToDir(files,cdir,prefix,module,container):
pwd=os.getcwd()
execACSCommand("mv "+files[0]+" "+cdir+"/idl/")
execACSCommand("mv "+files[3]+" "+cdir+"/src/")
os.chdir(cdir+"/src")
#print ("mv "+files[1]+" "+cdir+"/src/actlslow/myacstest/"+(files[1].split("."))[0]+"/")
execACSCommand("make clean all")
os.chdir(pwd)
impdir=cdir+"/src/"+prefix+"/"+module+"/"+(files[1].split("."))[0]+"/"
execACSCommand("mv "+impdir+(files[0].split("."))[0]+"ComponentHelper.java.tpl "+ impdir+(files[0].split("."))[0]+"ComponentHelper.java")
execACSCommand("mv "+files[1]+" "+impdir)
# Create the CBD in /test and the setCDB.sh scipt"
createCBDBaseDir(cdir+"/test")
setCDBEnvVar(cdir+"/test")
createCDBDirs()
createManagerXml()
createJavaContXml(container)
os.chdir(pwd)
cdb=os.environ["ACS_CDB"]+"/CDB/"
# install the component.xml file
cdirMaci=cdb+"MACI/Components/"
print (cdirMaci)
os.chdir(cdb+"MACI/Components/")
if not os.path.exists((files[0].split("."))[0]):
os.mkdir((files[0].split("."))[0])
cdir0=cdirMaci+(files[0].split("."))[0]+"/"
#check the CDB content
os.chdir(pwd)
print ("mv "+files[2]+" "+cdir0)
execACSCommand("mv "+files[2]+" "+cdir0)
execACSCommand("cdbChecker")
# Make final installation of the component
os.chdir(cdir+"/src")
basedir=os.environ["INTROOT"]
print (basedir)
if basedir=="":
print ("INTOORT variable is not defined: please set the Variable and the run: make clean all install")
return False
else:
execACSCommand("make clean all install")
#['testCBD.idl', 'testCBDImpl.java', 'testCBD.xml', 'Makefile', 'testCBD_component.xml']
if __name__=="__main__":
parser = OptionParser()
parser.add_option("-c", "--compName", dest="compName", default="helloWorld",
help="name of the component")
parser.add_option("-m", "--moduleName", dest="moduleName",default="test",
help="name of the module")
parser.add_option("-p", "--prefixName", dest="prefixName",default="astri",
help="name of the prefix")
(options, args) = parser.parse_args()
compdir=createACSDir("./",options.compName)
print (options.compName)
mygen=genSimpleTemplates(options.compName,options.prefixName,options.moduleName)
mygen.generateFiles()
copyToDir(mygen.genFile,compdir,options.prefixName,options.moduleName,"frodoContainer")
print (mygen.genFile)
pygen-21a3f6b8044f73b282015eeb4da264559761505c/GenDevice/genSimpleJavaCompFiles.py 0000664 0000000 0000000 00000006133 14142737031 0026064 0 ustar 00root root 0000000 0000000 from Cheetah.Template import Template
from datetime import date
import sys,os
class genSimpleTemplates:
def __init__(self, bookfile,prefix,module):
self.bookfile =bookfile
self.module=module
self.prefix=prefix
self.gendir=os.environ["PYGEN"]
self.templFiles=[self.gendir+"/templates/simpleCompTemplate/BaseIDL.tmpl",self.gendir+"/templates/simpleCompTemplate/JavaSimpleImpl.tmpl",
self.gendir+"/templates/simpleCompTemplate/simpleCompxml.tmpl",self.gendir+"/templates/simpleCompTemplate/makefile.tmpl"]
self.genFile=[self.bookfile +".idl",
self.bookfile +"Impl.java",
self.bookfile +".xml",
"Makefile"
#self.bookfile +"_component.xml"
]
today = date.today()
self.service =[1,2,3,4,5]
self.nameSpace = {'Author': "Gino Tosti", "Date":today.strftime("%y/%m/%d"),
'Description':("Component "+self.bookfile),
'Component': self.bookfile, 'Module':self.module,'prefix':self.prefix}
def generateFiles(self):
for i in range(0,4): #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 (">>>Done!")
if __name__=="__main__":
compName = sys.argv[1]
moduleName=sys.argv[2]
print (compName)
mygen=genSimpleTemplates(compName,moduleName)
mygen.generateFiles()
print (mygen.genFile)
"""
wbook=myIcd(bookfile)
#print(wbook.sheets['Main'])
#print(wbook.CmdSheet["Colnames"])
genFile=[wbook.MainSheet["Assembly"][0]+"Base.idl",
wbook.MainSheet["Assembly"][0]+"Base.xsd",
wbook.MainSheet["Assembly"][0]+".xml",
wbook.MainSheet["Assembly"][0]+"_component.xml",
wbook.MainSheet["Assembly"][0]+"BaseImpl.java",
wbook.MainSheet["Assembly"][0]+".idl",
"Makefile",
wbook.MainSheet["Assembly"][0]+"Impl.java"]
today = date.today()
service =[1,2,3,4,5]
nameSpace = {'Author': "Gino Tosti", "Date":today.strftime("%y/%m/%d"), 'Description':wbook.MainSheet["Description"][0],'Assembly': wbook.MainSheet["Assembly"][0], 'x': wbook,'y':datatype}
for i in range(0,len(genFile)):
print "Generating file:",genFile[i]
t = Template(file=templFiles[i], searchList=[nameSpace])
#print t
ff=open(genFile[i],"wb")
ff.write(str(t))
print ">>>Done!"
t1 = Template(file=templFiles[1], searchList=[nameSpace])
#print t1
ff=open(genFile[1],"wb")
ff.write(str(t1))
t2 = Template(file=templFiles[2], searchList=[nameSpace])
#print t2
ff=open(genFile[2],"wb")
ff.write(str(t2))
t3 = Template(file=templFiles[3], searchList=[nameSpace])
#print t3
ff=open(genFile[3],"wb")
ff.write(str(t3))
t4 = Template(file=templFiles[4], searchList=[nameSpace])
#print t4
ff=open(genFile[4],"wb")
ff.write(str(t4))
t5 = Template(file=templFiles[5], searchList=[nameSpace])
#print t5
ff=open(genFile[5],"wb")
ff.write(str(t5))
t6 = Template(file=templFiles[6], searchList=[nameSpace])
#print t6
ff=open(genFile[6],"wb")
ff.write(str(t6))
t7 = Template(file=templFiles[6], searchList=[nameSpace])
#print t7
ff=open(wbook.MainSheet["Assembly"][0]+"Impl.java","wb")
ff.write(str(t7))"""
pygen-21a3f6b8044f73b282015eeb4da264559761505c/GenDevice/generateFiles.py 0000775 0000000 0000000 00000001560 14142737031 0024314 0 ustar 00root root 0000000 0000000 #! /usr/bin/env python
from Cheetah.Template import Template
from datetime import date
from getSheets import myIcd
import sys,os
from optparse import OptionParser
import subprocess
from genFromTemplates import genFromTemplates
if __name__ =="__main__":
parser = OptionParser()
today = date.today()
parser.add_option("-f", "--file", dest="bookfile",
help="ICD Exel File ", metavar="FILE")
parser.add_option("-d", "--dir", dest="basedir", default=".",
help="Root dir where to install the new device ", metavar="DIR")
(options, args) = parser.parse_args()
print options.bookfile
wbook=myIcd(options.bookfile)
mygen=genFromTemplates(options.bookfile)
mygen.generateFiles()
print mygen.genFile
dirname=wbook.MainSheet["Assembly"][0]
outdir=os.path.join(options.basedir,dirname)
print mygen.genFile
pygen-21a3f6b8044f73b282015eeb4da264559761505c/GenDevice/installFilesNoGUI.py 0000664 0000000 0000000 00000012672 14142737031 0025035 0 ustar 00root root 0000000 0000000 #! /usr/bin/env python
from Cheetah.Template import Template
from datetime import date
from getSheets import myIcd
import sys,os
from optparse import OptionParser
import subprocess
from genFromTemplates import genFromTemplates
from createEmptyCDB import *
from acsUtils import *
if __name__ =="__main__":
parser = OptionParser()
today = date.today()
parser.add_option("-f", "--file", dest="bookfile",
help="ICD Exel File ", metavar="FILE")
parser.add_option("-d", "--dir", dest="basedir", default=".",
help="Root dir where to install the new device ", metavar="DIR")
parser.add_option("-i", "--install", dest="install", default="true",
help="execute the Makefile in src dir ", metavar="INSTALL")
(options, args) = parser.parse_args()
gendir=os.environ["PYGEN"]
if gendir=="":
print ("Please set the env variable PYGEN = the Geneartor Directory")
exit()
if not checkACS():
print ("ACS Enviroment is not set")
exit()
print (options.bookfile)
wbook=myIcd(options.bookfile)
if wbook.book == None:
sys.exit(1)
mygen=genFromTemplates(options.bookfile)
mygen.generateFilesNoGUI()
print (mygen.genFileNoGUI)
dirname=wbook.MainSheet["Assembly"][0]
basedir=options.basedir
if not os.path.exists(basedir):
os.mkdir(basedir)
outdir=os.path.join(basedir,dirname)
print ("output directory is:",outdir)
#cdbdir=os.path.join(os.environ["ACS_CDB"],"CDB")
print ("generating ACS device directory")
if createACSDir(basedir,dirname):
print (today.strftime("%y/%m/%d"),"....All done!")
else:
print (today.strftime("%y/%m/%d"),"ERROR: check your input args!")
exit()
print ("Installing IDL and Schema files")
targetFileBaseIdl = os.path.join(outdir,"idl")+"/"+mygen.genFileNoGUI[0]
command="mv "+mygen.genFileNoGUI[0] + " "+ os.path.join(outdir,"idl")+"/.;"
command=command + "mv "+mygen.genFileNoGUI[1] + " "+ os.path.join(outdir,"config/CDB/schemas")+"/.;"
targetFileIdl = os.path.join(outdir,"idl")+"/"+mygen.genFile[5]
if not os.path.exists(targetFileIdl):
command=command + "mv "+mygen.genFileNoGUI[5] + " "+ os.path.join(outdir,"idl")+"/.;"
else:
print ("file: ", targetFileIdl, " Already exist")
command = command+ "rm "+mygen.genFile[5]+";"
command=command + "mv "+mygen.genFileNoGUI[6] + " "+ os.path.join(outdir,"src")+"/.;"
#command=command + "mv "+mygen.genFileNoGUI[8] + " "+ os.path.join(outdir,"test")+"/.;"
command=command + "cp -n "+gendir +"/config/tatTemplates/*" " "+ os.path.join(outdir,"test")+"/"
print (command)
if execACSCommand(command):
print ("ERROR executing: ",command)
exit()
pwd=os.getcwd()
# Create the CBD in /test and the setCDB.sh scipt"
createCBDBaseDir(outdir+"/test")
setCDBEnvVar(outdir+"/test")
createCDBDirs()
createManagerXml()
createJavaContXml("frodoContainer")
os.chdir(pwd)
cdbdir=os.environ["ACS_CDB"]+"/CDB"
# install the component.xml file
cdirMaci=os.path.join(cdbdir,"MACI/Components")
print (cdirMaci)
#os.chdir(cdirMaci)
xmldir=os.path.join(cdbdir,"alma/"+dirname)
if not os.path.exists(xmldir):
os.mkdir(xmldir)
else:
print ("Directory:", xmldir," already exists")
command="mv -u "+mygen.genFileNoGUI[2]+ " "+ os.path.join(cdbdir,"alma/"+dirname)+"/."
print (command)
if execACSCommand(command):
print ("ERROR executing: ",command)
exit(1)
compdir=os.path.join(cdirMaci,dirname)
if not os.path.exists(compdir):
os.mkdir(compdir)
else:
print ("Directory:", compdir," already exists")
command="mv -u "+mygen.genFileNoGUI[3]+ " "+ compdir+"/"+mygen.genFileNoGUI[3].replace("_component","")
print (command)
if execACSCommand(command):
print ("2- ERROR executing: ",command)
exit(2)
else:
print ("......CDB Created")
dirBaseImpl=os.path.join(outdir,("src/astrima/tcs/"+dirname+"BaseImpl"))
if options.install == "true":
os.chdir(os.path.join(outdir,"src"))
cpwd=os.getcwd()
print ("Make Build ")
print (os.path.exists(os.path.join(cpwd,("astrima/tcs/"+dirname+"BaseImpl"))),"****")
if not os.path.exists(os.path.join(cpwd,("astrima/tcs/"+dirname+"BaseImpl"))):
print (dirBaseImpl)
command="make clean all"
print (command)
if execACSCommand(command):
print ("3- EXPECTED ERROR executing: ",command,)
dir1=cpwd+"/astrima/tcs/"+dirname+"BaseImpl/"+dirname
dir2=cpwd+"/astrima/tcs/"+dirname+"Impl/"+dirname
print ("****",dir1,dir2,"****")
command="mv -u "+ dir1+"BaseComponentHelper.java.tpl"+" "+dir1+"BaseComponentHelper.java;"
print ("****",command,"****")
command=command+"mv -u "+os.path.join(pwd,mygen.genFileNoGUI[4])+" "+cpwd+"/astrima/tcs/"+dirname+"BaseImpl/.;"
implFile = os.path.join(cpwd,"astrima/tcs/"+dirname+"Impl/"+mygen.genFileNoGUI[7])
if not os.path.exists(implFile):
command=command+"mv -u "+ dir2+"ComponentHelper.java.tpl"+" "+dir2+"ComponentHelper.java;"
command=command+"mv -u "+os.path.join(pwd,mygen.genFile[7])+" "+cpwd+"/astrima/tcs/"+dirname+"Impl/.;"
else:
print ("File: ",implFile," Already exist")
command=command+"rm "+os.path.join(pwd,mygen.genFileNoGUI[7])+";"
print (command)
if execACSCommand(command):
print ("4-ERROR executing: ",command)
os.chdir(pwd)
exit()
else:
command ="make clean all install"
if execACSCommand(command):
print ("ERROR executing: ",command)
os.chdir(pwd)
exit()
os.chdir(pwd)
command="cdbChecker"
if execACSCommand(command):
print ("ERROR executing: ",command)
exit()
print ("ALL Done")
pygen-21a3f6b8044f73b282015eeb4da264559761505c/README.md 0000664 0000000 0000000 00000006337 14142737031 0020617 0 ustar 00root root 0000000 0000000 as root:
yum install libXScrnSaver
as user:
pip install --upgrade --user pip setuptools wheel
pip install --user Cheetah3
pip install --user xlrd==2.0.1
pip install --user openpyxl
pip install --user pandas (it could be already installed)
pip install --user pysimplegui
Install pyGen:
git clone git@git.ia2.inaf.it:gino.tosti/pygen.git
source install.sh
set enviroment variable:
export $PYGEN=/home//pyGen
To test the generator from command line (this allow to create multiple devices components from a single ICD):
$>cd $PYGEN/test
$>python genDevice.py -f -p astri -m tcs
To test the generator with the GUI (only single device component generation is supported)
$>cd $PYGEN/test
$>python runGenDeviceGUI.py
It is now possible to generate an ICD in word (using the standard ASTRI document format) starting from open ecxel file format (.xlsx).
To use this feature you have to install:
pip install --user docx
pip install --user docxtpl
To run the converter
$>cd $PYGEN/test
$>python icd_converter.py -f
es.
$>python icd_converter.py -f $SHAREDIR/ICD/icdExample.xlsx
.....
.....
The generated .Docx file is: ..../ICD/icdExample.docx
An experimental simulation OPC-UA server written in python can be also generatedwith this version of pyGen. Arrays are not supported at present, then to play with it use ICD that do not include arrays.
Before to use it you need to install some libraries:
———Python OPCUA support libraries —-
the ACS environment must be active
library needed by Qt
from root /sudo
yum install libxcb
yum install xcb-util-wm
yum install xcb-util-image
yum install xcb-util-keysyms
yum install xcb-util-renderutil
from user account:
Install pyQT
pip3 install --user PyQt5
pip3 install --user pyqtgraph
Install python opcua https://github.com/FreeOpcUa/python-opcua
pip3 install --user opcua
pip3 install --user opcua-client
The documentation on python opcua is here:
https://github.com/FreeOpcUa/python-opcua
--------Simulation server generation----------
$>cd $PYGEN/test
$>python makeTestOPCUAServer.py -f -o
the input ICD file shall be the same used to generate the ACS component.The default output dir is "./SimulationOPCUAserver"
in the output you have someting like:
....
....
Working on: ['MyDevice']
File: /home/astrisw/pyGen/test/SimulationOPCUAserver/MyDeviceServerModel.xml created
File: /home/astrisw/pyGen/test/SimulationOPCUAserver/MyDevice_opcuaServer.py created
The Simulation server can be reached at: opc.tcp://127.0.0.1:52523/OPCUA/hwSimulator
$>cd ServerOutputDir
$>python _upcuaServer.py
you should see something like this output:
Server Started!
Python 3.6.9 (default, Sep 3 2020, 15:28:31)
Type 'copyright', 'credits' or 'license' for more information
IPython 7.8.0 -- An enhanced Interactive Python. Type '?' for help.
In [1]:
Insert exit at the In[1] prompt above.
To check the server open another terminal and insert the command:
$>opcua-client
Insert for example:"opc.tcp://127.0.0.1:52523/OPCUA/hwSimulator" in the input box on top left of the client and click on the "Connect button". You can play with the servers nodes now.
pygen-21a3f6b8044f73b282015eeb4da264559761505c/install.sh 0000664 0000000 0000000 00000000126 14142737031 0021330 0 ustar 00root root 0000000 0000000 python setup.py bdist_wheel
python -m pip install dist/GenDevice-0.2-py3-none-any.whl
pygen-21a3f6b8044f73b282015eeb4da264559761505c/setup.py 0000664 0000000 0000000 00000000360 14142737031 0021040 0 ustar 00root root 0000000 0000000 from setuptools import setup
setup(name='GenDevice',
version='0.2',
description='Python code generator for ASTRI-MA',
url='#',
author='Gino Tosti',
author_email='gino.tosti@inaf.it',
license='GPL 3',
packages=['GenDevice'],
zip_safe=False)
pygen-21a3f6b8044f73b282015eeb4da264559761505c/templates/ 0000775 0000000 0000000 00000000000 14142737031 0021325 5 ustar 00root root 0000000 0000000 pygen-21a3f6b8044f73b282015eeb4da264559761505c/templates/AddSQLDevice.tmpl 0000664 0000000 0000000 00000026032 14142737031 0024416 0 ustar 00root root 0000000 0000000 /*
* ASTRI - Template for Assembly SQL based on ALMA Software Templates
* (c) INAF/UNIPG, 2021
*
* WARNING! DO NOT MODIFY THIS FILE!
*
* Generated by: $Author
* Date: $Date
* Description: $Description
* Filename: $Filename
*
*/
/* Definiions */
SET @LRUName='$z['Assembly'][0]';
SET @LRUFullName='$z['Device Name'][0]';
SET @LRUICD='$z['ICD'][0]';
SET @LRUICDDate=1000000000000;
SET @LRUDescription='$z['Description'][0]';
SET @LRUNotes='';
SET @ASSEMBLY='$z['Assembly'][0]';
SET @COMPTYPE= 'IDL:astri/tcs/$z['Assembly'][0]:1.0';
SET @PRODCODE='${z['Assembly'][0]}Impl';
SET @BASELEMENT='Telescope';
SET @MP_Name =' ';
SET @MP_Description=' ';
SET @MP_Format='bb';
SET @MP_DisplayUnits='gg';
SET @MP_GraphMin=0;
SET @MP_GraphMax=0;
SET @MP_Interval=1;
SET @MP_MinRange=0;
SET @MP_MaxRange=0;
SET @MP_DataType='string';
SET @MP_DataUnits=@MP_DisplayUnits;
SET @MP_archive_suppress='0';
SELECT 'Transaction BEGIN';
/* LRUType*/
SELECT '1: find out wether LRUType Assembly has already been inserted.';
drop procedure if exists lru;
DELIMITER ;;
create procedure lru() begin
SELECT COUNT(lruName) INTO @lruNameCount FROM lruType WHERE lruName=@LRUName;
IF (@lruNameCount > 0) THEN
SELECT 'LRU already exists', @LRUName;
ELSE
SELECT 'No LRU',@LRUName, 'Inserting LRU';
INSERT INTO LRUType VALUES (@LRUName, @LRUFullName,@LRUICD,@LRUICDDate,@LRUDescription,@LRUNotes);
END IF;
end ;;
DELIMITER ;
call lru;
drop procedure lru;
-- SELECT * FROM lruType;
/* ComponentType */
SELECT '2: find out wether ComponentType has already been inserted.';
drop procedure if exists comptype;
DELIMITER ;;
create procedure comptype() begin
SELECT COUNT(componentTypeId) INTO @componentTypeIdCount FROM componentType WHERE idl= @COMPTYPE;
IF (@componentTypeIdCount > 0) THEN
SELECT 'COMPType already exists', @COMPTYPE;
ELSE
SELECT 'No COMPType',@COMPTYPE, 'Inserting COMPType';
INSERT INTO ComponentType (idl) VALUES (@COMPTYPE);
END IF;
end ;;
DELIMITER ;
call comptype;
drop procedure comptype;
/* Assembly Type */
SELECT '3: find out wether AssemblyType has already been inserted.';
SELECT componenttypeid INTO @compTypeId FROM componentType WHERE idl=@COMPTYPE;
drop procedure if exists assemblytype;
DELIMITER ;;
create procedure assemblytype() begin
SELECT COUNT(assemblytypename) INTO @assemblyNameCount FROM assemblyType WHERE assemblytypename=@ASSEMBLY;
IF (@assemblyNameCount > 0) THEN
SELECT 'ASSEMBLYType already exists', @ASSEMBLY;
ELSE
SELECT 'No ASSEMBLYType',@ASSEMBLY, 'Inserting ASSEMBLYType';
INSERT INTO AssemblyType (
ASSEMBLYTYPENAME,
BASEELEMENTTYPE,
LRUNAME,
FULLNAME,
DESCRIPTION,
NOTES,
COMPONENTTYPEID,
PRODUCTIONCODE,
SIMULATEDCODE)
VALUES (
@ASSEMBLY,
@BASELEMENT,
@ASSEMBLY,
@LRUFullName,
@LRUDescription,
'',
@compTypeId,
@PRODCODE,
''
);
END IF;
end ;;
DELIMITER ;
call assemblytype;
drop procedure assemblytype;
/* DefaultComponent */
SELECT '4: find out wether DefaultComponent has already been inserted.';
SELECT defaultcomponentid INTO @defCompId FROM defaultcomponent WHERE assemblytypename=@ASSEMBLY;
drop procedure if exists defcomp;
DELIMITER ;;
create procedure defcomp() begin
DECLARE exit_loop INT DEFAULT 0;
DECLARE defaultbacipropid1 INT DEFAULT 0;
DECLARE defaultbacipropertyid1 INT DEFAULT 0;
DECLARE propCur CURSOR FOR SELECT defaultbacipropid from defaultbaciproperty where defaultcomponentid = @defCompId;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET exit_loop = 1;
OPEN propCur;
SELECT count(defaultcomponentid) INTO @defaultComponentCount FROM defaultComponent WHERE assemblytypename=@ASSEMBLY;
IF @defaultComponentCount=0 THEN
SELECT 'Inserting defaultcomponent',@ASSEMBLY;
SELECT MAX(defaultcomponentid) INTO @defCompId FROM defaultComponent;
SET @defCompId=COALESCE(@defCompId,0)+1;
INSERT INTO DefaultComponent (
defaultcomponentid,
ComponentTypeId,
AssemblyTypeName,
ImplLang,
RealTime,
Code,
Path,
IsAutostart,
IsDefault,
IsStandaloneDefined,
KeepAliveTime,
MinLogLevel,
MinLogLevelLocal,
XMLDoc
)
VALUES (
@defCompId,
@compTypeId,
@ASSEMBLY,
'java',
'0',
'Impl.java',
'Impl.java',
'0',
'0',
'0',
'5',
'4',
'4',
''
);
ELSE
bp_loop:
LOOP
-- read the name from next row into the variables
FETCH propCur INTO defaultbacipropid1;
delete from defaultmonitorpoint where defaultbacipropertyid = defaultbacipropid1;
delete from defaultbaciproperty where defaultbacipropid = defaultbacipropid1;
-- check if the exit_loop flag has been set by mysql,
-- close the cursor and exit the loop if it has.
IF exit_loop THEN
CLOSE propCur;
LEAVE bp_loop;
END IF;
END LOOP bp_loop;
END IF;
end ;;
DELIMITER ;
call defcomp;
drop procedure defcomp;
SELECT '5: Inserting DefaultBaciProperties';
drop procedure if exists defbaci;
SELECT COUNT(propertyname) INTO @defaultBACIPropertyCount FROM defaultbaciProperty WHERE propertyname=@MP_Name AND defaultComponentId=@defCompId;
DELIMITER ;;
create procedure defbaci() begin
IF @defaultBACIPropertyCount=0 THEN
SELECT 'Property not found, it will be added...';
SELECT 'Inserting BACI Property', @MP_Name;
SELECT MAX(defaultBACIPropId) INTO @defaultBACIPropId FROM defaultbaciProperty;
SET @defaultBACIPropId=COALESCE(@defaultBACIPropId,0)+1;
INSERT INTO DefaultBACIProperty (
DEFAULTBACIPROPID,
DEFAULTCOMPONENTID,
PROPERTYNAME,
DESCRIPTION,
`FORMAT`,
UNITS,
RESOLUTION,
ARCHIVE_PRIORITY,
ARCHIVE_MIN_INT,
ARCHIVE_MAX_INT,
DEFAULT_TIMER_TRIG,
MIN_TIMER_TRIG,
INITIALIZE_DEVIO,
MIN_DELTA_TRIG,
DEFAULT_VALUE,
GRAPH_MIN,
GRAPH_MAX,
MIN_STEP,
ARCHIVE_DELTA,
ALARM_HIGH_ON,
ALARM_LOW_ON,
ALARM_HIGH_OFF,
ALARM_LOW_OFF,
ALARM_TIMER_TRIG,
MIN_VALUE,
MAX_VALUE,
BITDESCRIPTION,
WHENSET,
WHENCLEARED,
STATESDESCRIPTION,
`CONDITION`,
ALARM_ON,
ALARM_OFF,
`DATA`,
ALARM_FAULT_FAMILY,
ALARM_FAULT_MEMBER,
ALARM_LEVEL,
ARCHIVE_SUPPRESS,
ARCHIVE_MECHANISM)
VALUES (
@defaultBACIPropId,
@defCompId,
@MP_Name,
@MP_Description,
@MP_Format,
@MP_DisplayUnits,
'0',
'3',
'0',
@MP_Interval,
'1',
'1.',
'0.',
'0.',
'0.',
@MP_GraphMin,
@MP_GraphMax,
'0',
'0',
'0',
'0',
'0',
'0',
'0',
'-2147483648',
'2147483647',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'0',
@MP_archive_suppress,
'monitor_collector'
);
ELSE
SELECT 'Default BACI Property',@MP_NAME 'already exists... continue';
SELECT defaultBACIPropId INTO @defaultBACIPropId FROM defaultbaciProperty WHERE propertyname=@MP_NAME and defaultComponentId=@defCompId;
END IF;
SELECT COUNT(monitorPointName) INTO @monitorPropCount FROM defaultMonitorPoint WHERE defaultbacipropertyId=@defaultBACIPropId;
IF @monitorPropCount=0 THEN
SELECT MAX(defaultMonitorPointId) INTO @defaultMonPointId FROM defaultMonitorPoint;
SET @defaultMonPointId=COALESCE(@defaultMonPointId,0)+1;
INSERT INTO DefaultMonitorPoint (
DEFAULTMONITORPOINTID,
DEFAULTBACIPROPERTYID,
MONITORPOINTNAME,
INDICE,
DATATYPE,
RCA,
TERELATED,
RAWDATATYPE,
WORLDDATATYPE,
UNITS,
SCALE,
OFFSET,
MINRANGE,
MAXRANGE,
DESCRIPTION)
VALUES(
@defaultMonPointId,
@defaultBACIPropId,
@MP_Name,
'0',
@MP_DataType,
's=2',
'0',
@MP_DataType,
@MP_DataType,
@MP_DataUnits,
'1',
'0',
@MP_MinRange,
@MP_MaxRange,
@MP_Description
);
ELSE
SELECT 'WARNING: Found other Monitor Points associated with property',@MP_Name, 'Skipping unique monitor point insertion.';
END IF;
END ;;
DELIMITER ;
#for $idx in $range(0,$x["NRows"])
#if $x["IsMonitored"][$idx].upper() =="Y"
SET @MP_Name ='$x["Short name"][$idx]';
SET @MP_Description='$x["Description"][$idx]';
SET @MP_Format='na';
SET @MP_DisplayUnits='$x["Unit"][$idx]';
SET @MP_GraphMin=0;
SET @MP_GraphMax=0;
SET @MP_Interval=1;
SET @MP_archive_suppress='0';
#if $x["IsArchived"][$idx].upper() =="N"
SET @MP_archive_suppress='1';
#end if
SET @MP_MinRange=0;
SET @MP_MaxRange=0;
SET @MP_DataType='string';
SET @MP_DataUnits=@MP_DisplayUnits;
#end if
call defbaci;
#end for
drop procedure defbaci;
SELECT 'Transaction END';
pygen-21a3f6b8044f73b282015eeb4da264559761505c/templates/Alarms/ 0000775 0000000 0000000 00000000000 14142737031 0022544 5 ustar 00root root 0000000 0000000 pygen-21a3f6b8044f73b282015eeb4da264559761505c/templates/Alarms/Administrative/ 0000775 0000000 0000000 00000000000 14142737031 0025527 5 ustar 00root root 0000000 0000000 AlarmSystemConfiguration/ 0000775 0000000 0000000 00000000000 14142737031 0032441 5 ustar 00root root 0000000 0000000 pygen-21a3f6b8044f73b282015eeb4da264559761505c/templates/Alarms/Administrative AlarmSystemConfiguration.xml 0000775 0000000 0000000 00000000457 14142737031 0040165 0 ustar 00root root 0000000 0000000 pygen-21a3f6b8044f73b282015eeb4da264559761505c/templates/Alarms/Administrative/AlarmSystemConfiguration
CERN
pygen-21a3f6b8044f73b282015eeb4da264559761505c/templates/Alarms/Administrative/Categories/ 0000775 0000000 0000000 00000000000 14142737031 0027614 5 ustar 00root root 0000000 0000000 Categories.xml 0000775 0000000 0000000 00000001010 14142737031 0032337 0 ustar 00root root 0000000 0000000 pygen-21a3f6b8044f73b282015eeb4da264559761505c/templates/Alarms/Administrative/Categories
Test category 1
BaciPropTest#testDoubleVar
BaciPropTest#testPatternVar
TestFF
AnotherFF
pygen-21a3f6b8044f73b282015eeb4da264559761505c/templates/Alarms/Administrative/ReductionDefinitions/0000775 0000000 0000000 00000000000 14142737031 0031657 5 ustar 00root root 0000000 0000000 ReductionDefinitions.xml 0000775 0000000 0000000 00000000472 14142737031 0036460 0 ustar 00root root 0000000 0000000 pygen-21a3f6b8044f73b282015eeb4da264559761505c/templates/Alarms/Administrative/ReductionDefinitions
pygen-21a3f6b8044f73b282015eeb4da264559761505c/templates/Alarms/AlarmDefinitions/ 0000775 0000000 0000000 00000000000 14142737031 0025774 5 ustar 00root root 0000000 0000000 pygen-21a3f6b8044f73b282015eeb4da264559761505c/templates/Alarms/AlarmDefinitions/.DS_Store 0000775 0000000 0000000 00000020004 14142737031 0027456 0 ustar 00root root 0000000 0000000 Bud1 P r o p e r @ @ @ @ B A C I P r o p e r t ydsclbool B A C I P r o p e r t ylg1Scomp B A C I P r o p e r t ymoDDblob Y]bA B A C I P r o p e r t ymodDblob Y]bA B A C I P r o p e r t yph1Scomp B a c i P r o p T e s t # t e s t D o u b l e V a rlg1Scomp % B a c i P r o p T e s t # t e s t D o u b l e V a rmoDDblob Y]bA B a c i P r o p T e s t # t e s t D o u b l e V a rmodDblob Y]bA B a c i P r o p T e s t # t e s t D o u b l e V a rph1Scomp B a c i P r o p T e s t # t e s t E n u m V a rlg1Scomp # B a c i P r o p T e s t # t e s t E n u m V a rmoDDblob Y]bA B a c i P r o p T e s t # t e s t E n u m V a rmodDblob Y]bA B a c i P r o p T e s t # t e s t E n u m V a rph1Scomp B a c i P r o p T e s t # t e s t P a t t e r n V a rlg1Scomp &