backend_open62541_nodes.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  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 nodes import *
  18. from backend_open62541_datatypes import *
  19. import re
  20. import datetime
  21. import logging
  22. logger = logging.getLogger(__name__)
  23. #################
  24. # Generate Code #
  25. #################
  26. def generateNodeIdPrintable(node):
  27. CodePrintable = "NODE_"
  28. if isinstance(node.id, NodeId):
  29. CodePrintable = node.__class__.__name__ + "_" + str(node.id)
  30. else:
  31. CodePrintable = node.__class__.__name__ + "_unknown_nid"
  32. return re.sub('[^0-9a-z_]+', '_', CodePrintable.lower())
  33. def generateNodeValueInstanceName(node, parent, recursionDepth, arrayIndex):
  34. return generateNodeIdPrintable(parent) + "_" + str(node.alias) + "_" + str(arrayIndex) + "_" + str(recursionDepth)
  35. def generateReferenceCode(reference):
  36. if reference.isForward:
  37. return "retVal |= UA_Server_addReference(server, %s, %s, %s, true);" % \
  38. (generateNodeIdCode(reference.source),
  39. generateNodeIdCode(reference.referenceType),
  40. generateExpandedNodeIdCode(reference.target))
  41. else:
  42. return "retVal |= UA_Server_addReference(server, %s, %s, %s, false);" % \
  43. (generateNodeIdCode(reference.source),
  44. generateNodeIdCode(reference.referenceType),
  45. generateExpandedNodeIdCode(reference.target))
  46. def generateReferenceTypeNodeCode(node):
  47. code = []
  48. code.append("UA_ReferenceTypeAttributes attr = UA_ReferenceTypeAttributes_default;")
  49. if node.isAbstract:
  50. code.append("attr.isAbstract = true;")
  51. if node.symmetric:
  52. code.append("attr.symmetric = true;")
  53. if node.inverseName != "":
  54. code.append("attr.inverseName = UA_LOCALIZEDTEXT(\"\", \"%s\");" % \
  55. node.inverseName)
  56. return code
  57. def generateObjectNodeCode(node):
  58. code = []
  59. code.append("UA_ObjectAttributes attr = UA_ObjectAttributes_default;")
  60. if node.eventNotifier:
  61. code.append("attr.eventNotifier = true;")
  62. return code
  63. def generateVariableNodeCode(node, nodeset, max_string_length):
  64. code = []
  65. codeCleanup = []
  66. code.append("UA_VariableAttributes attr = UA_VariableAttributes_default;")
  67. if node.historizing:
  68. code.append("attr.historizing = true;")
  69. code.append("attr.minimumSamplingInterval = %f;" % node.minimumSamplingInterval)
  70. code.append("attr.userAccessLevel = %d;" % node.userAccessLevel)
  71. code.append("attr.accessLevel = %d;" % node.accessLevel)
  72. # in order to be compatible with mostly OPC UA client
  73. # force valueRank = -1 for scalar VariableNode
  74. if node.valueRank == -2:
  75. node.valueRank = -1
  76. code.append("attr.valueRank = %d;" % node.valueRank)
  77. if node.valueRank > 0:
  78. code.append("attr.arrayDimensionsSize = %d;" % node.valueRank)
  79. code.append("attr.arrayDimensions = (UA_UInt32 *)UA_Array_new({}, &UA_TYPES[UA_TYPES_UINT32]);".format(node.valueRank))
  80. codeCleanup.append("UA_Array_delete(attr.arrayDimensions, {}, &UA_TYPES[UA_TYPES_UINT32]);".format(node.valueRank))
  81. for dim in range(0, node.valueRank):
  82. code.append("attr.arrayDimensions[{}] = 0;".format(dim))
  83. if node.dataType is not None:
  84. if isinstance(node.dataType, NodeId) and node.dataType.ns == 0 and node.dataType.i == 0:
  85. #BaseDataType
  86. dataTypeNode = nodeset.nodes[NodeId("i=24")]
  87. dataTypeNodeOpaque = nodeset.nodes[NodeId("i=24")]
  88. else:
  89. dataTypeNodeOpaque = nodeset.getDataTypeNode(node.dataType)
  90. dataTypeNode = nodeset.getBaseDataType(nodeset.getDataTypeNode(node.dataType))
  91. if dataTypeNode is not None:
  92. code.append("attr.dataType = %s;" % generateNodeIdCode(dataTypeNodeOpaque.id))
  93. if dataTypeNode.isEncodable():
  94. if node.value is not None:
  95. [code1, codeCleanup1] = generateValueCode(node.value, nodeset.nodes[node.id], nodeset, max_string_length=max_string_length)
  96. code += code1
  97. codeCleanup += codeCleanup1
  98. else:
  99. code += generateValueCodeDummy(dataTypeNode, nodeset.nodes[node.id], nodeset)
  100. return [code, codeCleanup]
  101. def generateVariableTypeNodeCode(node, nodeset, max_string_length):
  102. code = []
  103. codeCleanup = []
  104. code.append("UA_VariableTypeAttributes attr = UA_VariableTypeAttributes_default;")
  105. if node.historizing:
  106. code.append("attr.historizing = true;")
  107. if node.isAbstract:
  108. code.append("attr.isAbstract = true;")
  109. code.append("attr.valueRank = (UA_Int32)%s;" % str(node.valueRank))
  110. if node.dataType is not None:
  111. if isinstance(node.dataType, NodeId) and node.dataType.ns == 0 and node.dataType.i == 0:
  112. #BaseDataType
  113. dataTypeNode = nodeset.nodes[NodeId("i=24")]
  114. else:
  115. dataTypeNode = nodeset.getBaseDataType(nodeset.getDataTypeNode(node.dataType))
  116. if dataTypeNode is not None:
  117. code.append("attr.dataType = %s;" % generateNodeIdCode(dataTypeNode.id))
  118. if dataTypeNode.isEncodable():
  119. if node.value is not None:
  120. [code1, codeCleanup1] = generateValueCode(node.value, nodeset.nodes[node.id], nodeset, max_string_length)
  121. code += code1
  122. codeCleanup += codeCleanup1
  123. else:
  124. code += generateValueCodeDummy(dataTypeNode, nodeset.nodes[node.id], nodeset)
  125. return [code, codeCleanup]
  126. def generateExtensionObjectSubtypeCode(node, parent, nodeset, recursionDepth=0, arrayIndex=0, max_string_length=0):
  127. code = [""]
  128. codeCleanup = [""]
  129. logger.debug("Building extensionObject for " + str(parent.id))
  130. logger.debug("Value " + str(node.value))
  131. logger.debug("Encoding " + str(node.encodingRule))
  132. instanceName = generateNodeValueInstanceName(node, parent, recursionDepth, arrayIndex)
  133. # If there are any ExtensionObjects instide this ExtensionObject, we need to
  134. # generate one-time-structs for them too before we can proceed;
  135. for subv in node.value:
  136. if isinstance(subv, list):
  137. logger.error("ExtensionObject contains an ExtensionObject, which is currently not encodable!")
  138. code.append("struct {")
  139. for field in node.encodingRule:
  140. ptrSym = ""
  141. # If this is an Array, this is pointer to its contents with a AliasOfFieldSize entry
  142. if field[2] != 0:
  143. code.append(" UA_Int32 " + str(field[0]) + "Size;")
  144. ptrSym = "*"
  145. if len(field[1]) == 1:
  146. code.append(" UA_" + str(field[1][0]) + " " + ptrSym + str(field[0]) + ";")
  147. else:
  148. code.append(" UA_ExtensionObject " + " " + ptrSym + str(field[0]) + ";")
  149. code.append("} " + instanceName + "_struct;")
  150. # Assign data to the struct contents
  151. # Track the encoding rule definition to detect arrays and/or ExtensionObjects
  152. encFieldIdx = 0
  153. for subv in node.value:
  154. encField = node.encodingRule[encFieldIdx]
  155. encFieldIdx = encFieldIdx + 1
  156. logger.debug(
  157. "Encoding of field " + subv.alias + " is " + str(subv.encodingRule) + "defined by " + str(encField))
  158. # Check if this is an array
  159. if encField[2] == 0:
  160. code.append(instanceName + "_struct." + subv.alias + " = " +
  161. generateNodeValueCode(subv, instanceName, asIndirect=False, max_string_length=max_string_length) + ";")
  162. else:
  163. if isinstance(subv, list):
  164. # this is an array
  165. code.append(instanceName + "_struct." + subv.alias + "Size = " + str(len(subv)) + ";")
  166. code.append(
  167. "{0}_struct.{1} = (UA_{2}*) UA_malloc(sizeof(UA_{2})*{3});".format(
  168. instanceName, subv.alias, subv.__class__.__name__, str(len(subv))))
  169. codeCleanup.append("UA_free({0}_struct.{1});".format(instanceName, subv.alias))
  170. logger.debug("Encoding included array of " + str(len(subv)) + " values.")
  171. for subvidx in range(0, len(subv)):
  172. subvv = subv[subvidx]
  173. logger.debug(" " + str(subvidx) + " " + str(subvv))
  174. code.append(instanceName + "_struct." + subv.alias + "[" + str(
  175. subvidx) + "] = " + generateNodeValueCode(subvv, instanceName, max_string_length=max_string_length) + ";")
  176. code.append("}")
  177. else:
  178. code.append(instanceName + "_struct." + subv.alias + "Size = 1;")
  179. code.append(
  180. "{0}_struct.{1} = (UA_{2}*) UA_malloc(sizeof(UA_{2}));".format(
  181. instanceName, subv.alias, subv.__class__.__name__))
  182. codeCleanup.append("UA_free({0}_struct.{1});".format(instanceName, subv.alias))
  183. code.append(instanceName + "_struct." + subv.alias + "[0] = " +
  184. generateNodeValueCode(subv, instanceName, asIndirect=True, max_string_length=max_string_length) + ";")
  185. # Allocate some memory
  186. code.append("UA_ExtensionObject *" + instanceName + " = UA_ExtensionObject_new();")
  187. codeCleanup.append("UA_ExtensionObject_delete(" + instanceName + ");")
  188. code.append(instanceName + "->encoding = UA_EXTENSIONOBJECT_ENCODED_BYTESTRING;")
  189. #if parent.dataType.ns == 0:
  190. binaryEncodingId = nodeset.getBinaryEncodingIdForNode(parent.dataType)
  191. code.append(
  192. instanceName + "->content.encoded.typeId = UA_NODEID_NUMERIC(" + str(binaryEncodingId.ns) + ", " +
  193. str(binaryEncodingId.i) + ");")
  194. code.append(
  195. "UA_ByteString_allocBuffer(&" + instanceName + "->content.encoded.body, 65000);")
  196. # Encode each value as a bytestring separately.
  197. code.append("UA_Byte *pos" + instanceName + " = " + instanceName + "->content.encoded.body.data;")
  198. code.append("const UA_Byte *end" + instanceName + " = &" + instanceName + "->content.encoded.body.data[65000];")
  199. encFieldIdx = 0
  200. code.append("{")
  201. for subv in node.value:
  202. encField = node.encodingRule[encFieldIdx]
  203. encFieldIdx = encFieldIdx + 1
  204. if encField[2] == 0:
  205. code.append(
  206. "retVal |= UA_encodeBinary(&" + instanceName + "_struct." + subv.alias + ", " +
  207. getTypesArrayForValue(nodeset, subv) + ", &pos" + instanceName + ", &end" + instanceName + ", NULL, NULL);")
  208. else:
  209. if isinstance(subv, list):
  210. for subvidx in range(0, len(subv)):
  211. code.append("retVal |= UA_encodeBinary(&" + instanceName + "_struct." + subv.alias + "[" +
  212. str(subvidx) + "], " + getTypesArrayForValue(nodeset, subv) + ", &pos" +
  213. instanceName + ", &end" + instanceName + ", NULL, NULL);")
  214. else:
  215. code.append(
  216. "retVal |= UA_encodeBinary(&" + instanceName + "_struct." + subv.alias + "[0], " +
  217. getTypesArrayForValue(nodeset, subv) + ", &pos" + instanceName + ", &end" + instanceName + ", NULL, NULL);")
  218. code.append("}")
  219. # Reallocate the memory by swapping the 65k Bytestring for a new one
  220. code.append("size_t " + instanceName + "_encOffset = (uintptr_t)(" +
  221. "pos" + instanceName + "-" + instanceName + "->content.encoded.body.data);")
  222. code.append(instanceName + "->content.encoded.body.length = " + instanceName + "_encOffset;")
  223. code.append("UA_Byte *" + instanceName + "_newBody = (UA_Byte *) UA_malloc(" + instanceName + "_encOffset);")
  224. code.append("memcpy(" + instanceName + "_newBody, " + instanceName + "->content.encoded.body.data, " +
  225. instanceName + "_encOffset);")
  226. code.append("UA_Byte *" + instanceName + "_oldBody = " + instanceName + "->content.encoded.body.data;")
  227. code.append(instanceName + "->content.encoded.body.data = " + instanceName + "_newBody;")
  228. code.append("UA_free(" + instanceName + "_oldBody);")
  229. code.append("")
  230. return [code, codeCleanup]
  231. def generateValueCodeDummy(dataTypeNode, parentNode, nodeset):
  232. code = []
  233. valueName = generateNodeIdPrintable(parentNode) + "_variant_DataContents"
  234. typeBrowseNode = dataTypeNode.browseName.name
  235. if typeBrowseNode == "NumericRange":
  236. # in the stack we define a separate structure for the numeric range, but
  237. # the value itself is just a string
  238. typeBrowseNode = "String"
  239. typeArr = dataTypeNode.typesArray + "[" + dataTypeNode.typesArray + "_" + typeBrowseNode.upper() + "]"
  240. typeStr = "UA_" + typeBrowseNode
  241. if parentNode.valueRank > 0:
  242. for i in range(0, parentNode.valueRank):
  243. code.append("UA_Variant_setArray(&attr.value, NULL, (UA_Int32) " + "0, &" + typeArr + ");")
  244. elif not dataTypeNode.isAbstract:
  245. code.append("UA_STACKARRAY(" + typeStr + ", " + valueName + ", 1);")
  246. code.append("UA_init(" + valueName + ", &" + typeArr + ");")
  247. code.append("UA_Variant_setScalar(&attr.value, " + valueName + ", &" + typeArr + ");")
  248. return code
  249. def getTypesArrayForValue(nodeset, value):
  250. typeNode = nodeset.getNodeByBrowseName(value.__class__.__name__)
  251. if typeNode is None or value.isInternal:
  252. typesArray = "UA_TYPES"
  253. else:
  254. typesArray = typeNode.typesArray
  255. return "&" + typesArray + "[" + typesArray + "_" + \
  256. value.__class__.__name__.upper() + "]"
  257. def generateValueCode(node, parentNode, nodeset, bootstrapping=True, max_string_length=0):
  258. code = []
  259. codeCleanup = []
  260. valueName = generateNodeIdPrintable(parentNode) + "_variant_DataContents"
  261. # node.value either contains a list of multiple identical BUILTINTYPES, or it
  262. # contains a single builtintype (which may be a container); choose if we need
  263. # to create an array or a single variable.
  264. # Note that some genious defined that there are arrays of size 1, which are
  265. # distinctly different then a single value, so we need to check that as well
  266. # Semantics:
  267. # -3: Scalar or 1-dim
  268. # -2: Scalar or x-dim | x>0
  269. # -1: Scalar
  270. # 0: x-dim | x>0
  271. # n: n-dim | n>0
  272. if (len(node.value) == 0):
  273. return ["", ""]
  274. if not isinstance(node.value[0], Value):
  275. return ["", ""]
  276. if parentNode.valueRank != -1 and (parentNode.valueRank >= 0
  277. or (len(node.value) > 1
  278. and (parentNode.valueRank != -2 or parentNode.valueRank != -3))):
  279. # User the following strategy for all directly mappable values a la 'UA_Type MyInt = (UA_Type) 23;'
  280. if node.value[0].numericRepresentation == BUILTINTYPE_TYPEID_GUID:
  281. logger.warn("Don't know how to print array of GUID in node " + str(parentNode.id))
  282. elif node.value[0].numericRepresentation == BUILTINTYPE_TYPEID_DIAGNOSTICINFO:
  283. logger.warn("Don't know how to print array of DiagnosticInfo in node " + str(parentNode.id))
  284. elif node.value[0].numericRepresentation == BUILTINTYPE_TYPEID_STATUSCODE:
  285. logger.warn("Don't know how to print array of StatusCode in node " + str(parentNode.id))
  286. else:
  287. if node.value[0].numericRepresentation == BUILTINTYPE_TYPEID_EXTENSIONOBJECT:
  288. for idx, v in enumerate(node.value):
  289. logger.debug("Building extObj array index " + str(idx))
  290. [code1, codeCleanup1] = generateExtensionObjectSubtypeCode(v, parent=parentNode, nodeset=nodeset, arrayIndex=idx, max_string_length=max_string_length)
  291. code = code + code1
  292. codeCleanup = codeCleanup + codeCleanup1
  293. code.append("UA_" + node.value[0].__class__.__name__ + " " + valueName + "[" + str(len(node.value)) + "];")
  294. if node.value[0].numericRepresentation == BUILTINTYPE_TYPEID_EXTENSIONOBJECT:
  295. for idx, v in enumerate(node.value):
  296. logger.debug("Printing extObj array index " + str(idx))
  297. instanceName = generateNodeValueInstanceName(v, parentNode, 0, idx)
  298. code.append(
  299. valueName + "[" + str(idx) + "] = " +
  300. generateNodeValueCode(v, instanceName, max_string_length=max_string_length) + ";")
  301. # code.append("UA_free(&" +valueName + "[" + str(idx) + "]);")
  302. else:
  303. for idx, v in enumerate(node.value):
  304. instanceName = generateNodeValueInstanceName(v, parentNode, 0, idx)
  305. code.append(
  306. valueName + "[" + str(idx) + "] = " + generateNodeValueCode(v, instanceName, max_string_length=max_string_length) + ";")
  307. code.append("UA_Variant_setArray(&attr.value, &" + valueName +
  308. ", (UA_Int32) " + str(len(node.value)) + ", " +
  309. getTypesArrayForValue(nodeset, node.value[0]) + ");")
  310. else:
  311. # User the following strategy for all directly mappable values a la 'UA_Type MyInt = (UA_Type) 23;'
  312. if node.value[0].numericRepresentation == BUILTINTYPE_TYPEID_GUID:
  313. logger.warn("Don't know how to print scalar GUID in node " + str(parentNode.id))
  314. elif node.value[0].numericRepresentation == BUILTINTYPE_TYPEID_DIAGNOSTICINFO:
  315. logger.warn("Don't know how to print scalar DiagnosticInfo in node " + str(parentNode.id))
  316. elif node.value[0].numericRepresentation == BUILTINTYPE_TYPEID_STATUSCODE:
  317. logger.warn("Don't know how to print scalar StatusCode in node " + str(parentNode.id))
  318. else:
  319. # The following strategy applies to all other types, in particular strings and numerics.
  320. if node.value[0].numericRepresentation == BUILTINTYPE_TYPEID_EXTENSIONOBJECT:
  321. [code1, codeCleanup1] = generateExtensionObjectSubtypeCode(node.value[0], parent=parentNode, nodeset=nodeset, max_string_length=max_string_length)
  322. code = code + code1
  323. codeCleanup = codeCleanup + codeCleanup1
  324. instanceName = generateNodeValueInstanceName(node.value[0], parentNode, 0, 0)
  325. if node.value[0].numericRepresentation == BUILTINTYPE_TYPEID_EXTENSIONOBJECT:
  326. code.append("UA_" + node.value[0].__class__.__name__ + " *" + valueName + " = " +
  327. generateNodeValueCode(node.value[0], instanceName, max_string_length=max_string_length) + ";")
  328. code.append(
  329. "UA_Variant_setScalar(&attr.value, " + valueName + ", " +
  330. getTypesArrayForValue(nodeset, node.value[0]) + ");")
  331. # FIXME: There is no membership definition for extensionObjects generated in this function.
  332. # code.append("UA_" + node.value[0].__class__.__name__ + "_deleteMembers(" + valueName + ");")
  333. else:
  334. code.append("UA_" + node.value[0].__class__.__name__ + " *" + valueName + " = UA_" + node.value[
  335. 0].__class__.__name__ + "_new();")
  336. code.append("*" + valueName + " = " + generateNodeValueCode(node.value[0], instanceName, asIndirect=True, max_string_length=max_string_length) + ";")
  337. code.append(
  338. "UA_Variant_setScalar(&attr.value, " + valueName + ", " +
  339. getTypesArrayForValue(nodeset, node.value[0]) + ");")
  340. codeCleanup.append("UA_{0}_delete({1});".format(
  341. node.value[0].__class__.__name__, valueName))
  342. return [code, codeCleanup]
  343. def generateMethodNodeCode(node):
  344. code = []
  345. code.append("UA_MethodAttributes attr = UA_MethodAttributes_default;")
  346. if node.executable:
  347. code.append("attr.executable = true;")
  348. if node.userExecutable:
  349. code.append("attr.userExecutable = true;")
  350. return code
  351. def generateObjectTypeNodeCode(node):
  352. code = []
  353. code.append("UA_ObjectTypeAttributes attr = UA_ObjectTypeAttributes_default;")
  354. if node.isAbstract:
  355. code.append("attr.isAbstract = true;")
  356. return code
  357. def generateDataTypeNodeCode(node):
  358. code = []
  359. code.append("UA_DataTypeAttributes attr = UA_DataTypeAttributes_default;")
  360. if node.isAbstract:
  361. code.append("attr.isAbstract = true;")
  362. return code
  363. def generateViewNodeCode(node):
  364. code = []
  365. code.append("UA_ViewAttributes attr = UA_ViewAttributes_default;")
  366. if node.containsNoLoops:
  367. code.append("attr.containsNoLoops = true;")
  368. code.append("attr.eventNotifier = (UA_Byte)%s;" % str(node.eventNotifier))
  369. return code
  370. def getNodeTypeDefinition(node):
  371. for ref in node.references:
  372. # 40 = HasTypeDefinition
  373. if ref.referenceType.i == 40:
  374. return ref.target
  375. return None
  376. def generateSubtypeOfDefinitionCode(node):
  377. for ref in node.inverseReferences:
  378. # 45 = HasSubtype
  379. if ref.referenceType.i == 45:
  380. return generateNodeIdCode(ref.target)
  381. return "UA_NODEID_NULL"
  382. def generateNodeCode_begin(node, nodeset, max_string_length, generate_ns0, parentref):
  383. code = []
  384. codeCleanup = []
  385. code.append("UA_StatusCode retVal = UA_STATUSCODE_GOOD;")
  386. # Attributes
  387. if isinstance(node, ReferenceTypeNode):
  388. code.extend(generateReferenceTypeNodeCode(node))
  389. elif isinstance(node, ObjectNode):
  390. code.extend(generateObjectNodeCode(node))
  391. elif isinstance(node, VariableNode) and not isinstance(node, VariableTypeNode):
  392. [code1, codeCleanup1] = generateVariableNodeCode(node, nodeset, max_string_length)
  393. code.extend(code1)
  394. codeCleanup.extend(codeCleanup1)
  395. elif isinstance(node, VariableTypeNode):
  396. [code1, codeCleanup1] = generateVariableTypeNodeCode(node, nodeset, max_string_length)
  397. code.extend(code1)
  398. codeCleanup.extend(codeCleanup1)
  399. elif isinstance(node, MethodNode):
  400. code.extend(generateMethodNodeCode(node))
  401. elif isinstance(node, ObjectTypeNode):
  402. code.extend(generateObjectTypeNodeCode(node))
  403. elif isinstance(node, DataTypeNode):
  404. code.extend(generateDataTypeNodeCode(node))
  405. elif isinstance(node, ViewNode):
  406. code.extend(generateViewNodeCode(node))
  407. code.append("attr.displayName = " + generateLocalizedTextCode(node.displayName, alloc=False,
  408. max_string_length=max_string_length) + ";")
  409. code.append("attr.description = " + generateLocalizedTextCode(node.description, alloc=False,
  410. max_string_length=max_string_length) + ";")
  411. code.append("attr.writeMask = %d;" % node.writeMask)
  412. code.append("attr.userWriteMask = %d;" % node.userWriteMask)
  413. # AddNodes call
  414. code.append("retVal |= UA_Server_addNode_begin(server, UA_NODECLASS_{},".
  415. format(node.__class__.__name__.upper().replace("NODE" ,"")))
  416. code.append(generateNodeIdCode(node.id) + ",")
  417. code.append(generateNodeIdCode(parentref.target) + ",")
  418. code.append(generateNodeIdCode(parentref.referenceType) + ",")
  419. code.append(generateQualifiedNameCode(node.browseName, max_string_length=max_string_length) + ",")
  420. if isinstance(node, VariableNode) or isinstance(node, ObjectNode):
  421. typeDefRef = node.popTypeDef()
  422. code.append(generateNodeIdCode(typeDefRef.target) + ",")
  423. else:
  424. code.append(" UA_NODEID_NULL,")
  425. code.append("(const UA_NodeAttributes*)&attr, &UA_TYPES[UA_TYPES_{}ATTRIBUTES],NULL, NULL);".
  426. format(node.__class__.__name__.upper().replace("NODE" ,"")))
  427. code.extend(codeCleanup)
  428. return "\n".join(code)
  429. def generateNodeCode_finish(node):
  430. code = []
  431. if isinstance(node, MethodNode):
  432. code.append("UA_Server_addMethodNode_finish(server, ")
  433. else:
  434. code.append("UA_Server_addNode_finish(server, ")
  435. code.append(generateNodeIdCode(node.id))
  436. if isinstance(node, MethodNode):
  437. code.append(", NULL, 0, NULL, 0, NULL);")
  438. else:
  439. code.append(");")
  440. return "\n".join(code)