open62541_MacroHelper.py 14 KB

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