nodeset_compiler.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # This Source Code Form is subject to the terms of the Mozilla Public
  4. # License, v. 2.0. If a copy of the MPL was not distributed with this
  5. # file, You can obtain one at http://mozilla.org/MPL/2.0/.
  6. ###
  7. ### Authors:
  8. ### - Chris Iatrou (ichrispa@core-vector.net)
  9. ### - Julius Pfrommer
  10. ### - Stefan Profanter (profanter@fortiss.org)
  11. ###
  12. ### This program was created for educational purposes and has been
  13. ### contributed to the open62541 project by the author. All licensing
  14. ### terms for this source is inherited by the terms and conditions
  15. ### specified for by the open62541 project (see the projects readme
  16. ### file for more information on the MPLv2 terms and restrictions).
  17. ###
  18. ### This program is not meant to be used in a production environment. The
  19. ### author is not liable for any complications arising due to the use of
  20. ### this program.
  21. ###
  22. import logging
  23. import argparse
  24. from datatypes import NodeId
  25. from nodeset import *
  26. parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter)
  27. parser.add_argument('-e', '--existing',
  28. metavar="<existingNodeSetXML>",
  29. type=argparse.FileType('rb'),
  30. dest="existing",
  31. action='append',
  32. default=[],
  33. help='NodeSet XML files with nodes that are already present on the server.')
  34. parser.add_argument('-x', '--xml',
  35. metavar="<nodeSetXML>",
  36. type=argparse.FileType('rb'),
  37. action='append',
  38. dest="infiles",
  39. default=[],
  40. help='NodeSet XML files with nodes that shall be generated.')
  41. parser.add_argument('outputFile',
  42. metavar='<outputFile>',
  43. help='The path/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.')
  44. parser.add_argument('--internal-headers',
  45. action='store_true',
  46. dest="internal_headers",
  47. help='Include internal headers instead of amalgamated header')
  48. parser.add_argument('-b', '--blacklist',
  49. metavar="<blacklistFile>",
  50. type=argparse.FileType('r'),
  51. action='append',
  52. dest="blacklistFiles",
  53. default=[],
  54. 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 nodeset prior to compilation. Any references to these nodes will also be removed')
  55. parser.add_argument('-i', '--ignore',
  56. metavar="<ignoreFile>",
  57. type=argparse.FileType('r'),
  58. action='append',
  59. dest="ignoreFiles",
  60. default=[],
  61. help='Loads a list of NodeIDs stored in ignoreFile (one NodeID per line). Any of the nodeIds encountered in this file will be kept in the nodestore but not printed in the generated code')
  62. parser.add_argument('-t', '--types-array',
  63. metavar="<typesArray>",
  64. action='append',
  65. type=str,
  66. dest="typesArray",
  67. default=[],
  68. help='Types array for the given namespace. Can be used mutliple times to define (in the same order as the .xml files, first for --existing, then --xml) the type arrays')
  69. parser.add_argument('-v', '--verbose', action='count',
  70. default=1,
  71. help='Make the script more verbose. Can be applied up to 4 times')
  72. parser.add_argument('--backend',
  73. default='open62541',
  74. const='open62541',
  75. nargs='?',
  76. choices=['open62541', 'graphviz'],
  77. help='Backend for the output files (default: %(default)s)')
  78. args = parser.parse_args()
  79. # Set up logging
  80. logger = logging.getLogger(__name__)
  81. logger.setLevel(logging.INFO)
  82. verbosity = 0
  83. if args.verbose:
  84. verbosity = int(args.verbose)
  85. if (verbosity == 1):
  86. logging.basicConfig(level=logging.ERROR)
  87. elif (verbosity == 2):
  88. logging.basicConfig(level=logging.WARNING)
  89. elif (verbosity == 3):
  90. logging.basicConfig(level=logging.INFO)
  91. elif (verbosity >= 4):
  92. logging.basicConfig(level=logging.DEBUG)
  93. else:
  94. logging.basicConfig(level=logging.CRITICAL)
  95. # Create a new nodeset. The nodeset name is not significant.
  96. # Parse the XML files
  97. ns = NodeSet()
  98. nsCount = 0
  99. loadedFiles = list()
  100. def getTypesArray(nsIdx):
  101. if nsIdx < len(args.typesArray):
  102. return args.typesArray[nsIdx]
  103. else:
  104. return "UA_TYPES"
  105. for xmlfile in args.existing:
  106. if xmlfile.name in loadedFiles:
  107. logger.info("Skipping Nodeset since it is already loaded: {} ".format(xmlfile.name))
  108. continue
  109. loadedFiles.append(xmlfile.name)
  110. logger.info("Preprocessing (existing) " + str(xmlfile.name))
  111. ns.addNodeSet(xmlfile, True, typesArray=getTypesArray(nsCount))
  112. nsCount +=1
  113. for xmlfile in args.infiles:
  114. if xmlfile.name in loadedFiles:
  115. logger.info("Skipping Nodeset since it is already loaded: {} ".format(xmlfile.name))
  116. continue
  117. loadedFiles.append(xmlfile.name)
  118. logger.info("Preprocessing " + str(xmlfile.name))
  119. ns.addNodeSet(xmlfile, typesArray=getTypesArray(nsCount))
  120. nsCount +=1
  121. # # We need to notify the open62541 server of the namespaces used to be able to use i.e. ns=3
  122. # namespaceArrayNames = preProc.getUsedNamespaceArrayNames()
  123. # for key in namespaceArrayNames:
  124. # ns.addNamespace(key, namespaceArrayNames[key])
  125. # Remove blacklisted nodes from the nodeset
  126. # Doing this now ensures that unlinkable pointers will be cleanly removed
  127. # during sanitation.
  128. for blacklist in args.blacklistFiles:
  129. for line in blacklist.readlines():
  130. line = line.replace(" ", "")
  131. id = line.replace("\n", "")
  132. if ns.getNodeByIDString(id) is None:
  133. logger.info("Can't blacklist node, namespace does currently not contain a node with id " + str(id))
  134. else:
  135. ns.removeNodeById(line)
  136. blacklist.close()
  137. # Set the nodes from the ignore list to hidden. This removes them from dependency calculation
  138. # and from printing their generated code.
  139. # These nodes should be already pre-created on the server to avoid any errors during
  140. # creation.
  141. for ignoreFile in args.ignoreFiles:
  142. for line in ignoreFile.readlines():
  143. line = line.replace(" ", "")
  144. id = line.replace("\n", "")
  145. ns.hide_node(NodeId(id))
  146. #if not ns.hide_node(NodeId(id)):
  147. # logger.info("Can't ignore node, namespace does currently not contain a node with id " + str(id))
  148. ignoreFile.close()
  149. # Remove nodes that are not printable or contain parsing errors, such as
  150. # unresolvable or no references or invalid NodeIDs
  151. ns.sanitize()
  152. # Parse Datatypes in order to find out what the XML keyed values actually
  153. # represent.
  154. # Ex. <rpm>123</rpm> is not encodable
  155. # only after parsing the datatypes, it is known that
  156. # rpm is encoded as a double
  157. ns.buildEncodingRules()
  158. # Allocate/Parse the data values. In order to do this, we must have run
  159. # buidEncodingRules.
  160. ns.allocateVariables()
  161. ns.addInverseReferences()
  162. logger.info("Generating Code for Backend: {}".format(args.backend))
  163. if args.backend == "open62541":
  164. # Create the C code with the open62541 backend of the compiler
  165. from backend_open62541 import generateOpen62541Code
  166. generateOpen62541Code(ns, args.outputFile, args.internal_headers, args.typesArray)
  167. elif args.backend == "graphviz":
  168. from backend_graphviz import generateGraphvizCode
  169. generateGraphvizCode(ns, filename=args.outputFile)
  170. else:
  171. logger.error("Unsupported backend: {}".format(args.backend))
  172. exit(1)
  173. logger.info("NodeSet generation code successfully printed")