nodeset_compiler.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  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. ### Author: Chris Iatrou (ichrispa@core-vector.net)
  8. ### Version: rev 14
  9. ###
  10. ### This program was created for educational purposes and has been
  11. ### contributed to the open62541 project by the author. All licensing
  12. ### terms for this source is inherited by the terms and conditions
  13. ### specified for by the open62541 project (see the projects readme
  14. ### file for more information on the MPLv2 terms and restrictions).
  15. ###
  16. ### This program is not meant to be used in a production environment. The
  17. ### author is not liable for any complications arising due to the use of
  18. ### this program.
  19. ###
  20. import logging
  21. import argparse
  22. from nodeset import *
  23. from backend_open62541 import generateOpen62541Code
  24. parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter)
  25. parser.add_argument('-e', '--existing',
  26. metavar="<existingNodeSetXML>",
  27. type=argparse.FileType('r'),
  28. dest="existing",
  29. action='append',
  30. default=[],
  31. help='NodeSet XML files with nodes that are already present on the server.')
  32. parser.add_argument('-x', '--xml',
  33. metavar="<nodeSetXML>",
  34. type=argparse.FileType('r'),
  35. action='append',
  36. dest="infiles",
  37. default=[],
  38. help='NodeSet XML files with nodes that shall be generated.')
  39. parser.add_argument('outputFile',
  40. metavar='<outputFile>',
  41. 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.')
  42. parser.add_argument('--generate-ns0',
  43. action='store_true',
  44. dest="generate_ns0",
  45. help='Omit some consistency checks for bootstrapping namespace 0, create references to parents and type definitions manually')
  46. parser.add_argument('-b', '--blacklist',
  47. metavar="<blacklistFile>",
  48. type=argparse.FileType('r'),
  49. action='append',
  50. dest="blacklistFiles",
  51. default=[],
  52. 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')
  53. parser.add_argument('-i', '--ignore',
  54. metavar="<ignoreFile>",
  55. type=argparse.FileType('r'),
  56. action='append',
  57. dest="ignoreFiles",
  58. default=[],
  59. 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')
  60. parser.add_argument('-s', '--suppress',
  61. metavar="<attribute>",
  62. action='append',
  63. dest="suppressedAttributes",
  64. choices=['description', 'browseName', 'displayName', 'writeMask', 'userWriteMask', 'nodeid'],
  65. default=[],
  66. help="Suppresses the generation of some node attributes. Currently supported options are 'description', 'browseName', 'displayName', 'writeMask', 'userWriteMask' and 'nodeid'.")
  67. parser.add_argument('-t', '--types-array',
  68. metavar="<typesArray>",
  69. action='append',
  70. type=str,
  71. dest="typesArray",
  72. default=[],
  73. 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')
  74. parser.add_argument('-v', '--verbose', action='count',
  75. help='Make the script more verbose. Can be applied up to 4 times')
  76. args = parser.parse_args()
  77. # Set up logging
  78. logger = logging.getLogger(__name__)
  79. logger.setLevel(logging.INFO)
  80. verbosity = 0
  81. if args.verbose:
  82. verbosity = int(args.verbose)
  83. if (verbosity == 1):
  84. logging.basicConfig(level=logging.ERROR)
  85. elif (verbosity == 2):
  86. logging.basicConfig(level=logging.WARNING)
  87. elif (verbosity == 3):
  88. logging.basicConfig(level=logging.INFO)
  89. elif (verbosity >= 4):
  90. logging.basicConfig(level=logging.DEBUG)
  91. else:
  92. logging.basicConfig(level=logging.CRITICAL)
  93. # Create a new nodeset. The nodeset name is not significant.
  94. # Parse the XML files
  95. ns = NodeSet()
  96. nsCount = 0
  97. def getTypesArray(nsIdx):
  98. if nsIdx < len(args.typesArray):
  99. return args.typesArray[nsIdx]
  100. else:
  101. return "UA_TYPES"
  102. for xmlfile in args.existing:
  103. logger.info("Preprocessing (existing) " + str(xmlfile.name))
  104. ns.addNodeSet(xmlfile, True, typesArray=getTypesArray(nsCount))
  105. nsCount +=1
  106. for xmlfile in args.infiles:
  107. logger.info("Preprocessing " + str(xmlfile.name))
  108. ns.addNodeSet(xmlfile, typesArray=getTypesArray(nsCount))
  109. nsCount +=1
  110. # # We need to notify the open62541 server of the namespaces used to be able to use i.e. ns=3
  111. # namespaceArrayNames = preProc.getUsedNamespaceArrayNames()
  112. # for key in namespaceArrayNames:
  113. # ns.addNamespace(key, namespaceArrayNames[key])
  114. # Remove blacklisted nodes from the nodeset
  115. # Doing this now ensures that unlinkable pointers will be cleanly removed
  116. # during sanitation.
  117. for blacklist in args.blacklistFiles:
  118. for line in blacklist.readlines():
  119. line = line.replace(" ", "")
  120. id = line.replace("\n", "")
  121. if ns.getNodeByIDString(id) == None:
  122. logger.info("Can't blacklist node, namespace does currently not contain a node with id " + str(id))
  123. else:
  124. ns.removeNodeById(line)
  125. blacklist.close()
  126. # Set the nodes from the ignore list to hidden. This removes them from dependency calculation
  127. # and from printing their generated code.
  128. # These nodes should be already pre-created on the server to avoid any errors during
  129. # creation.
  130. for ignoreFile in args.ignoreFiles:
  131. for line in ignoreFile.readlines():
  132. line = line.replace(" ", "")
  133. id = line.replace("\n", "")
  134. ns.hide_node(NodeId(id))
  135. #if not ns.hide_node(NodeId(id)):
  136. # logger.info("Can't ignore node, namespace does currently not contain a node with id " + str(id))
  137. ignoreFile.close()
  138. # Remove nodes that are not printable or contain parsing errors, such as
  139. # unresolvable or no references or invalid NodeIDs
  140. ns.sanitize()
  141. # Parse Datatypes in order to find out what the XML keyed values actually
  142. # represent.
  143. # Ex. <rpm>123</rpm> is not encodable
  144. # only after parsing the datatypes, it is known that
  145. # rpm is encoded as a double
  146. ns.buildEncodingRules()
  147. # Allocate/Parse the data values. In order to do this, we must have run
  148. # buidEncodingRules.
  149. ns.allocateVariables()
  150. #printDependencyGraph(ns)
  151. # Create the C code with the open62541 backend of the compiler
  152. logger.info("Generating Code")
  153. generateOpen62541Code(ns, args.outputFile, args.suppressedAttributes, args.generate_ns0, args.typesArray)
  154. logger.info("NodeSet generation code successfully printed")