open62541_MacroHelper.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  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;" % nodetype)
  178. code.append("UA_%sAttributes_init(&attr);" % nodetype);
  179. code.append("attr.displayName = UA_LOCALIZEDTEXT(\"\", \"" + str(node.displayName()) + "\");")
  180. code.append("attr.description = UA_LOCALIZEDTEXT(\"\", \"" + str(node.description()) + "\");")
  181. if nodetype == "Variable":
  182. code.append("attr.accessLevel = %s;" % str(node.accessLevel()))
  183. code.append("attr.userAccessLevel = %s;" % str(node.userAccessLevel()))
  184. if nodetype in ["Variable", "VariableType"]:
  185. code.append("attr.valueRank = %s;" % str(node.valueRank()))
  186. if nodetype in ["Variable", "VariableType"]:
  187. code = code + node.printOpen62541CCode_SubtypeEarly(bootstrapping = False)
  188. elif nodetype == "Method":
  189. if node.executable():
  190. code.append("attr.executable = true;")
  191. if node.userExecutable():
  192. code.append("attr.userExecutable = true;")
  193. code.append("UA_NodeId nodeId = " + str(self.getCreateNodeIDMacro(node)) + ";")
  194. if nodetype in ["Object", "Variable", "VariableType"]:
  195. typeDefinition = None
  196. for r in node.getReferences():
  197. if r.isForward() and r.referenceType().id().ns == 0 and r.referenceType().id().i == 40:
  198. typeDefinition = r.target()
  199. if typeDefinition == None:
  200. # FIXME: We might want to resort to BaseXYTTypes here?
  201. code.append("UA_NodeId typeDefinition = UA_NODEID_NUMERIC(0, UA_NS0ID_BASEDATAVARIABLETYPE);")
  202. else:
  203. code.append("UA_NodeId typeDefinition = " + str(self.getCreateNodeIDMacro(typeDefinition)) + ";")
  204. code.append("UA_NodeId parentNodeId = " + str(self.getCreateNodeIDMacro(parentNode)) + ";")
  205. code.append("UA_NodeId parentReferenceNodeId = " + str(self.getCreateNodeIDMacro(parentReference.referenceType())) + ";")
  206. extrNs = node.browseName().split(":")
  207. if len(extrNs) > 1:
  208. code.append("UA_QualifiedName nodeName = UA_QUALIFIEDNAME(" + str(extrNs[0]) + ", \"" + extrNs[1] + "\");")
  209. else:
  210. code.append("UA_QualifiedName nodeName = UA_QUALIFIEDNAME(0, \"" + str(node.browseName()) + "\");")
  211. # In case of a MethodNode: Add in|outArg struct generation here. Mandates that namespace reordering was done using
  212. # Djikstra (check that arguments have not been printed). (@ichrispa)
  213. code.append("UA_Server_add%sNode(server, nodeId, parentNodeId, parentReferenceNodeId, nodeName" % nodetype)
  214. if nodetype in ["Object", "Variable", "VariableType"]:
  215. code.append(" , typeDefinition")
  216. if nodetype != "Method":
  217. code.append(" , attr, NULL, NULL);")
  218. else:
  219. code.append(" , attr, (UA_MethodCallback) NULL, " + str(len(inArgVal)) + ", inputArguments, " + str(len(outArgVal)) + ", outputArguments, NULL, NULL);")
  220. #Adding a Node with typeDefinition = UA_NODEID_NULL will create a HasTypeDefinition reference to BaseDataType - remove it since
  221. #a real Reference will be add in a later step (a single HasTypeDefinition reference is assumed here)
  222. #The current API does not let us specify IDs of Object's subelements.
  223. if nodetype is "Object":
  224. 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");
  225. if nodetype is "Variable":
  226. 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");
  227. return code
  228. def getCreateNodeBootstrap(self, node):
  229. nodetype = ""
  230. code = []
  231. code.append("// Node: " + str(node) + ", " + str(node.browseName()))
  232. if node.nodeClass() == NODE_CLASS_OBJECT:
  233. nodetype = "Object"
  234. elif node.nodeClass() == NODE_CLASS_VARIABLE:
  235. nodetype = "Variable"
  236. elif node.nodeClass() == NODE_CLASS_METHOD:
  237. nodetype = "Method"
  238. elif node.nodeClass() == NODE_CLASS_OBJECTTYPE:
  239. nodetype = "ObjectType"
  240. elif node.nodeClass() == NODE_CLASS_REFERENCETYPE:
  241. nodetype = "ReferenceType"
  242. elif node.nodeClass() == NODE_CLASS_VARIABLETYPE:
  243. nodetype = "VariableType"
  244. elif node.nodeClass() == NODE_CLASS_DATATYPE:
  245. nodetype = "DataType"
  246. elif node.nodeClass() == NODE_CLASS_VIEW:
  247. nodetype = "View"
  248. else:
  249. code.append("/* undefined nodeclass */")
  250. return;
  251. code.append("UA_" + nodetype + "Node *" + node.getCodePrintableID() + " = UA_NodeStore_new" + nodetype + "Node();")
  252. if not "browsename" in self.supressGenerationOfAttribute:
  253. extrNs = node.browseName().split(":")
  254. if len(extrNs) > 1:
  255. code.append(node.getCodePrintableID() + "->browseName = UA_QUALIFIEDNAME_ALLOC(" + str(extrNs[0]) + ", \"" + extrNs[1] + "\");")
  256. else:
  257. code.append(node.getCodePrintableID() + "->browseName = UA_QUALIFIEDNAME_ALLOC(0, \"" + node.browseName() + "\");")
  258. if not "displayname" in self.supressGenerationOfAttribute:
  259. code.append(node.getCodePrintableID() + "->displayName = UA_LOCALIZEDTEXT_ALLOC(\"\", \"" + node.displayName() + "\");")
  260. if not "description" in self.supressGenerationOfAttribute:
  261. code.append(node.getCodePrintableID() + "->description = UA_LOCALIZEDTEXT_ALLOC(\"\", \"" + node.description() + "\");")
  262. if not "writemask" in self.supressGenerationOfAttribute:
  263. if node.__node_writeMask__ != 0:
  264. code.append(node.getCodePrintableID() + "->writeMask = (UA_Int32) " + str(node.__node_writeMask__) + ";")
  265. if not "userwritemask" in self.supressGenerationOfAttribute:
  266. if node.__node_userWriteMask__ != 0:
  267. code.append(node.getCodePrintableID() + "->userWriteMask = (UA_Int32) " + str(node.__node_userWriteMask__) + ";")
  268. if not "nodeid" in self.supressGenerationOfAttribute:
  269. if node.id().ns != 0:
  270. code.append(node.getCodePrintableID() + "->nodeId.namespaceIndex = " + str(node.id().ns) + ";")
  271. if node.id().i != None:
  272. code.append(node.getCodePrintableID() + "->nodeId.identifier.numeric = " + str(node.id().i) + ";")
  273. elif node.id().b != None:
  274. code.append(node.getCodePrintableID() + "->nodeId.identifierType = UA_NODEIDTYPE_BYTESTRING;")
  275. logger.error("ByteString IDs for nodes has not been implemented yet.")
  276. return []
  277. elif node.id().g != None:
  278. #<jpfr> the string is sth like { .length = 111, .data = <ptr> }
  279. #<jpfr> there you _may_ alloc the <ptr> on the heap
  280. #<jpfr> for the guid, just set it to {.data1 = 111, .data2 = 2222, ....
  281. code.append(node.getCodePrintableID() + "->nodeId.identifierType = UA_NODEIDTYPE_GUID;")
  282. logger.error(self, "GUIDs for nodes has not been implemented yet.")
  283. return []
  284. elif node.id().s != None:
  285. code.append(node.getCodePrintableID() + "->nodeId.identifierType = UA_NODEIDTYPE_STRING;")
  286. code.append(node.getCodePrintableID() + "->nodeId.identifier.numeric = UA_STRING_ALLOC(\"" + str(node.id().i) + "\");")
  287. else:
  288. logger.error("Node ID is not numeric, bytestring, guid or string. I do not know how to create c code for that...")
  289. return []
  290. return code