backend_open62541_nodes.py 26 KB

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