generate_open62541CCode.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3. ###
  4. ### Author: Chris Iatrou (ichrispa@core-vector.net)
  5. ### Version: rev 13
  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 sys import argv, exit
  18. from os import path
  19. from ua_namespace import *
  20. from logger import *
  21. def usage():
  22. print "Script usage:"
  23. print "generate_open62541CCode [-i <ignorefile> | -b <blacklistfile>] <namespace XML> [namespace.xml[ namespace.xml[...]]] <output file>"
  24. print ""
  25. print "generate_open62541CCode will first read all XML files passed on the command line, then "
  26. print "link and check the namespace. All nodes that fullfill the basic requirements will then be"
  27. print "printed as C-Code intended to be included in the open62541 OPC-UA Server that will"
  28. print "initialize the corresponding name space."
  29. print ""
  30. print "Manditory Arguments:"
  31. print "<namespace XML> At least one Namespace XML file must be passed."
  32. print "<output file> The basename for the <output file>.c and <output file>.h files to be generated."
  33. print " This will also be the function name used in the header and c-file."
  34. print ""
  35. print ""
  36. print "Additional Arguments:"
  37. print """ -i <ignoreFile> Loads a list of NodeIDs stored in ignoreFile (one NodeID per line)
  38. The compiler will assume that these Nodes have been created externally
  39. and not generate any code for them. They will however be linked to
  40. from other nodes."""
  41. print """ -b <blacklistFile> Loads a list of NodeIDs stored in blacklistFile (one NodeID per line)
  42. Any of the nodeIds encountered in this file will be removed from the namespace
  43. prior to compilation. Any references to these nodes will also be removed"""
  44. print """ -s <attribute> Suppresses the generation of some node attributes. Currently supported
  45. options are 'description', 'browseName', 'displayName', 'writeMask', 'userWriteMask'
  46. and 'nodeid'."""
  47. print """ namespaceXML Any number of namespace descriptions in XML format. Note that the
  48. last description of a node encountered will be used and all prior definitions
  49. are discarded."""
  50. if __name__ == '__main__':
  51. # Check if the parameters given correspond to actual files
  52. infiles = []
  53. ouffile = ""
  54. ignoreFiles = []
  55. blacklistFiles = []
  56. supressGenerationOfAttribute=[]
  57. GLOBAL_LOG_LEVEL = LOG_LEVEL_DEBUG
  58. arg_isIgnore = False
  59. arg_isBlacklist = False
  60. arg_isSupress = False
  61. if len(argv) < 2:
  62. usage()
  63. exit(1)
  64. for filename in argv[1:-1]:
  65. if arg_isIgnore:
  66. arg_isIgnore = False
  67. if path.exists(filename):
  68. ignoreFiles.append(filename)
  69. else:
  70. log(None, "File " + str(filename) + " does not exist.", LOG_LEVEL_ERROR)
  71. usage()
  72. exit(1)
  73. elif arg_isBlacklist:
  74. arg_isBlacklist = False
  75. if path.exists(filename):
  76. blacklistFiles.append(filename)
  77. else:
  78. log(None, "File " + str(filename) + " does not exist.", LOG_LEVEL_ERROR)
  79. usage()
  80. exit(1)
  81. elif arg_isSupress:
  82. arg_isSupress = False
  83. supressGenerationOfAttribute.append(filename.lower())
  84. else:
  85. if path.exists(filename):
  86. infiles.append(filename)
  87. elif filename.lower() == "-i" or filename.lower() == "--ignore" :
  88. arg_isIgnore = True
  89. elif filename.lower() == "-b" or filename.lower() == "--blacklist" :
  90. arg_isBlacklist = True
  91. elif filename.lower() == "-s" or filename.lower() == "--suppress" :
  92. arg_isSupress = True
  93. else:
  94. log(None, "File " + str(filename) + " does not exist.", LOG_LEVEL_ERROR)
  95. usage()
  96. exit(1)
  97. # Creating the header is tendious. We can skip the entire process if
  98. # the header exists.
  99. #if path.exists(argv[-1]+".c") or path.exists(argv[-1]+".h"):
  100. # log(None, "File " + str(argv[-1]) + " does already exists.", LOG_LEVEL_INFO)
  101. # log(None, "Header generation will be skipped. Delete the header and rerun this script if necessary.", LOG_LEVEL_INFO)
  102. # exit(0)
  103. # Open the output file
  104. outfileh = open(argv[-1]+".h", r"w+")
  105. outfilec = open(argv[-1]+".c", r"w+")
  106. # Create a new namespace
  107. # Note that the name is actually completely symbolic, it has no other
  108. # function but to distinguish this specific class.
  109. # A namespace class acts as a container for nodes. The nodes may belong
  110. # to any number of different OPC-UA namespaces.
  111. ns = opcua_namespace("open62541")
  112. # Parse the XML files
  113. for xmlfile in infiles:
  114. log(None, "Parsing " + str(xmlfile), LOG_LEVEL_INFO)
  115. ns.parseXML(xmlfile)
  116. # Remove blacklisted nodes from the namespace
  117. # Doing this now ensures that unlinkable pointers will be cleanly removed
  118. # during sanitation.
  119. for blacklist in blacklistFiles:
  120. bl = open(blacklist, "r")
  121. for line in bl.readlines():
  122. line = line.replace(" ","")
  123. id = line.replace("\n","")
  124. if ns.getNodeByIDString(id) == None:
  125. log(None, "Can't blacklist node, namespace does currently not contain a node with id " + str(id), LOG_LEVEL_WARN)
  126. else:
  127. ns.removeNodeById(line)
  128. bl.close()
  129. # Link the references in the namespace
  130. log(None, "Linking namespace nodes and references", LOG_LEVEL_INFO)
  131. ns.linkOpenPointers()
  132. # Remove nodes that are not printable or contain parsing errors, such as
  133. # unresolvable or no references or invalid NodeIDs
  134. ns.sanitize()
  135. # Parse Datatypes in order to find out what the XML keyed values actually
  136. # represent.
  137. # Ex. <rpm>123</rpm> is not encodable
  138. # only after parsing the datatypes, it is known that
  139. # rpm is encoded as a double
  140. log(None, "Building datatype encoding rules", LOG_LEVEL_INFO)
  141. ns.buildEncodingRules()
  142. # Allocate/Parse the data values. In order to do this, we must have run
  143. # buidEncodingRules.
  144. log(None, "Allocating variables", LOG_LEVEL_INFO)
  145. ns.allocateVariables()
  146. # Users may have manually defined some nodes in their code already (such as serverStatus).
  147. # To prevent those nodes from being reprinted, we will simply mark them as already
  148. # converted to C-Code. That way, they will still be reffered to by other nodes, but
  149. # they will not be created themselves.
  150. ignoreNodes = []
  151. for ignore in ignoreFiles:
  152. ig = open(ignore, "r")
  153. for line in ig.readlines():
  154. line = line.replace(" ","")
  155. id = line.replace("\n","")
  156. if ns.getNodeByIDString(id) == None:
  157. log(None, "Can't ignore node, Namespace does currently not contain a node with id " + str(id), LOG_LEVEL_WARN)
  158. else:
  159. ignoreNodes.append(ns.getNodeByIDString(id))
  160. ig.close()
  161. # Create the C Code
  162. log(None, "Generating Header", LOG_LEVEL_INFO)
  163. # Returns a tuple of (["Header","lines"],["Code","lines","generated"])
  164. generatedCode=ns.printOpen62541Header(ignoreNodes, supressGenerationOfAttribute, outfilename=path.basename(argv[-1]))
  165. for line in generatedCode[0]:
  166. outfileh.write(line+"\n")
  167. for line in generatedCode[1]:
  168. outfilec.write(line+"\n")
  169. outfilec.close()
  170. outfileh.close()
  171. exit(0)