for mname in interface['methods']: method = interface['methods'][mname] outValues = [] if method['return'] != 'void': outValues.append([method['return'], 'ret']) paramStrA = '' for p in method['params']: if p['decorator'] == 'out': outValues.append([p['type'], p['name']]) else: paramStrA += ', ' + p['name'] cog.outl('') cog.outl('<TABHERE>#') cog.outl('<TABHERE># ' + 'SUBSCRIPTION to '+ method['name'] +' method from ' + interface['name'] + ' interface') cog.outl('<TABHERE>#') if not communicationIsIce(imp): cog.outl('<TABHERE>def ROS' + interface['name'] + "_" + method['name'] + '(self' + paramStrA + "):") else: cog.outl('<TABHERE>def ' + interface['name'] + "_" + method['name'] + '(self' + paramStrA + "):") if method['return'] != 'void': cog.outl("<TABHERE><TABHERE>ret = "+method['return']+'()') cog.outl("<TABHERE><TABHERE>#") cog.outl("<TABHERE><TABHERE>#subscribesToCODE") cog.outl("<TABHERE><TABHERE>#") if len(outValues) == 0: cog.outl("<TABHERE><TABHERE>pass\n") elif len(outValues) == 1: if method['return'] != 'void': cog.outl("<TABHERE><TABHERE>return ret\n") else: cog.outl("<TABHERE><TABHERE>"+outValues[0][1]+" = "+replaceTypeCPP2Python(outValues[0][0])+"()") cog.outl("<TABHERE><TABHERE>return "+outValues[0][1]+"\n")
params[1] = '--Ice.Config=' + params[1] elif len(params) == 1: params.append('--Ice.Config=config') ic = Ice.initialize(params) status = 0 mprx = {} parameters = {} for i in ic.getProperties(): parameters[str(i)] = str(ic.getProperties().getProperty(i)) [[[cog try: needIce = False needStorm = False for req in component['requires']: if communicationIsIce(req): needIce = True for imp in component['implements']: if communicationIsIce(imp): needIce = True for pub in component['publishes']: if communicationIsIce(pub): needIce = True needStorm = True for sub in component['subscribesTo']: if communicationIsIce(sub): needIce = True needStorm = True if needStorm: cog.outl(""" <TABHERE># Topic Manager <TABHERE>proxy = ic.getProperties().getProperty("TopicManager.Proxy")
def generarH(idslFile, imported): idsl = gimmeIDSLStruct(idslFile, files='', includeDirectories=includeDirectories) os.system("rm -f " + outputPath + "/" + idsl['module']['name'] + "ROS/msg/__init__.py") os.system("rm -f " + outputPath + "/" + idsl['module']['name'] + "ROS/srv/__init__.py") for imp in idsl['module']['contents']: if imp['type'] in ['struct', 'sequence']: for f in ["SERVANT.MSG"]: ofile = outputPath + "/" + imp['name'] + "." + f.split( '.')[-1].lower() print('Generating', ofile, ' (servant for', idslFile.split('.')[0].lower() + ')') # Call cog run = "cog.py -z -d" + ' -D theIDSLPaths=' + '#'.join( includeDirectories ) + " -D structName=" + imp[ 'name'] + " -D theIDSL=" + idslFile + " -o " + ofile + " " + "/opt/robocomp/share/robocompdsl/templateCPP/" + f run = run.split(' ') ret = Cog().main(run) if ret != 0: print('ERROR') sys.exit(-1) replaceTagsInFile(ofile) commandCPP = "/opt/ros/melodic/lib/gencpp/gen_cpp.py " + ofile + " -Istd_msgs:/opt/ros/melodic/share/std_msgs/msg -I" + idsl[ 'module']['name'] + "ROS:" + outputPath commandPY = "/opt/ros/melodic/lib/genpy/genmsg_py.py " + ofile + " -Istd_msgs:/opt/ros/melodic/share/std_msgs/msg -I" + idsl[ 'module']['name'] + "ROS:" + outputPath for impo in imported: if not impo == idsl['module']['name'] + "ROS": commandCPP = commandCPP + " -I" + impo + ":" + outputPath commandPY = commandPY + " -I" + impo + ":" + outputPath if not os.path.exists(outputPath): create_directory(outputPath) commandCPP = commandCPP + " -p " + idsl['module'][ 'name'] + "ROS -o " + outputPath + "/" + idsl['module'][ 'name'] + "ROS -e /opt/ros/melodic/share/gencpp" commandPY = commandPY + " -p " + idsl['module'][ 'name'] + "ROS -o " + outputPath + "/" + idsl[ 'module']['name'] + "ROS/msg" if comp['language'].lower() == 'cpp': os.system(commandCPP) else: os.system(commandPY) try: fileInit = open( outputPath + "/" + idsl['module']['name'] + "ROS/msg/__init__.py", 'a') fileInit.write("from ._" + imp['name'] + " import *\n") fileInit.close() except: pass for imp in idsl['module']['contents']: if imp['type'] == 'interface': for ima in component['implements'] + component['requires']: im = ima if type(im) != type(''): im = im[0] if not communicationIsIce(ima) and im == imp['name']: for method in imp['methods']: if 'params' in method: if len(method['params']) == 2: for f in ["SERVANT.SRV"]: ofile = outputPath + "/" + method[ 'name'] + "." + f.split( '.')[-1].lower() print( 'Generating', ofile, ' (servant for', idslFile.split('.')[0].lower() + ')') # Call cog run = "cog.py -z -d" + ' -D theIDSLPaths=' + '#'.join( includeDirectories ) + " -D methodName=" + method[ 'name'] + " -D theIDSL=" + idslFile + " -o " + ofile + " " + "/opt/robocomp/share/robocompdsl/templateCPP/" + f run = run.split(' ') ret = Cog().main(run) if ret != 0: print('ERROR') sys.exit(-1) replaceTagsInFile(ofile) commandCPP = "/opt/ros/melodic/lib/gencpp/gen_cpp.py " + ofile + " -Istd_msgs:/opt/ros/melodic/share/std_msgs/msg -Istd_srvs:/opt/ros/melodic/share/std_srv/cmake/../srv -I" + idsl[ 'module'][ 'name'] + "ROS:" + outputPath commandPY = "/opt/ros/melodic/lib/genpy/gensrv_py.py " + ofile + " -Istd_msgs:/opt/ros/melodic/share/std_msgs/msg -Istd_srvs:/opt/ros/kinetic/share/std_srv/cmake/../srv -I" + idsl[ 'module'][ 'name'] + "ROS:" + outputPath for impo in imported: if not impo == idsl['module'][ 'name'] + "ROS": commandCPP = commandCPP + " -I" + impo + ":" + outputPath commandPY = commandPY + " -I" + impo + ":" + outputPath if not os.path.exists(outputPath): create_directory(outputPath) commandCPP = commandCPP + " -p " + idsl[ 'module'][ 'name'] + "ROS -o " + outputPath + "/" + idsl[ 'module'][ 'name'] + "ROS -e /opt/ros/melodic/share/gencpp/cmake/.." commandPY = commandPY + " -p " + idsl[ 'module'][ 'name'] + "ROS -o " + outputPath + "/" + idsl[ 'module'][ 'name'] + "ROS/srv" if comp['language'].lower() == 'cpp': os.system(commandCPP) else: os.system(commandPY) try: fileInit = open( outputPath + "/" + idsl['module']['name'] + "ROS/srv/__init__.py", 'a') fileInit.write("from ._" + method['name'] + " import *\n") fileInit.close() except: pass else: print( "error: ROS service with incorrect number of parameters. ROS only supports remote procedure calls of the form: void method(type inVar, out type outVar);" ) for param in enumerate(method['params']): print(param[0], '-->', param[1]) sys.exit(-1) else: print( "error: service without params. Form is: void method(type inVar, out type outVar);" ) sys.exit(-1) os.system("touch " + outputPath + "/" + idsl['module']['name'] + "ROS/__init__.py") return idsl['module']['name'] + "ROS"
def main(): parser = MyParser( description= 'This application create components files from cdsl files or .ice from idsl\n' '\ta) to generate code from a CDSL file: ' + sys.argv[0].split('/')[-1] + ' INPUT_FILE.CDSL OUTPUT_PATH\n' + '\tb) to generate a new CDSL file: ' + sys.argv[0].split('/')[-1] + ' NEW_COMPONENT_DESCRIPTOR.CDSL', formatter_class=argparse.RawTextHelpFormatter) parser.add_argument("-I", "--include_dirs", nargs='*', help="Include directories", action=FullPaths, default=[]) parser.add_argument("-d", '--diff', dest='diff', choices=DIFF_TOOLS, action='store') parser.add_argument("input_file", help="The input dsl file") parser.add_argument("output_path", nargs='?', help="The path to put the files") args = parser.parse_args() if args.output_path is None: if args.input_file.endswith(".cdsl"): generateDummyCDSL(args.input_file) generateDummySMDSL("statemachine.smdsl") sys.exit(0) else: print(args.output_path, args.input_file) print(parser.error("No output path with non .cdsl file")) sys.exit(-1) inputFile = args.input_file outputPath = args.output_path sys.path.append('/opt/robocomp/python') new_existing_files = {} if inputFile.endswith(".cdsl"): component = DSLFactory().from_file( inputFile, includeDirectories=args.include_dirs) imports = ''.join([imp + '#' for imp in component['imports']]) # verification pool = IDSLPool(imports, args.include_dirs) interface_list = component['requires'] + component[ 'implements'] + component['subscribesTo'] + component['publishes'] for interface_required in interface_list: interface_required = interface_required if isinstance( interface_required, str) else interface_required[0] if not pool.moduleProviding(interface_required): raise rcExceptions.InterfaceNotFound(interface_required, pool.interfaces()) if component['language'].lower( ) == 'cpp' or component['language'].lower() == 'cpp11': # # Check output directory # if not os.path.exists(outputPath): create_directory(outputPath) # Create directories within the output directory try: create_directory(outputPath + "/bin") create_directory(outputPath + "/etc") create_directory(outputPath + "/src") except: print('There was a problem creating a directory') sys.exit(1) pass # # Generate regular files # files = [ 'CMakeLists.txt', 'DoxyFile', 'README-STORM.txt', 'README.md', 'etc/config', 'src/main.cpp', 'src/CMakeLists.txt', 'src/CMakeListsSpecific.txt', 'src/commonbehaviorI.h', 'src/commonbehaviorI.cpp', 'src/genericmonitor.h', 'src/genericmonitor.cpp', 'src/config.h', 'src/specificmonitor.h', 'src/specificmonitor.cpp', 'src/genericworker.h', 'src/genericworker.cpp', 'src/specificworker.h', 'src/specificworker.cpp', 'src/mainUI.ui' ] specificFiles = [ 'src/specificworker.h', 'src/specificworker.cpp', 'src/CMakeListsSpecific.txt', 'src/mainUI.ui', 'src/specificmonitor.h', 'src/specificmonitor.cpp', 'README.md', 'etc/config' ] for f in files: ofile = outputPath + '/' + f if f in specificFiles and os.path.exists(ofile): print('Not overwriting specific file "' + ofile + '", saving it to ' + ofile + '.new') new_existing_files[os.path.abspath( ofile)] = os.path.abspath(ofile) + '.new' ofile += '.new' ifile = "/opt/robocomp/share/robocompdsl/templateCPP/" + f if f != 'src/mainUI.ui' or component['gui'] is not None: print('Generating', ofile) run = "cog.py -z -d -D theCDSL=" + inputFile + " -D theIDSLs=" + imports + ' -D theIDSLPaths=' + '#'.join( args.include_dirs) + " -o " + ofile + " " + ifile run = run.split(' ') ret = Cog().main(run) if ret != 0: print('ERROR') sys.exit(-1) replaceTagsInFile(ofile) # # Generate interface-dependent files # for ima in component['implements']: im = ima if type(im) != type(''): im = im[0] if communicationIsIce(ima): for f in ["SERVANT.H", "SERVANT.CPP"]: ofile = outputPath + '/src/' + im.lower( ) + 'I.' + f.split('.')[-1].lower() print('Generating ', ofile, ' (servant for', im + ')') # Call cog run = "cog.py -z -d -D theCDSL=" + inputFile + " -D theIDSLs=" + imports + ' -D theIDSLPaths=' + '#'.join( args.include_dirs ) + " -D theInterface=" + im + " -o " + ofile + " " + "/opt/robocomp/share/robocompdsl/templateCPP/" + f run = run.split(' ') ret = Cog().main(run) if ret != 0: print('ERROR') sys.exit(-1) replaceTagsInFile(ofile) for imp in component['subscribesTo']: im = imp if type(im) != type(''): im = im[0] if communicationIsIce(imp): for f in ["SERVANT.H", "SERVANT.CPP"]: ofile = outputPath + '/src/' + im.lower( ) + 'I.' + f.split('.')[-1].lower() print('Generating ', ofile, ' (servant for', im + ')') # Call cog theInterfaceStr = im if type(theInterfaceStr) == type([]): theInterfaceStr = str(';'.join(im)) run = "cog.py -z -d -D theCDSL=" + inputFile + " -D theIDSLs=" + imports + ' -D theIDSLPaths=' + '#'.join( args.include_dirs ) + " -D theInterface=" + theInterfaceStr + " -o " + ofile + " " + "/opt/robocomp/share/robocompdsl/templateCPP/" + f #print(run run = run.split(' ') ret = Cog().main(run) if ret != 0: print('ERROR') sys.exit(-1) replaceTagsInFile(ofile) elif component['language'].lower() == 'python': # # Check output directory # if not os.path.exists(outputPath): create_directory(outputPath) # Create directories within the output directory try: create_directory(outputPath + "/etc") create_directory(outputPath + "/src") except: print('There was a problem creating a directory') sys.exit(1) pass needStorm = False for pub in component['publishes']: if communicationIsIce(pub): needStorm = True for sub in component['subscribesTo']: if communicationIsIce(sub): needStorm = True # # Generate regular files # files = [ 'CMakeLists.txt', 'DoxyFile', 'README-STORM.txt', 'README.md', 'etc/config', 'src/main.py', 'src/genericworker.py', 'src/specificworker.py', 'src/mainUI.ui' ] specificFiles = [ 'src/specificworker.py', 'src/mainUI.ui', 'README.md', 'etc/config' ] for f in files: if f == 'src/main.py': ofile = outputPath + '/src/' + component['name'] + '.py' else: ofile = outputPath + '/' + f if f in specificFiles and os.path.exists(ofile): print('Not overwriting specific file "' + ofile + '", saving it to ' + ofile + '.new') new_existing_files[os.path.abspath( ofile)] = os.path.abspath(ofile) + '.new' ofile += '.new' ifile = "/opt/robocomp/share/robocompdsl/templatePython/" + f ignoreFile = False if f == 'src/mainUI.ui' and component['gui'] is None: ignoreFile = True if f == 'CMakeLists.txt' and component['gui'] is None: ignoreFile = True if f == 'README-STORM.txt' and needStorm == False: ignoreFile = True if not ignoreFile: print('Generating', ofile) run = "cog.py -z -d -D theCDSL=" + inputFile + " -D theIDSLs=" + imports + ' -D theIDSLPaths=' + '#'.join( args.include_dirs) + " -o " + ofile + " " + ifile run = run.split(' ') ret = Cog().main(run) if ret != 0: print('ERROR') sys.exit(-1) replaceTagsInFile(ofile) if f == 'src/main.py': os.chmod(ofile, os.stat(ofile).st_mode | 0o111) # # Generate interface-dependent files # for imp in component['implements'] + component['subscribesTo']: if type(imp) != type(''): im = imp[0] else: im = imp if communicationIsIce(imp): for f in ["SERVANT.PY"]: ofile = outputPath + '/src/' + im.lower( ) + 'I.' + f.split('.')[-1].lower() print('Generating', ofile, ' (servant for', im + ')') # Call cog run = "cog.py -z -d -D theCDSL=" + inputFile + " -D theIDSLs=" + imports + ' -D theIDSLPaths=' + '#'.join( args.include_dirs ) + " -D theInterface=" + im + " -o " + ofile + " " + "/opt/robocomp/share/robocompdsl/templatePython/" + f run = run.split(' ') ret = Cog().main(run) if ret != 0: print('ERROR') sys.exit(-1) replaceTagsInFile(ofile) else: print('Unsupported language', component['language']) if component['usingROS'] == True: for imp in component['imports']: generateROSHeaders(imp, outputPath + "/src", component, args.include_dirs) # Code to launch diff tool on .new files to be compared with their old version if args.diff is not None: diff_tool, _ = get_diff_tool(prefered=args.diff) print( "Executing diff tool for existing files. Close if no change is needed." ) for o_file, n_file in new_existing_files.items(): if not filecmp.cmp(o_file, n_file): print([diff_tool, o_file, n_file]) try: subprocess.call([diff_tool, o_file, n_file]) except KeyboardInterrupt as e: print( "Comparasion interrupted. All files have been generated. Check this .new files manually:" ) for o_file2, n_file2 in new_existing_files.items(): if not filecmp.cmp(o_file2, n_file2): print("%s %s" % (o_file2, n_file2)) break except Exception as e: print("Exception trying to execute %s" % (diff_tool)) print(e.message) else: print("Binary equal files %s and %s" % (o_file, n_file)) elif inputFile.endswith(".idsl"): # idsl = IDSLParsing.fromFileIDSL(inputFile) print('Generating ICE file ', outputPath) # Call cog run = "cog.py -z -d" + " -D theIDSL=" + inputFile + ' -D theIDSLPaths=' + '#'.join( args.include_dirs ) + " -o " + outputPath + " /opt/robocomp/share/robocompdsl/TEMPLATE.ICE" run = run.split(' ') ret = Cog().main(run) if ret != 0: print('ERROR') sys.exit(-1) replaceTagsInFile(outputPath)
def string_to_struct(self, string, **kwargs): parsing_result = self.parse_string(string) component = OrderedDict() # print 'parseCDSL.component', includeDirectories if self._include_directories == None: self._include_directories = [] if "include_directories" in kwargs: self._include_directories = kwargs["include_directories"] # Set options component['options'] = [] try: for op in parsing_result['component']['content']['options']: component['options'].append(op.lower()) except: traceback.print_exc() # Component name component['name'] = parsing_result['component']['name'] # Imports component['imports'] = [] component['recursiveImports'] = [] try: imprts = [ path['idsl_path'] for path in parsing_result.asDict()["imports"] ] except: parsing_result['imports'] = [] imprts = [] if isAGM1Agent(component): imprts.extend([ 'AGMExecutive.idsl', 'AGMCommonBehavior.idsl', 'AGMWorldModel.idsl', 'AGMExecutiveTopic.idsl' ]) if isAGM2Agent(component): imprts.extend(['AGM2.idsl']) iD = self._include_directories + [ '/opt/robocomp/interfaces/IDSLs/', os.path.expanduser('~/robocomp/interfaces/IDSLs/') ] for imp in sorted(imprts): import_basename = os.path.basename(imp) component['imports'].append(import_basename) component['recursiveImports'] = generateRecursiveImports( component['imports'], self._include_directories) # Language component['language'] = parsing_result['component']['content'][ 'language'] # Statemachine component['statemachine'] = None try: statemachine = parsing_result['component']['content'][ 'statemachine']['machine_path'] component['statemachine'] = statemachine except: pass try: statemachine_visual = parsing_result['component']['content'][ 'statemachine']['visual'] except: component['statemachine_visual'] = False else: component['statemachine_visual'] = statemachine_visual # innermodelviewer component['innermodelviewer'] = False try: component['innermodelviewer'] = 'innermodelviewer' in [ x.lower() for x in component['options'] ] pass except: pass # GUI component['gui'] = None try: uiT = parsing_result['component']['content']['gui'][0] uiI = parsing_result['component']['content']['gui']['gui_options'] if uiT.lower() == 'qt' and uiI in [ 'QWidget', 'QMainWindow', 'QDialog' ]: component['gui'] = [uiT, uiI] pass else: print(('Wrong UI specification', parsing_result['properties']['gui'])) sys.exit(1) except: # TODO: check exceptions and do something when accessing gui options fails. pass # Communications component['rosInterfaces'] = [] component['iceInterfaces'] = [] component['implements'] = [] component['requires'] = [] component['publishes'] = [] component['subscribesTo'] = [] component['usingROS'] = False #################### com_types = ['implements', 'requires', 'publishes', 'subscribesTo'] communications = parsing_result['component']['content'][ 'communications'] for comm_type in com_types: if comm_type in communications: interfaces = sorted(communications[comm_type]) for interface in interfaces: component[comm_type].append(interface) if communicationIsIce(interface): component['iceInterfaces'].append(interface) else: component['rosInterfaces'].append(interface) component['usingROS'] = True # Handle options for communications if isAGM1Agent(component): component['iceInterfaces'] += [ 'AGMCommonBehavior', 'AGMExecutive', 'AGMExecutiveTopic', 'AGMWorldModel' ] if not 'AGMCommonBehavior' in component['implements']: component['implements'] = ['AGMCommonBehavior' ] + component['implements'] if not 'AGMExecutive' in component['requires']: component['requires'] = ['AGMExecutive' ] + component['requires'] if not 'AGMExecutiveTopic' in component['subscribesTo']: component['subscribesTo'] = ['AGMExecutiveTopic' ] + component['subscribesTo'] if isAGM2Agent(component): if isAGM2AgentROS(component): component['usingROS'] = True agm2agent_requires = [['AGMDSRService', 'ros']] agm2agent_subscribesTo = [['AGMExecutiveTopic', 'ros'], ['AGMDSRTopic', 'ros']] if not 'AGMDSRService' in component['rosInterfaces']: component['rosInterfaces'].append('AGMDSRService') if not 'AGMDSRTopic' in component['rosInterfaces']: component['rosInterfaces'].append('AGMDSRTopic') if not 'AGMExecutiveTopic' in component['rosInterfaces']: component['rosInterfaces'].append('AGMExecutiveTopic') else: agm2agent_requires = [['AGMDSRService', 'ice']] agm2agent_subscribesTo = [['AGMExecutiveTopic', 'ice'], ['AGMDSRTopic', 'ice']] if not 'AGMDSRService' in component['iceInterfaces']: component['iceInterfaces'].append('AGMDSRService') if not 'AGMDSRTopic' in component['iceInterfaces']: component['iceInterfaces'].append('AGMDSRTopic') if not 'AGMExecutiveTopic' in component['iceInterfaces']: component['iceInterfaces'].append('AGMExecutiveTopic') # AGM2 agents REQUIRES for agm2agent_req in agm2agent_requires: if not agm2agent_req in component['requires']: component['requires'] = [agm2agent_req ] + component['requires'] # AGM2 agents SUBSCRIBES for agm2agent_sub in agm2agent_subscribesTo: if not agm2agent_sub in component['subscribesTo']: component['subscribesTo'] = [agm2agent_sub ] + component['subscribesTo'] self.struct = component return component
cog.outl('<TABHERE><TABHERE>Ice.loadSlice(wholeStr)') cog.outl('<TABHERE><TABHERE>ice_'+name+' = True') cog.outl('<TABHERE><TABHERE>break') cog.outl('if not ice_'+name+':') cog.outl("<TABHERE>print('Couln\\\'t load "+name+"')") cog.outl('<TABHERE>sys.exit(-1)') module = gimmeIDSL(file_name, files='', includeDirectories=includeDirectories) cog.outl('from '+ module['name'] +' import *') ]]] [[[end]]] [[[cog for im in component['implements'] + component['subscribesTo']: if communicationIsIce(im): cog.outl('from ' + im.lower() + 'I import *') ]]] [[[end]]] [[[cog if component['usingROS'] == True: cog.outl('import rospy') cog.outl('from std_msgs.msg import *') msgIncludes = {} for imp in component['publishes']: if type(imp) == str: im = imp else: im = imp[0] if not communicationIsIce(imp):