backend_open62541_nodes.py 25 KB

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