backend_open62541_nodes.py 25 KB

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