generate_open62541CCode.py 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3. ###
  4. ### Author: Chris Iatrou (ichrispa@core-vector.net)
  5. ### Version: rev 14
  6. ###
  7. ### This program was created for educational purposes and has been
  8. ### contributed to the open62541 project by the author. All licensing
  9. ### terms for this source is inherited by the terms and conditions
  10. ### specified for by the open62541 project (see the projects readme
  11. ### file for more information on the LGPL terms and restrictions).
  12. ###
  13. ### This program is not meant to be used in a production environment. The
  14. ### author is not liable for any complications arising due to the use of
  15. ### this program.
  16. ###
  17. from __future__ import print_function
  18. from ua_namespace import *
  19. import logging
  20. import argparse
  21. from open62541_XMLPreprocessor import open62541_XMLPreprocessor
  22. logger = logging.getLogger(__name__)
  23. parser = argparse.ArgumentParser(
  24. description="""Parse OPC UA NamespaceXML file(s) and create C code for generating nodes in open62541
  25. generate_open62541CCode.py will first read all XML files passed on the command line, then link and check the namespace. All nodes that fulfill the basic requirements will then be printed as C-Code intended to be included in the open62541 OPC UA Server that will initialize the corresponding namespace.""",
  26. formatter_class=argparse.RawDescriptionHelpFormatter)
  27. parser.add_argument('infiles',
  28. metavar="<namespaceXML>",
  29. nargs='+',
  30. type=argparse.FileType('r'),
  31. help='Namespace XML file(s). Note that the last definition of a node encountered will be used and all prior definitions are discarded.')
  32. parser.add_argument('outputFile',
  33. metavar='<outputFile>',
  34. #type=argparse.FileType('w', 0),
  35. help='The basename for the <output file>.c and <output file>.h files to be generated. This will also be the function name used in the header and c-file.')
  36. parser.add_argument('-i','--ignore',
  37. metavar="<ignoreFile>",
  38. type=argparse.FileType('r'),
  39. action='append',
  40. dest="ignoreFiles",
  41. default=[],
  42. help='Loads a list of NodeIDs stored in ignoreFile (one NodeID per line). The compiler will assume that these nodes have been created externally and not generate any code for them. They will however be linked to from other nodes.')
  43. parser.add_argument('-b','--blacklist',
  44. metavar="<blacklistFile>",
  45. type=argparse.FileType('r'),
  46. action='append',
  47. dest="blacklistFiles",
  48. default=[],
  49. help='Loads a list of NodeIDs stored in blacklistFile (one NodeID per line). Any of the nodeIds encountered in this file will be removed from the namespace prior to compilation. Any references to these nodes will also be removed')
  50. parser.add_argument('-s','--suppress',
  51. metavar="<attribute>",
  52. action='append',
  53. dest="suppressedAttributes",
  54. choices=['description', 'browseName', 'displayName', 'writeMask', 'userWriteMask','nodeid'],
  55. default=[],
  56. help="Suppresses the generation of some node attributes. Currently supported options are 'description', 'browseName', 'displayName', 'writeMask', 'userWriteMask' and 'nodeid'.")
  57. parser.add_argument('-v','--verbose', action='count', help='Make the script more verbose. Can be applied up to 4 times')
  58. args = parser.parse_args()
  59. level = logging.CRITICAL
  60. verbosity = 0
  61. if args.verbose:
  62. verbosity = int(args.verbose)
  63. if (verbosity==1):
  64. level = logging.ERROR
  65. elif (verbosity==2):
  66. level = logging.WARNING
  67. elif (verbosity==3):
  68. level = logging.INFO
  69. elif (verbosity>=4):
  70. level = logging.DEBUG
  71. logging.basicConfig(level=level)
  72. logger.setLevel(logging.INFO)
  73. # Creating the header is tendious. We can skip the entire process if
  74. # the header exists.
  75. #if path.exists(argv[-1]+".c") or path.exists(argv[-1]+".h"):
  76. # log(None, "File " + str(argv[-1]) + " does already exists.", LOG_LEVEL_INFO)
  77. # log(None, "Header generation will be skipped. Delete the header and rerun this script if necessary.", LOG_LEVEL_INFO)
  78. # exit(0)
  79. # Open the output file
  80. outfileh = open(args.outputFile+".h", r"w+")
  81. outfilec = open(args.outputFile+".c", r"w+")
  82. # Create a new namespace. Note that the namespace name is not significant.
  83. ns = opcua_namespace("open62541")
  84. # Clean up the XML files by removing duplicate namespaces and unwanted prefixes
  85. preProc = open62541_XMLPreprocessor()
  86. for xmlfile in args.infiles:
  87. logger.info("Preprocessing " + str(xmlfile.name))
  88. preProc.addDocument(xmlfile.name)
  89. preProc.preprocessAll()
  90. # Parse the XML files
  91. for xmlfile in preProc.getPreProcessedFiles():
  92. logger.info("Parsing " + str(xmlfile))
  93. ns.parseXML(xmlfile)
  94. # We need to notify the open62541 server of the namespaces used to be able to use i.e. ns=3
  95. namespaceArrayNames = preProc.getUsedNamespaceArrayNames()
  96. for key in namespaceArrayNames:
  97. ns.addNamespace(key, namespaceArrayNames[key])
  98. # Remove any temp files - they are not needed after the AST is created
  99. preProc.removePreprocessedFiles()
  100. # Remove blacklisted nodes from the namespace
  101. # Doing this now ensures that unlinkable pointers will be cleanly removed
  102. # during sanitation.
  103. for blacklist in args.blacklistFiles:
  104. for line in blacklist.readlines():
  105. line = line.replace(" ","")
  106. id = line.replace("\n","")
  107. if ns.getNodeByIDString(id) == None:
  108. logger.info("Can't blacklist node, namespace does currently not contain a node with id " + str(id))
  109. else:
  110. ns.removeNodeById(line)
  111. blacklist.close()
  112. # Link the references in the namespace
  113. logger.info("Linking namespace nodes and references")
  114. ns.linkOpenPointers()
  115. # Remove nodes that are not printable or contain parsing errors, such as
  116. # unresolvable or no references or invalid NodeIDs
  117. ns.sanitize()
  118. # Parse Datatypes in order to find out what the XML keyed values actually
  119. # represent.
  120. # Ex. <rpm>123</rpm> is not encodable
  121. # only after parsing the datatypes, it is known that
  122. # rpm is encoded as a double
  123. logger.info("Building datatype encoding rules")
  124. ns.buildEncodingRules()
  125. # Allocate/Parse the data values. In order to do this, we must have run
  126. # buidEncodingRules.
  127. logger.info("Allocating variables")
  128. ns.allocateVariables()
  129. # Users may have manually defined some nodes in their code already (such as serverStatus).
  130. # To prevent those nodes from being reprinted, we will simply mark them as already
  131. # converted to C-Code. That way, they will still be referred to by other nodes, but
  132. # they will not be created themselves.
  133. ignoreNodes = []
  134. for ignore in args.ignoreFiles:
  135. for line in ignore.readlines():
  136. line = line.replace(" ","")
  137. id = line.replace("\n","")
  138. if ns.getNodeByIDString(id) == None:
  139. logger.warn("Can't ignore node, Namespace does currently not contain a node with id " + str(id))
  140. else:
  141. ignoreNodes.append(ns.getNodeByIDString(id))
  142. ignore.close()
  143. # Create the C Code
  144. logger.info("Generating Header")
  145. # Returns a tuple of (["Header","lines"],["Code","lines","generated"])
  146. from os.path import basename
  147. generatedCode = ns.printOpen62541Header(ignoreNodes, args.suppressedAttributes, outfilename=basename(args.outputFile))
  148. for line in generatedCode[0]:
  149. outfileh.write(line+"\n")
  150. for line in generatedCode[1]:
  151. outfilec.write(line+"\n")
  152. outfilec.close()
  153. outfileh.close()
  154. logger.info("Namespace generation code successfully printed")