open62541_MacroHelper.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  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 13
  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. from ua_constants import *
  22. import string
  23. logger = logging.getLogger(__name__)
  24. __unique_item_id = 0
  25. defined_typealiases = []
  26. class open62541_MacroHelper():
  27. def __init__(self, supressGenerationOfAttribute=[]):
  28. self.supressGenerationOfAttribute = supressGenerationOfAttribute
  29. def getCreateExpandedNodeIDMacro(self, node):
  30. if node.id().i != None:
  31. return "UA_EXPANDEDNODEID_NUMERIC(" + str(node.id().ns) + ", " + str(node.id().i) + ")"
  32. elif node.id().s != None:
  33. return "UA_EXPANDEDNODEID_STRING(" + str(node.id().ns) + ", " + node.id().s + ")"
  34. elif node.id().b != None:
  35. logger.debug("NodeID Generation macro for bytestrings has not been implemented.")
  36. return ""
  37. elif node.id().g != None:
  38. logger.debug("NodeID Generation macro for guids has not been implemented.")
  39. return ""
  40. else:
  41. return ""
  42. def substitutePunctuationCharacters(self, input):
  43. ''' substitutePunctuationCharacters
  44. Replace punctuation characters in input. Part of this class because it is used by
  45. ua_namespace on occasion.
  46. returns: C-printable string representation of input
  47. '''
  48. # No punctuation characters <>!$
  49. for illegal_char in list(string.punctuation):
  50. if illegal_char == '_': # underscore is allowed
  51. continue
  52. input = input.replace(illegal_char, "_") # map to underscore
  53. return input
  54. def getNodeIdDefineString(self, node):
  55. code = []
  56. extrNs = node.browseName().split(":")
  57. symbolic_name = ""
  58. # strip all characters that would be illegal in C-Code
  59. if len(extrNs) > 1:
  60. nodename = extrNs[1]
  61. else:
  62. nodename = extrNs[0]
  63. symbolic_name = self.substitutePunctuationCharacters(nodename)
  64. if symbolic_name != nodename :
  65. logger.warn("Subsituted characters in browsename for nodeid " + str(node.id().i) + " while generating C-Code ")
  66. if symbolic_name in defined_typealiases:
  67. logger.warn(self, "Typealias definition of " + str(node.id().i) + " is non unique!")
  68. extendedN = 1
  69. while (symbolic_name+"_"+str(extendedN) in defined_typealiases):
  70. logger.warn("Typealias definition of " + str(node.id().i) + " is non unique!")
  71. extendedN+=1
  72. symbolic_name = symbolic_name+"_"+str(extendedN)
  73. defined_typealiases.append(symbolic_name)
  74. code.append("#define UA_NS" + str(node.id().ns) + "ID_" + symbolic_name.upper() + " " + str(node.id().i))
  75. return code
  76. def getCreateNodeIDMacro(self, node):
  77. if node.id().i != None:
  78. return "UA_NODEID_NUMERIC(" + str(node.id().ns) + ", " + str(node.id().i) + ")"
  79. elif node.id().s != None:
  80. return "UA_NODEID_STRING(" + str(node.id().ns) + ", " + node.id().s + ")"
  81. elif node.id().b != None:
  82. logger.debug("NodeID Generation macro for bytestrings has not been implemented.")
  83. return ""
  84. elif node.id().g != None:
  85. logger.debug("NodeID Generation macro for guids has not been implemented.")
  86. return ""
  87. else:
  88. return ""
  89. def getCreateStandaloneReference(self, sourcenode, reference):
  90. code = []
  91. if reference.isForward():
  92. code.append("UA_Server_addReference(server, " + self.getCreateNodeIDMacro(sourcenode) + ", " + self.getCreateNodeIDMacro(reference.referenceType()) + ", " + self.getCreateExpandedNodeIDMacro(reference.target()) + ", true);")
  93. else:
  94. code.append("UA_Server_addReference(server, " + self.getCreateNodeIDMacro(sourcenode) + ", " + self.getCreateNodeIDMacro(reference.referenceType()) + ", " + self.getCreateExpandedNodeIDMacro(reference.target()) + ", false);")
  95. return code
  96. def getCreateNodeNoBootstrap(self, node, parentNode, parentReference, unprintedNodes):
  97. code = []
  98. code.append("// Node: " + str(node) + ", " + str(node.browseName()))
  99. if node.nodeClass() == NODE_CLASS_OBJECT:
  100. nodetype = "Object"
  101. elif node.nodeClass() == NODE_CLASS_VARIABLE:
  102. nodetype = "Variable"
  103. elif node.nodeClass() == NODE_CLASS_METHOD:
  104. nodetype = "Method"
  105. elif node.nodeClass() == NODE_CLASS_OBJECTTYPE:
  106. nodetype = "ObjectType"
  107. elif node.nodeClass() == NODE_CLASS_REFERENCETYPE:
  108. nodetype = "ReferenceType"
  109. elif node.nodeClass() == NODE_CLASS_VARIABLETYPE:
  110. nodetype = "VariableType"
  111. elif node.nodeClass() == NODE_CLASS_DATATYPE:
  112. nodetype = "DataType"
  113. elif node.nodeClass() == NODE_CLASS_VIEW:
  114. nodetype = "View"
  115. else:
  116. code.append("/* undefined nodeclass */")
  117. return code;
  118. # If this is a method, construct in/outargs for addMethod
  119. #inputArguments.arrayDimensionsSize = 0;
  120. #inputArguments.arrayDimensions = NULL;
  121. #inputArguments.dataType = UA_TYPES[UA_TYPES_STRING].typeId;
  122. # Node ordering should have made sure that arguments, if they exist, have not been printed yet
  123. if node.nodeClass() == NODE_CLASS_METHOD:
  124. inArgVal = []
  125. outArgVal = []
  126. code.append("UA_Argument *inputArguments = NULL;")
  127. code.append("UA_Argument *outputArguments = NULL;")
  128. for r in node.getReferences():
  129. if r.isForward():
  130. if r.target() != None and r.target().nodeClass() == NODE_CLASS_VARIABLE and r.target().browseName() == 'InputArguments':
  131. while r.target() in unprintedNodes:
  132. unprintedNodes.remove(r.target())
  133. if r.target().value() != None:
  134. inArgVal = r.target().value().value
  135. elif r.target() != None and r.target().nodeClass() == NODE_CLASS_VARIABLE and r.target().browseName() == 'OutputArguments':
  136. while r.target() in unprintedNodes:
  137. unprintedNodes.remove(r.target())
  138. if r.target().value() != None:
  139. outArgVal = r.target().value().value
  140. if len(inArgVal)>0:
  141. code.append("")
  142. code.append("inputArguments = (UA_Argument *) UA_malloc(sizeof(UA_Argument) * " + str(len(inArgVal)) + ");")
  143. code.append("int inputArgumentCnt;")
  144. code.append("for (inputArgumentCnt=0; inputArgumentCnt<" + str(len(inArgVal)) + "; ++inputArgumentCnt) UA_Argument_init(&inputArguments[inputArgumentCnt]); ")
  145. argumentCnt = 0
  146. for inArg in inArgVal:
  147. if inArg.getValueFieldByAlias("Description") != None:
  148. code.append("inputArguments[" + str(argumentCnt) + "].description = UA_LOCALIZEDTEXT(\"" + str(inArg.getValueFieldByAlias("Description")[0]) + "\",\"" + str(inArg.getValueFieldByAlias("Description")[1]) + "\");")
  149. if inArg.getValueFieldByAlias("Name") != None:
  150. code.append("inputArguments[" + str(argumentCnt) + "].name = UA_STRING(\"" + str(inArg.getValueFieldByAlias("Name")) + "\");")
  151. if inArg.getValueFieldByAlias("ValueRank") != None:
  152. code.append("inputArguments[" + str(argumentCnt) + "].valueRank = " + str(inArg.getValueFieldByAlias("ValueRank")) + ";")
  153. if inArg.getValueFieldByAlias("DataType") != None:
  154. code.append("inputArguments[" + str(argumentCnt) + "].dataType = " + str(self.getCreateNodeIDMacro(inArg.getValueFieldByAlias("DataType"))) + ";")
  155. #if inArg.getValueFieldByAlias("ArrayDimensions") != None:
  156. # code.append("inputArguments[" + str(argumentCnt) + "].arrayDimensions = " + str(inArg.getValueFieldByAlias("ArrayDimensions")) + ";")
  157. argumentCnt += 1
  158. if len(outArgVal)>0:
  159. code.append("")
  160. code.append("outputArguments = (UA_Argument *) UA_malloc(sizeof(UA_Argument) * " + str(len(outArgVal)) + ");")
  161. code.append("int outputArgumentCnt;")
  162. code.append("for (outputArgumentCnt=0; outputArgumentCnt<" + str(len(outArgVal)) + "; ++outputArgumentCnt) UA_Argument_init(&outputArguments[outputArgumentCnt]); ")
  163. argumentCnt = 0
  164. for outArg in outArgVal:
  165. if outArg.getValueFieldByAlias("Description") != None:
  166. code.append("outputArguments[" + str(argumentCnt) + "].description = UA_LOCALIZEDTEXT(\"" + str(outArg.getValueFieldByAlias("Description")[0]) + "\",\"" + str(outArg.getValueFieldByAlias("Description")[1]) + "\");")
  167. if outArg.getValueFieldByAlias("Name") != None:
  168. code.append("outputArguments[" + str(argumentCnt) + "].name = UA_STRING(\"" + str(outArg.getValueFieldByAlias("Name")) + "\");")
  169. if outArg.getValueFieldByAlias("ValueRank") != None:
  170. code.append("outputArguments[" + str(argumentCnt) + "].valueRank = " + str(outArg.getValueFieldByAlias("ValueRank")) + ";")
  171. if outArg.getValueFieldByAlias("DataType") != None:
  172. code.append("outputArguments[" + str(argumentCnt) + "].dataType = " + str(self.getCreateNodeIDMacro(outArg.getValueFieldByAlias("DataType"))) + ";")
  173. #if outArg.getValueFieldByAlias("ArrayDimensions") != None:
  174. # code.append("outputArguments[" + str(argumentCnt) + "].arrayDimensions = " + str(outArg.getValueFieldByAlias("ArrayDimensions")) + ";")
  175. argumentCnt += 1
  176. # print the attributes struct
  177. code.append("UA_%sAttributes attr = UA_%sAttributes_default;" % (nodetype, nodetype))
  178. code.append("attr.displayName = UA_LOCALIZEDTEXT(\"\", \"" + str(node.displayName()) + "\");")
  179. code.append("attr.description = UA_LOCALIZEDTEXT(\"\", \"" + str(node.description()) + "\");")
  180. if nodetype == "Variable":
  181. code.append("attr.accessLevel = %s;" % str(node.accessLevel()))
  182. code.append("attr.userAccessLevel = %s;" % str(node.userAccessLevel()))
  183. if nodetype in ["Variable", "VariableType"]:
  184. code.append("attr.valueRank = %s;" % str(node.valueRank()))
  185. if nodetype in ["Variable", "VariableType"]:
  186. code = code + node.printOpen62541CCode_SubtypeEarly(bootstrapping = False)
  187. elif nodetype == "Method":
  188. if node.executable():
  189. code.append("attr.executable = true;")
  190. if node.userExecutable():
  191. code.append("attr.userExecutable = true;")
  192. code.append("UA_NodeId nodeId = " + str(self.getCreateNodeIDMacro(node)) + ";")
  193. if nodetype in ["Object", "Variable", "VariableType"]:
  194. typeDefinition = None
  195. for r in node.getReferences():
  196. if r.isForward() and r.referenceType().id().ns == 0 and r.referenceType().id().i == 40:
  197. typeDefinition = r.target()
  198. if typeDefinition == None:
  199. # FIXME: We might want to resort to BaseXYTTypes here?
  200. code.append("UA_NodeId typeDefinition = UA_NODEID_NUMERIC(0, UA_NS0ID_BASEDATAVARIABLETYPE);")
  201. else:
  202. code.append("UA_NodeId typeDefinition = " + str(self.getCreateNodeIDMacro(typeDefinition)) + ";")
  203. code.append("UA_NodeId parentNodeId = " + str(self.getCreateNodeIDMacro(parentNode)) + ";")
  204. code.append("UA_NodeId parentReferenceNodeId = " + str(self.getCreateNodeIDMacro(parentReference.referenceType())) + ";")
  205. extrNs = node.browseName().split(":")
  206. if len(extrNs) > 1:
  207. code.append("UA_QualifiedName nodeName = UA_QUALIFIEDNAME(" + str(extrNs[0]) + ", \"" + extrNs[1] + "\");")
  208. else:
  209. code.append("UA_QualifiedName nodeName = UA_QUALIFIEDNAME(0, \"" + str(node.browseName()) + "\");")
  210. # In case of a MethodNode: Add in|outArg struct generation here. Mandates that namespace reordering was done using
  211. # Djikstra (check that arguments have not been printed). (@ichrispa)
  212. code.append("UA_Server_add%sNode(server, nodeId, parentNodeId, parentReferenceNodeId, nodeName" % nodetype)
  213. if nodetype in ["Object", "Variable", "VariableType"]:
  214. code.append(" , typeDefinition")
  215. if nodetype != "Method":
  216. code.append(" , attr, NULL, NULL);")
  217. else:
  218. code.append(" , attr, (UA_MethodCallback) NULL, " + str(len(inArgVal)) + ", inputArguments, " + str(len(outArgVal)) + ", outputArguments, NULL, NULL);")
  219. #Adding a Node with typeDefinition = UA_NODEID_NULL will create a HasTypeDefinition reference to BaseDataType - remove it since
  220. #a real Reference will be add in a later step (a single HasTypeDefinition reference is assumed here)
  221. #The current API does not let us specify IDs of Object's subelements.
  222. if nodetype is "Object":
  223. code.append("UA_Server_deleteReference(server, nodeId, UA_NODEID_NUMERIC(0, 40), true, UA_EXPANDEDNODEID_NUMERIC(0, 58), true); //remove HasTypeDefinition refs generated by addObjectNode");
  224. if nodetype is "Variable":
  225. code.append("UA_Server_deleteReference(server, nodeId, UA_NODEID_NUMERIC(0, 40), true, UA_EXPANDEDNODEID_NUMERIC(0, 62), true); //remove HasTypeDefinition refs generated by addVariableNode");
  226. return code