generate_open62541CCode.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. /* This Source Code Form is subject to the terms of the Mozilla Public
  2. * License, v. 2.0. If a copy of the MPL was not distributed with this
  3. * file, You can obtain one at http://mozilla.org/MPL/2.0/.
  4. #!/usr/bin/python
  5. # -*- coding: utf-8 -*-
  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. from __future__ import print_function
  21. from ua_namespace import *
  22. import logging
  23. import argparse
  24. from open62541_XMLPreprocessor import open62541_XMLPreprocessor
  25. logger = logging.getLogger(__name__)
  26. parser = argparse.ArgumentParser(
  27. description="""Parse OPC UA NamespaceXML file(s) and create C code for generating nodes in open62541
  28. 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.""",
  29. formatter_class=argparse.RawDescriptionHelpFormatter)
  30. parser.add_argument('infiles',
  31. metavar="<namespaceXML>",
  32. nargs='+',
  33. type=argparse.FileType('r'),
  34. help='Namespace XML file(s). Note that the last definition of a node encountered will be used and all prior definitions are discarded.')
  35. parser.add_argument('outputFile',
  36. metavar='<outputFile>',
  37. #type=argparse.FileType('w', 0),
  38. 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.')
  39. parser.add_argument('-i','--ignore',
  40. metavar="<ignoreFile>",
  41. type=argparse.FileType('r'),
  42. action='append',
  43. dest="ignoreFiles",
  44. default=[],
  45. 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.')
  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 namespace prior to compilation. Any references to these nodes will also be removed')
  53. parser.add_argument('-s','--suppress',
  54. metavar="<attribute>",
  55. action='append',
  56. dest="suppressedAttributes",
  57. choices=['description', 'browseName', 'displayName', 'writeMask', 'userWriteMask','nodeid'],
  58. default=[],
  59. help="Suppresses the generation of some node attributes. Currently supported options are 'description', 'browseName', 'displayName', 'writeMask', 'userWriteMask' and 'nodeid'.")
  60. parser.add_argument('-v','--verbose', action='count', help='Make the script more verbose. Can be applied up to 4 times')
  61. args = parser.parse_args()
  62. level = logging.CRITICAL
  63. verbosity = 0
  64. if args.verbose:
  65. verbosity = int(args.verbose)
  66. if (verbosity==1):
  67. level = logging.ERROR
  68. elif (verbosity==2):
  69. level = logging.WARNING
  70. elif (verbosity==3):
  71. level = logging.INFO
  72. elif (verbosity>=4):
  73. level = logging.DEBUG
  74. logging.basicConfig(level=level)
  75. logger.setLevel(logging.INFO)
  76. # Creating the header is tendious. We can skip the entire process if
  77. # the header exists.
  78. #if path.exists(argv[-1]+".c") or path.exists(argv[-1]+".h"):
  79. # log(None, "File " + str(argv[-1]) + " does already exists.", LOG_LEVEL_INFO)
  80. # log(None, "Header generation will be skipped. Delete the header and rerun this script if necessary.", LOG_LEVEL_INFO)
  81. # exit(0)
  82. # Open the output file
  83. outfileh = open(args.outputFile+".h", r"w+")
  84. outfilec = open(args.outputFile+".c", r"w+")
  85. # Create a new namespace. Note that the namespace name is not significant.
  86. ns = opcua_namespace("open62541")
  87. # Clean up the XML files by removing duplicate namespaces and unwanted prefixes
  88. preProc = open62541_XMLPreprocessor()
  89. for xmlfile in args.infiles:
  90. logger.info("Preprocessing " + str(xmlfile.name))
  91. preProc.addDocument(xmlfile.name)
  92. preProc.preprocessAll()
  93. # Parse the XML files
  94. for xmlfile in preProc.getPreProcessedFiles():
  95. logger.info("Parsing " + str(xmlfile))
  96. ns.parseXML(xmlfile)
  97. # We need to notify the open62541 server of the namespaces used to be able to use i.e. ns=3
  98. namespaceArrayNames = preProc.getUsedNamespaceArrayNames()
  99. for key in namespaceArrayNames:
  100. ns.addNamespace(key, namespaceArrayNames[key])
  101. # Remove any temp files - they are not needed after the AST is created
  102. preProc.removePreprocessedFiles()
  103. # Remove blacklisted nodes from the namespace
  104. # Doing this now ensures that unlinkable pointers will be cleanly removed
  105. # during sanitation.
  106. for blacklist in args.blacklistFiles:
  107. for line in blacklist.readlines():
  108. line = line.replace(" ","")
  109. id = line.replace("\n","")
  110. if ns.getNodeByIDString(id) == None:
  111. logger.info("Can't blacklist node, namespace does currently not contain a node with id " + str(id))
  112. else:
  113. ns.removeNodeById(line)
  114. blacklist.close()
  115. # Link the references in the namespace
  116. logger.info("Linking namespace nodes and references")
  117. ns.linkOpenPointers()
  118. # Remove nodes that are not printable or contain parsing errors, such as
  119. # unresolvable or no references or invalid NodeIDs
  120. ns.sanitize()
  121. # Parse Datatypes in order to find out what the XML keyed values actually
  122. # represent.
  123. # Ex. <rpm>123</rpm> is not encodable
  124. # only after parsing the datatypes, it is known that
  125. # rpm is encoded as a double
  126. logger.info("Building datatype encoding rules")
  127. ns.buildEncodingRules()
  128. # Allocate/Parse the data values. In order to do this, we must have run
  129. # buidEncodingRules.
  130. logger.info("Allocating variables")
  131. ns.allocateVariables()
  132. # Users may have manually defined some nodes in their code already (such as serverStatus).
  133. # To prevent those nodes from being reprinted, we will simply mark them as already
  134. # converted to C-Code. That way, they will still be referred to by other nodes, but
  135. # they will not be created themselves.
  136. ignoreNodes = []
  137. for ignore in args.ignoreFiles:
  138. for line in ignore.readlines():
  139. line = line.replace(" ","")
  140. id = line.replace("\n","")
  141. if ns.getNodeByIDString(id) == None:
  142. logger.warn("Can't ignore node, Namespace does currently not contain a node with id " + str(id))
  143. else:
  144. ignoreNodes.append(ns.getNodeByIDString(id))
  145. ignore.close()
  146. # Create the C Code
  147. logger.info("Generating Header")
  148. # Returns a tuple of (["Header","lines"],["Code","lines","generated"])
  149. from os.path import basename
  150. generatedCode = ns.printOpen62541Header(ignoreNodes, args.suppressedAttributes, outfilename=basename(args.outputFile))
  151. for line in generatedCode[0]:
  152. outfileh.write(line+"\n")
  153. for line in generatedCode[1]:
  154. outfilec.write(line+"\n")
  155. outfilec.close()
  156. outfileh.close()
  157. logger.info("Namespace generation code successfully printed")