backend_open62541_nodes.py 25 KB

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