open62541_MacroHelper.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. #!/usr/bin/env/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. import logging
  18. from ua_constants import *
  19. import string
  20. logger = logging.getLogger(__name__)
  21. __unique_item_id = 0
  22. defined_typealiases = []
  23. class open62541_MacroHelper():
  24. def __init__(self, supressGenerationOfAttribute=[]):
  25. self.supressGenerationOfAttribute = supressGenerationOfAttribute
  26. def getCreateExpandedNodeIDMacro(self, node):
  27. if node.id().i != None:
  28. return "UA_EXPANDEDNODEID_NUMERIC(" + str(node.id().ns) + ", " + str(node.id().i) + ")"
  29. elif node.id().s != None:
  30. return "UA_EXPANDEDNODEID_STRING(" + str(node.id().ns) + ", " + node.id().s + ")"
  31. elif node.id().b != None:
  32. logger.debug("NodeID Generation macro for bytestrings has not been implemented.")
  33. return ""
  34. elif node.id().g != None:
  35. logger.debug("NodeID Generation macro for guids has not been implemented.")
  36. return ""
  37. else:
  38. return ""
  39. def substitutePunctuationCharacters(self, input):
  40. ''' substitutePunctuationCharacters
  41. Replace punctuation characters in input. Part of this class because it is used by
  42. ua_namespace on occasion.
  43. returns: C-printable string representation of input
  44. '''
  45. # No punctuation characters <>!$
  46. for illegal_char in list(string.punctuation):
  47. if illegal_char == '_': # underscore is allowed
  48. continue
  49. input = input.replace(illegal_char, "_") # map to underscore
  50. return input
  51. def getNodeIdDefineString(self, node):
  52. code = []
  53. extrNs = node.browseName().split(":")
  54. symbolic_name = ""
  55. # strip all characters that would be illegal in C-Code
  56. if len(extrNs) > 1:
  57. nodename = extrNs[1]
  58. else:
  59. nodename = extrNs[0]
  60. symbolic_name = self.substitutePunctuationCharacters(nodename)
  61. if symbolic_name != nodename :
  62. logger.warn("Subsituted characters in browsename for nodeid " + str(node.id().i) + " while generating C-Code ")
  63. if symbolic_name in defined_typealiases:
  64. logger.warn(self, "Typealias definition of " + str(node.id().i) + " is non unique!")
  65. extendedN = 1
  66. while (symbolic_name+"_"+str(extendedN) in defined_typealiases):
  67. logger.warn("Typealias definition of " + str(node.id().i) + " is non unique!")
  68. extendedN+=1
  69. symbolic_name = symbolic_name+"_"+str(extendedN)
  70. defined_typealiases.append(symbolic_name)
  71. code.append("#define UA_NS" + str(node.id().ns) + "ID_" + symbolic_name.upper() + " " + str(node.id().i))
  72. return code
  73. def getCreateNodeIDMacro(self, node):
  74. if node.id().i != None:
  75. return "UA_NODEID_NUMERIC(" + str(node.id().ns) + ", " + str(node.id().i) + ")"
  76. elif node.id().s != None:
  77. return "UA_NODEID_STRING(" + str(node.id().ns) + ", " + node.id().s + ")"
  78. elif node.id().b != None:
  79. logger.debug("NodeID Generation macro for bytestrings has not been implemented.")
  80. return ""
  81. elif node.id().g != None:
  82. logger.debug("NodeID Generation macro for guids has not been implemented.")
  83. return ""
  84. else:
  85. return ""
  86. def getCreateStandaloneReference(self, sourcenode, reference):
  87. code = []
  88. if reference.isForward():
  89. code.append("UA_Server_addReference(server, " + self.getCreateNodeIDMacro(sourcenode) + ", " + self.getCreateNodeIDMacro(reference.referenceType()) + ", " + self.getCreateExpandedNodeIDMacro(reference.target()) + ", true);")
  90. else:
  91. code.append("UA_Server_addReference(server, " + self.getCreateNodeIDMacro(sourcenode) + ", " + self.getCreateNodeIDMacro(reference.referenceType()) + ", " + self.getCreateExpandedNodeIDMacro(reference.target()) + ", false);")
  92. return code
  93. def getCreateNodeNoBootstrap(self, node, parentNode, parentReference, unprintedNodes):
  94. code = []
  95. code.append("// Node: " + str(node) + ", " + str(node.browseName()))
  96. if node.nodeClass() == NODE_CLASS_OBJECT:
  97. nodetype = "Object"
  98. elif node.nodeClass() == NODE_CLASS_VARIABLE:
  99. nodetype = "Variable"
  100. elif node.nodeClass() == NODE_CLASS_METHOD:
  101. nodetype = "Method"
  102. elif node.nodeClass() == NODE_CLASS_OBJECTTYPE:
  103. nodetype = "ObjectType"
  104. elif node.nodeClass() == NODE_CLASS_REFERENCETYPE:
  105. nodetype = "ReferenceType"
  106. elif node.nodeClass() == NODE_CLASS_VARIABLETYPE:
  107. nodetype = "VariableType"
  108. elif node.nodeClass() == NODE_CLASS_DATATYPE:
  109. nodetype = "DataType"
  110. elif node.nodeClass() == NODE_CLASS_VIEW:
  111. nodetype = "View"
  112. else:
  113. code.append("/* undefined nodeclass */")
  114. return code;
  115. # If this is a method, construct in/outargs for addMethod
  116. #inputArguments.arrayDimensionsSize = 0;
  117. #inputArguments.arrayDimensions = NULL;
  118. #inputArguments.dataType = UA_TYPES[UA_TYPES_STRING].typeId;
  119. # Node ordering should have made sure that arguments, if they exist, have not been printed yet
  120. if node.nodeClass() == NODE_CLASS_METHOD:
  121. inArgVal = []
  122. outArgVal = []
  123. code.append("UA_Argument *inputArguments = NULL;")
  124. code.append("UA_Argument *outputArguments = NULL;")
  125. for r in node.getReferences():
  126. if r.isForward():
  127. if r.target() != None and r.target().nodeClass() == NODE_CLASS_VARIABLE and r.target().browseName() == 'InputArguments':
  128. while r.target() in unprintedNodes:
  129. unprintedNodes.remove(r.target())
  130. if r.target().value() != None:
  131. inArgVal = r.target().value().value
  132. elif r.target() != None and r.target().nodeClass() == NODE_CLASS_VARIABLE and r.target().browseName() == 'OutputArguments':
  133. while r.target() in unprintedNodes:
  134. unprintedNodes.remove(r.target())
  135. if r.target().value() != None:
  136. outArgVal = r.target().value().value
  137. if len(inArgVal)>0:
  138. code.append("")
  139. code.append("inputArguments = (UA_Argument *) malloc(sizeof(UA_Argument) * " + str(len(inArgVal)) + ");")
  140. code.append("int inputArgumentCnt;")
  141. code.append("for (inputArgumentCnt=0; inputArgumentCnt<" + str(len(inArgVal)) + "; inputArgumentCnt++) UA_Argument_init(&inputArguments[inputArgumentCnt]); ")
  142. argumentCnt = 0
  143. for inArg in inArgVal:
  144. if inArg.getValueFieldByAlias("Description") != None:
  145. code.append("inputArguments[" + str(argumentCnt) + "].description = UA_LOCALIZEDTEXT(\"" + str(inArg.getValueFieldByAlias("Description")[0]) + "\",\"" + str(inArg.getValueFieldByAlias("Description")[1]) + "\");")
  146. if inArg.getValueFieldByAlias("Name") != None:
  147. code.append("inputArguments[" + str(argumentCnt) + "].name = UA_STRING(\"" + str(inArg.getValueFieldByAlias("Name")) + "\");")
  148. if inArg.getValueFieldByAlias("ValueRank") != None:
  149. code.append("inputArguments[" + str(argumentCnt) + "].valueRank = " + str(inArg.getValueFieldByAlias("ValueRank")) + ";")
  150. if inArg.getValueFieldByAlias("DataType") != None:
  151. code.append("inputArguments[" + str(argumentCnt) + "].dataType = " + str(self.getCreateNodeIDMacro(inArg.getValueFieldByAlias("DataType"))) + ";")
  152. #if inArg.getValueFieldByAlias("ArrayDimensions") != None:
  153. # code.append("inputArguments[" + str(argumentCnt) + "].arrayDimensions = " + str(inArg.getValueFieldByAlias("ArrayDimensions")) + ";")
  154. argumentCnt += 1
  155. if len(outArgVal)>0:
  156. code.append("")
  157. code.append("outputArguments = (UA_Argument *) malloc(sizeof(UA_Argument) * " + str(len(outArgVal)) + ");")
  158. code.append("int outputArgumentCnt;")
  159. code.append("for (outputArgumentCnt=0; outputArgumentCnt<" + str(len(outArgVal)) + "; outputArgumentCnt++) UA_Argument_init(&outputArguments[outputArgumentCnt]); ")
  160. argumentCnt = 0
  161. for outArg in outArgVal:
  162. if outArg.getValueFieldByAlias("Description") != None:
  163. code.append("outputArguments[" + str(argumentCnt) + "].description = UA_LOCALIZEDTEXT(\"" + str(outArg.getValueFieldByAlias("Description")[0]) + "\",\"" + str(outArg.getValueFieldByAlias("Description")[1]) + "\");")
  164. if outArg.getValueFieldByAlias("Name") != None:
  165. code.append("outputArguments[" + str(argumentCnt) + "].name = UA_STRING(\"" + str(outArg.getValueFieldByAlias("Name")) + "\");")
  166. if outArg.getValueFieldByAlias("ValueRank") != None:
  167. code.append("outputArguments[" + str(argumentCnt) + "].valueRank = " + str(outArg.getValueFieldByAlias("ValueRank")) + ";")
  168. if outArg.getValueFieldByAlias("DataType") != None:
  169. code.append("outputArguments[" + str(argumentCnt) + "].dataType = " + str(self.getCreateNodeIDMacro(outArg.getValueFieldByAlias("DataType"))) + ";")
  170. #if outArg.getValueFieldByAlias("ArrayDimensions") != None:
  171. # code.append("outputArguments[" + str(argumentCnt) + "].arrayDimensions = " + str(outArg.getValueFieldByAlias("ArrayDimensions")) + ";")
  172. argumentCnt += 1
  173. # print the attributes struct
  174. code.append("UA_%sAttributes attr;" % nodetype)
  175. code.append("UA_%sAttributes_init(&attr);" % nodetype);
  176. code.append("attr.displayName = UA_LOCALIZEDTEXT(\"\", \"" + str(node.displayName()) + "\");")
  177. code.append("attr.description = UA_LOCALIZEDTEXT(\"\", \"" + str(node.description()) + "\");")
  178. if nodetype == "Variable":
  179. code.append("attr.accessLevel = %s;" % str(node.accessLevel()))
  180. code.append("attr.userAccessLevel = %s;" % str(node.userAccessLevel()))
  181. if nodetype in ["Variable", "VariableType"]:
  182. code = code + node.printOpen62541CCode_SubtypeEarly(bootstrapping = False)
  183. elif nodetype == "Method":
  184. if node.executable():
  185. code.append("attr.executable = true;")
  186. if node.userExecutable():
  187. code.append("attr.userExecutable = true;")
  188. code.append("UA_NodeId nodeId = " + str(self.getCreateNodeIDMacro(node)) + ";")
  189. if nodetype in ["Object", "Variable"]:
  190. code.append("UA_NodeId typeDefinition = UA_NODEID_NULL;") #due to the current API we cannot set types here since the API will generate nodes with random IDs
  191. code.append("UA_NodeId parentNodeId = " + str(self.getCreateNodeIDMacro(parentNode)) + ";")
  192. code.append("UA_NodeId parentReferenceNodeId = " + str(self.getCreateNodeIDMacro(parentReference.referenceType())) + ";")
  193. extrNs = node.browseName().split(":")
  194. if len(extrNs) > 1:
  195. code.append("UA_QualifiedName nodeName = UA_QUALIFIEDNAME(" + str(extrNs[0]) + ", \"" + extrNs[1] + "\");")
  196. else:
  197. code.append("UA_QualifiedName nodeName = UA_QUALIFIEDNAME(0, \"" + str(node.browseName()) + "\");")
  198. # In case of a MethodNode: Add in|outArg struct generation here. Mandates that namespace reordering was done using
  199. # Djikstra (check that arguments have not been printed). (@ichrispa)
  200. code.append("UA_Server_add%sNode(server, nodeId, parentNodeId, parentReferenceNodeId, nodeName" % nodetype)
  201. if nodetype in ["Object", "Variable"]:
  202. code.append(" , typeDefinition")
  203. if nodetype != "Method":
  204. code.append(" , attr, NULL, NULL);")
  205. else:
  206. code.append(" , attr, (UA_MethodCallback) NULL, NULL, " + str(len(inArgVal)) + ", inputArguments, " + str(len(outArgVal)) + ", outputArguments, NULL);")
  207. #Adding a Node with typeDefinition = UA_NODEID_NULL will create a HasTypeDefinition reference to BaseDataType - remove it since
  208. #a real Reference will be add in a later step (a single HasTypeDefinition reference is assumed here)
  209. #The current API does not let us specify IDs of Object's subelements.
  210. if nodetype is "Object":
  211. 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");
  212. if nodetype is "Variable":
  213. 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");
  214. return code
  215. def getCreateNodeBootstrap(self, node):
  216. nodetype = ""
  217. code = []
  218. code.append("// Node: " + str(node) + ", " + str(node.browseName()))
  219. if node.nodeClass() == NODE_CLASS_OBJECT:
  220. nodetype = "Object"
  221. elif node.nodeClass() == NODE_CLASS_VARIABLE:
  222. nodetype = "Variable"
  223. elif node.nodeClass() == NODE_CLASS_METHOD:
  224. nodetype = "Method"
  225. elif node.nodeClass() == NODE_CLASS_OBJECTTYPE:
  226. nodetype = "ObjectType"
  227. elif node.nodeClass() == NODE_CLASS_REFERENCETYPE:
  228. nodetype = "ReferenceType"
  229. elif node.nodeClass() == NODE_CLASS_VARIABLETYPE:
  230. nodetype = "VariableType"
  231. elif node.nodeClass() == NODE_CLASS_DATATYPE:
  232. nodetype = "DataType"
  233. elif node.nodeClass() == NODE_CLASS_VIEW:
  234. nodetype = "View"
  235. else:
  236. code.append("/* undefined nodeclass */")
  237. return;
  238. code.append("UA_" + nodetype + "Node *" + node.getCodePrintableID() + " = UA_NodeStore_new" + nodetype + "Node();")
  239. if not "browsename" in self.supressGenerationOfAttribute:
  240. extrNs = node.browseName().split(":")
  241. if len(extrNs) > 1:
  242. code.append(node.getCodePrintableID() + "->browseName = UA_QUALIFIEDNAME_ALLOC(" + str(extrNs[0]) + ", \"" + extrNs[1] + "\");")
  243. else:
  244. code.append(node.getCodePrintableID() + "->browseName = UA_QUALIFIEDNAME_ALLOC(0, \"" + node.browseName() + "\");")
  245. if not "displayname" in self.supressGenerationOfAttribute:
  246. code.append(node.getCodePrintableID() + "->displayName = UA_LOCALIZEDTEXT_ALLOC(\"en_US\", \"" + node.displayName() + "\");")
  247. if not "description" in self.supressGenerationOfAttribute:
  248. code.append(node.getCodePrintableID() + "->description = UA_LOCALIZEDTEXT_ALLOC(\"en_US\", \"" + node.description() + "\");")
  249. if not "writemask" in self.supressGenerationOfAttribute:
  250. if node.__node_writeMask__ != 0:
  251. code.append(node.getCodePrintableID() + "->writeMask = (UA_Int32) " + str(node.__node_writeMask__) + ";")
  252. if not "userwritemask" in self.supressGenerationOfAttribute:
  253. if node.__node_userWriteMask__ != 0:
  254. code.append(node.getCodePrintableID() + "->userWriteMask = (UA_Int32) " + str(node.__node_userWriteMask__) + ";")
  255. if not "nodeid" in self.supressGenerationOfAttribute:
  256. if node.id().ns != 0:
  257. code.append(node.getCodePrintableID() + "->nodeId.namespaceIndex = " + str(node.id().ns) + ";")
  258. if node.id().i != None:
  259. code.append(node.getCodePrintableID() + "->nodeId.identifier.numeric = " + str(node.id().i) + ";")
  260. elif node.id().b != None:
  261. code.append(node.getCodePrintableID() + "->nodeId.identifierType = UA_NODEIDTYPE_BYTESTRING;")
  262. logger.error("ByteString IDs for nodes has not been implemented yet.")
  263. return []
  264. elif node.id().g != None:
  265. #<jpfr> the string is sth like { .length = 111, .data = <ptr> }
  266. #<jpfr> there you _may_ alloc the <ptr> on the heap
  267. #<jpfr> for the guid, just set it to {.data1 = 111, .data2 = 2222, ....
  268. code.append(node.getCodePrintableID() + "->nodeId.identifierType = UA_NODEIDTYPE_GUID;")
  269. logger.error(self, "GUIDs for nodes has not been implemented yet.")
  270. return []
  271. elif node.id().s != None:
  272. code.append(node.getCodePrintableID() + "->nodeId.identifierType = UA_NODEIDTYPE_STRING;")
  273. code.append(node.getCodePrintableID() + "->nodeId.identifier.numeric = UA_STRING_ALLOC(\"" + str(node.id().i) + "\");")
  274. else:
  275. logger.error("Node ID is not numeric, bytestring, guid or string. I do not know how to create c code for that...")
  276. return []
  277. return code