open62541_MacroHelper.py 17 KB

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