open62541_MacroHelper.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  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. from logger import *
  18. from ua_constants import *
  19. import string
  20. __unique_item_id = 0
  21. defined_typealiases = []
  22. class open62541_MacroHelper():
  23. def __init__(self, supressGenerationOfAttribute=[]):
  24. self.supressGenerationOfAttribute = supressGenerationOfAttribute
  25. def getCreateExpandedNodeIDMacro(self, node):
  26. if node.id().i != None:
  27. return "UA_EXPANDEDNODEID_NUMERIC(" + str(node.id().ns) + ", " + str(node.id().i) + ")"
  28. elif node.id().s != None:
  29. return "UA_EXPANDEDNODEID_STRING(" + str(node.id().ns) + ", " + node.id().s + ")"
  30. elif node.id().b != None:
  31. log(self, "NodeID Generation macro for bytestrings has not been implemented.")
  32. return ""
  33. elif node.id().g != None:
  34. log(self, "NodeID Generation macro for guids has not been implemented.")
  35. return ""
  36. else:
  37. return ""
  38. def substitutePunctuationCharacters(self, input):
  39. ''' substitutePunctuationCharacters
  40. Replace punctuation characters in input. Part of this class because it is used by
  41. ua_namespace on occasion.
  42. returns: C-printable string representation of input
  43. '''
  44. # No punctuation characters <>!$
  45. illegal_chars = list(string.punctuation)
  46. # underscore is allowed
  47. illegal_chars.remove('_')
  48. illegal = "".join(illegal_chars)
  49. substitution = ""
  50. # Map all punctuation characters to underscore
  51. for illegal_char in illegal_chars:
  52. substitution = substitution + '_'
  53. return input.translate(string.maketrans(illegal, substitution), illegal)
  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. log(self, "Subsituted characters in browsename for nodeid " + str(node.id().i) + " while generating C-Code ", LOG_LEVEL_WARN)
  66. if symbolic_name in defined_typealiases:
  67. log(self, "Typealias definition of " + str(node.id().i) + " is non unique!", LOG_LEVEL_WARN)
  68. extendedN = 1
  69. while (symbolic_name+"_"+str(extendedN) in defined_typealiases):
  70. log(self, "Typealias definition of " + str(node.id().i) + " is non unique!", LOG_LEVEL_WARN)
  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. log(self, "NodeID Generation macro for bytestrings has not been implemented.")
  83. return ""
  84. elif node.id().g != None:
  85. log(self, "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.target() != None and r.target().nodeClass() == NODE_CLASS_VARIABLE and r.target().browseName() == 'InputArguments':
  130. while r.target() in unprintedNodes:
  131. unprintedNodes.remove(r.target())
  132. if r.target().value() != None:
  133. inArgVal = r.target().value().value
  134. elif r.target() != None and r.target().nodeClass() == NODE_CLASS_VARIABLE and r.target().browseName() == 'OutputArguments':
  135. while r.target() in unprintedNodes:
  136. unprintedNodes.remove(r.target())
  137. if r.target().value() != None:
  138. outArgVal = r.target().value().value
  139. if len(inArgVal)>0:
  140. code.append("")
  141. code.append("inputArguments = (UA_Argument *) malloc(sizeof(UA_Argument) * " + str(len(inArgVal)) + ");")
  142. code.append("int inputArgumentCnt;")
  143. code.append("for (inputArgumentCnt=0; inputArgumentCnt<" + str(len(inArgVal)) + "; inputArgumentCnt++) UA_Argument_init(&inputArguments[inputArgumentCnt]); ")
  144. argumentCnt = 0
  145. for inArg in inArgVal:
  146. if inArg.getValueFieldByAlias("Description") != None:
  147. code.append("inputArguments[" + str(argumentCnt) + "].description = UA_LOCALIZEDTEXT(\"" + str(inArg.getValueFieldByAlias("Description")[0]) + "\",\"" + str(inArg.getValueFieldByAlias("Description")[1]) + "\");")
  148. if inArg.getValueFieldByAlias("Name") != None:
  149. code.append("inputArguments[" + str(argumentCnt) + "].name = UA_STRING(\"" + str(inArg.getValueFieldByAlias("Name")) + "\");")
  150. if inArg.getValueFieldByAlias("ValueRank") != None:
  151. code.append("inputArguments[" + str(argumentCnt) + "].valueRank = " + str(inArg.getValueFieldByAlias("ValueRank")) + ";")
  152. if inArg.getValueFieldByAlias("DataType") != None:
  153. code.append("inputArguments[" + str(argumentCnt) + "].dataType = " + str(self.getCreateNodeIDMacro(inArg.getValueFieldByAlias("DataType"))) + ";")
  154. #if inArg.getValueFieldByAlias("ArrayDimensions") != None:
  155. # code.append("inputArguments[" + str(argumentCnt) + "].arrayDimensions = " + str(inArg.getValueFieldByAlias("ArrayDimensions")) + ";")
  156. argumentCnt += 1
  157. if len(outArgVal)>0:
  158. code.append("")
  159. code.append("outputArguments = (UA_Argument *) malloc(sizeof(UA_Argument) * " + str(len(outArgVal)) + ");")
  160. code.append("int outputArgumentCnt;")
  161. code.append("for (outputArgumentCnt=0; outputArgumentCnt<" + str(len(outArgVal)) + "; outputArgumentCnt++) UA_Argument_init(&outputArguments[outputArgumentCnt]); ")
  162. argumentCnt = 0
  163. for outArg in outArgVal:
  164. if outArg.getValueFieldByAlias("Description") != None:
  165. code.append("outputArguments[" + str(argumentCnt) + "].description = UA_LOCALIZEDTEXT(\"" + str(outArg.getValueFieldByAlias("Description")[0]) + "\",\"" + str(outArg.getValueFieldByAlias("Description")[1]) + "\");")
  166. if outArg.getValueFieldByAlias("Name") != None:
  167. code.append("outputArguments[" + str(argumentCnt) + "].name = UA_STRING(\"" + str(outArg.getValueFieldByAlias("Name")) + "\");")
  168. if outArg.getValueFieldByAlias("ValueRank") != None:
  169. code.append("outputArguments[" + str(argumentCnt) + "].valueRank = " + str(outArg.getValueFieldByAlias("ValueRank")) + ";")
  170. if outArg.getValueFieldByAlias("DataType") != None:
  171. code.append("outputArguments[" + str(argumentCnt) + "].dataType = " + str(self.getCreateNodeIDMacro(outArg.getValueFieldByAlias("DataType"))) + ";")
  172. #if outArg.getValueFieldByAlias("ArrayDimensions") != None:
  173. # code.append("outputArguments[" + str(argumentCnt) + "].arrayDimensions = " + str(outArg.getValueFieldByAlias("ArrayDimensions")) + ";")
  174. argumentCnt += 1
  175. # print the attributes struct
  176. code.append("UA_%sAttributes attr;" % nodetype)
  177. code.append("UA_%sAttributes_init(&attr);" % nodetype);
  178. code.append("attr.displayName = UA_LOCALIZEDTEXT(\"\", \"" + str(node.displayName()) + "\");")
  179. code.append("attr.description = UA_LOCALIZEDTEXT(\"\", \"" + str(node.description()) + "\");")
  180. if nodetype in ["Variable", "VariableType"]:
  181. code = code + node.printOpen62541CCode_SubtypeEarly(bootstrapping = False)
  182. elif nodetype == "Method":
  183. if node.executable():
  184. code.append("attr.executable = true;")
  185. if node.userExecutable():
  186. code.append("attr.userExecutable = true;")
  187. code.append("UA_NodeId nodeId = " + str(self.getCreateNodeIDMacro(node)) + ";")
  188. if nodetype in ["Object", "Variable"]:
  189. code.append("UA_NodeId typeDefinition = UA_NODEID_NULL;") # todo instantiation of object and variable types
  190. code.append("UA_NodeId parentNodeId = " + str(self.getCreateNodeIDMacro(parentNode)) + ";")
  191. code.append("UA_NodeId parentReferenceNodeId = " + str(self.getCreateNodeIDMacro(parentReference.referenceType())) + ";")
  192. extrNs = node.browseName().split(":")
  193. if len(extrNs) > 1:
  194. code.append("UA_QualifiedName nodeName = UA_QUALIFIEDNAME(" + str(extrNs[0]) + ", \"" + extrNs[1] + "\");")
  195. else:
  196. code.append("UA_QualifiedName nodeName = UA_QUALIFIEDNAME(0, \"" + str(node.browseName()) + "\");")
  197. # In case of a MethodNode: Add in|outArg struct generation here. Mandates that namespace reordering was done using
  198. # Djikstra (check that arguments have not been printed). (@ichrispa)
  199. code.append("UA_Server_add%sNode(server, nodeId, parentNodeId, parentReferenceNodeId, nodeName" % nodetype)
  200. if nodetype in ["Object", "Variable"]:
  201. code.append(" , typeDefinition")
  202. if nodetype != "Method":
  203. code.append(" , attr, NULL, NULL);")
  204. else:
  205. code.append(" , attr, (UA_MethodCallback) NULL, NULL, " + str(len(inArgVal)) + ", inputArguments, " + str(len(outArgVal)) + ", outputArguments, NULL);")
  206. return code
  207. def getCreateNodeBootstrap(self, node):
  208. nodetype = ""
  209. code = []
  210. code.append("// Node: " + str(node) + ", " + str(node.browseName()))
  211. if node.nodeClass() == NODE_CLASS_OBJECT:
  212. nodetype = "Object"
  213. elif node.nodeClass() == NODE_CLASS_VARIABLE:
  214. nodetype = "Variable"
  215. elif node.nodeClass() == NODE_CLASS_METHOD:
  216. nodetype = "Method"
  217. elif node.nodeClass() == NODE_CLASS_OBJECTTYPE:
  218. nodetype = "ObjectType"
  219. elif node.nodeClass() == NODE_CLASS_REFERENCETYPE:
  220. nodetype = "ReferenceType"
  221. elif node.nodeClass() == NODE_CLASS_VARIABLETYPE:
  222. nodetype = "VariableType"
  223. elif node.nodeClass() == NODE_CLASS_DATATYPE:
  224. nodetype = "DataType"
  225. elif node.nodeClass() == NODE_CLASS_VIEW:
  226. nodetype = "View"
  227. else:
  228. code.append("/* undefined nodeclass */")
  229. return;
  230. code.append("UA_" + nodetype + "Node *" + node.getCodePrintableID() + " = UA_NodeStore_new" + nodetype + "Node();")
  231. if not "browsename" in self.supressGenerationOfAttribute:
  232. extrNs = node.browseName().split(":")
  233. if len(extrNs) > 1:
  234. code.append(node.getCodePrintableID() + "->browseName = UA_QUALIFIEDNAME_ALLOC(" + str(extrNs[0]) + ", \"" + extrNs[1] + "\");")
  235. else:
  236. code.append(node.getCodePrintableID() + "->browseName = UA_QUALIFIEDNAME_ALLOC(0, \"" + node.browseName() + "\");")
  237. if not "displayname" in self.supressGenerationOfAttribute:
  238. code.append(node.getCodePrintableID() + "->displayName = UA_LOCALIZEDTEXT_ALLOC(\"en_US\", \"" + node.displayName() + "\");")
  239. if not "description" in self.supressGenerationOfAttribute:
  240. code.append(node.getCodePrintableID() + "->description = UA_LOCALIZEDTEXT_ALLOC(\"en_US\", \"" + node.description() + "\");")
  241. if not "writemask" in self.supressGenerationOfAttribute:
  242. if node.__node_writeMask__ != 0:
  243. code.append(node.getCodePrintableID() + "->writeMask = (UA_Int32) " + str(node.__node_writeMask__) + ";")
  244. if not "userwritemask" in self.supressGenerationOfAttribute:
  245. if node.__node_userWriteMask__ != 0:
  246. code.append(node.getCodePrintableID() + "->userWriteMask = (UA_Int32) " + str(node.__node_userWriteMask__) + ";")
  247. if not "nodeid" in self.supressGenerationOfAttribute:
  248. if node.id().ns != 0:
  249. code.append(node.getCodePrintableID() + "->nodeId.namespaceIndex = " + str(node.id().ns) + ";")
  250. if node.id().i != None:
  251. code.append(node.getCodePrintableID() + "->nodeId.identifier.numeric = " + str(node.id().i) + ";")
  252. elif node.id().b != None:
  253. code.append(node.getCodePrintableID() + "->nodeId.identifierType = UA_NODEIDTYPE_BYTESTRING;")
  254. log(self, "ByteString IDs for nodes has not been implemented yet.", LOG_LEVEL_ERROR)
  255. return []
  256. elif node.id().g != None:
  257. #<jpfr> the string is sth like { .length = 111, .data = <ptr> }
  258. #<jpfr> there you _may_ alloc the <ptr> on the heap
  259. #<jpfr> for the guid, just set it to {.data1 = 111, .data2 = 2222, ....
  260. code.append(node.getCodePrintableID() + "->nodeId.identifierType = UA_NODEIDTYPE_GUID;")
  261. log(self, "GUIDs for nodes has not been implemented yet.", LOG_LEVEL_ERROR)
  262. return []
  263. elif node.id().s != None:
  264. code.append(node.getCodePrintableID() + "->nodeId.identifierType = UA_NODEIDTYPE_STRING;")
  265. code.append(node.getCodePrintableID() + "->nodeId.identifier.numeric = UA_STRING_ALLOC(\"" + str(node.id().i) + "\");")
  266. else:
  267. log(self, "Node ID is not numeric, bytestring, guid or string. I do not know how to create c code for that...", LOG_LEVEL_ERROR)
  268. return []
  269. return code