backend_open62541_nodes.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  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):
  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
  263. # the value itself is just a string
  264. typeBrowseNode = "String"
  265. typeArr = dataTypeNode.typesArray + "[" + dataTypeNode.typesArray + "_" + typeBrowseNode.upper() + "]"
  266. typeStr = "UA_" + typeBrowseNode
  267. if parentNode.valueRank > 0:
  268. code.append("UA_STACKARRAY(" + typeStr + ", " + valueName + "," + str(parentNode.valueRank) + ");")
  269. for i in range(0, parentNode.valueRank):
  270. code.append("UA_init(&" + valueName + "[" + str(i) + "], &" + typeArr + ");")
  271. code.append("UA_Variant_setArray(&attr.value, " + valueName + ", (UA_Int32) " +
  272. str(parentNode.valueRank) + ", &" + typeArr + ");")
  273. else:
  274. code.append("UA_STACKARRAY(" + typeStr + ", " + valueName + ", 1);")
  275. code.append("UA_init(" + valueName + ", &" + typeArr + ");")
  276. code.append("UA_Variant_setScalar(&attr.value, " + valueName + ", &" + typeArr + ");")
  277. return code
  278. def getTypesArrayForValue(nodeset, value):
  279. typeNode = nodeset.getNodeByBrowseName(value.__class__.__name__)
  280. if typeNode is None or value.isInternal:
  281. typesArray = "UA_TYPES"
  282. else:
  283. typesArray = typeNode.typesArray
  284. return "&" + typesArray + "[" + typesArray + "_" + \
  285. value.__class__.__name__.upper() + "]"
  286. def generateValueCode(node, parentNode, nodeset, bootstrapping=True, max_string_length=0):
  287. code = []
  288. codeCleanup = []
  289. valueName = generateNodeIdPrintable(parentNode) + "_variant_DataContents"
  290. # node.value either contains a list of multiple identical BUILTINTYPES, or it
  291. # contains a single builtintype (which may be a container); choose if we need
  292. # to create an array or a single variable.
  293. # Note that some genious defined that there are arrays of size 1, which are
  294. # distinctly different then a single value, so we need to check that as well
  295. # Semantics:
  296. # -3: Scalar or 1-dim
  297. # -2: Scalar or x-dim | x>0
  298. # -1: Scalar
  299. # 0: x-dim | x>0
  300. # n: n-dim | n>0
  301. if (len(node.value) == 0):
  302. return ["", ""]
  303. if not isinstance(node.value[0], Value):
  304. return ["", ""]
  305. if parentNode.valueRank != -1 and (parentNode.valueRank >= 0
  306. or (len(node.value) > 1
  307. and (parentNode.valueRank != -2 or parentNode.valueRank != -3))):
  308. # User the following strategy for all directly mappable values a la 'UA_Type MyInt = (UA_Type) 23;'
  309. if node.value[0].numericRepresentation == BUILTINTYPE_TYPEID_GUID:
  310. logger.warn("Don't know how to print array of GUID in node " + str(parentNode.id))
  311. elif node.value[0].numericRepresentation == BUILTINTYPE_TYPEID_DIAGNOSTICINFO:
  312. logger.warn("Don't know how to print array of DiagnosticInfo in node " + str(parentNode.id))
  313. elif node.value[0].numericRepresentation == BUILTINTYPE_TYPEID_STATUSCODE:
  314. logger.warn("Don't know how to print array of StatusCode in node " + str(parentNode.id))
  315. else:
  316. if node.value[0].numericRepresentation == BUILTINTYPE_TYPEID_EXTENSIONOBJECT:
  317. for idx, v in enumerate(node.value):
  318. logger.debug("Building extObj array index " + str(idx))
  319. [code1, codeCleanup1] = generateExtensionObjectSubtypeCode(v, parent=parentNode, nodeset=nodeset, arrayIndex=idx, max_string_length=max_string_length)
  320. code = code + code1
  321. codeCleanup = codeCleanup + codeCleanup1
  322. code.append("UA_" + node.value[0].__class__.__name__ + " " + valueName + "[" + str(len(node.value)) + "];")
  323. if node.value[0].numericRepresentation == BUILTINTYPE_TYPEID_EXTENSIONOBJECT:
  324. for idx, v in enumerate(node.value):
  325. logger.debug("Printing extObj array index " + str(idx))
  326. instanceName = generateNodeValueInstanceName(v, parentNode, 0, idx)
  327. code.append(
  328. valueName + "[" + str(idx) + "] = " +
  329. generateNodeValueCode(v, instanceName, max_string_length=max_string_length) + ";")
  330. # code.append("UA_free(&" +valueName + "[" + str(idx) + "]);")
  331. else:
  332. for idx, v in enumerate(node.value):
  333. instanceName = generateNodeValueInstanceName(v, parentNode, 0, idx)
  334. code.append(
  335. valueName + "[" + str(idx) + "] = " + generateNodeValueCode(v, instanceName, max_string_length=max_string_length) + ";")
  336. code.append("UA_Variant_setArray(&attr.value, &" + valueName +
  337. ", (UA_Int32) " + str(len(node.value)) + ", " +
  338. getTypesArrayForValue(nodeset, node.value[0]) + ");")
  339. else:
  340. # User the following strategy for all directly mappable values a la 'UA_Type MyInt = (UA_Type) 23;'
  341. if node.value[0].numericRepresentation == BUILTINTYPE_TYPEID_GUID:
  342. logger.warn("Don't know how to print scalar GUID in node " + str(parentNode.id))
  343. elif node.value[0].numericRepresentation == BUILTINTYPE_TYPEID_DIAGNOSTICINFO:
  344. logger.warn("Don't know how to print scalar DiagnosticInfo in node " + str(parentNode.id))
  345. elif node.value[0].numericRepresentation == BUILTINTYPE_TYPEID_STATUSCODE:
  346. logger.warn("Don't know how to print scalar StatusCode in node " + str(parentNode.id))
  347. else:
  348. # The following strategy applies to all other types, in particular strings and numerics.
  349. if node.value[0].numericRepresentation == BUILTINTYPE_TYPEID_EXTENSIONOBJECT:
  350. [code1, codeCleanup1] = generateExtensionObjectSubtypeCode(node.value[0], parent=parentNode, nodeset=nodeset, max_string_length=max_string_length)
  351. code = code + code1
  352. codeCleanup = codeCleanup + codeCleanup1
  353. instanceName = generateNodeValueInstanceName(node.value[0], parentNode, 0, 0)
  354. if node.value[0].numericRepresentation == BUILTINTYPE_TYPEID_EXTENSIONOBJECT:
  355. code.append("UA_" + node.value[0].__class__.__name__ + " *" + valueName + " = " +
  356. generateNodeValueCode(node.value[0], instanceName, max_string_length=max_string_length) + ";")
  357. code.append(
  358. "UA_Variant_setScalar(&attr.value, " + valueName + ", " +
  359. getTypesArrayForValue(nodeset, node.value[0]) + ");")
  360. # FIXME: There is no membership definition for extensionObjects generated in this function.
  361. # code.append("UA_" + node.value[0].__class__.__name__ + "_deleteMembers(" + valueName + ");")
  362. else:
  363. code.append("UA_" + node.value[0].__class__.__name__ + " *" + valueName + " = UA_" + node.value[
  364. 0].__class__.__name__ + "_new();")
  365. code.append("*" + valueName + " = " + generateNodeValueCode(node.value[0], instanceName, asIndirect=True, max_string_length=max_string_length) + ";")
  366. code.append(
  367. "UA_Variant_setScalar(&attr.value, " + valueName + ", " +
  368. getTypesArrayForValue(nodeset, node.value[0]) + ");")
  369. codeCleanup.append("UA_{0}_delete({1});".format(
  370. node.value[0].__class__.__name__, valueName))
  371. return [code, codeCleanup]
  372. def generateMethodNodeCode(node):
  373. code = []
  374. code.append("UA_MethodAttributes attr = UA_MethodAttributes_default;")
  375. if node.executable:
  376. code.append("attr.executable = true;")
  377. if node.userExecutable:
  378. code.append("attr.userExecutable = true;")
  379. return code
  380. def generateObjectTypeNodeCode(node):
  381. code = []
  382. code.append("UA_ObjectTypeAttributes attr = UA_ObjectTypeAttributes_default;")
  383. if node.isAbstract:
  384. code.append("attr.isAbstract = true;")
  385. return code
  386. def generateDataTypeNodeCode(node):
  387. code = []
  388. code.append("UA_DataTypeAttributes attr = UA_DataTypeAttributes_default;")
  389. if node.isAbstract:
  390. code.append("attr.isAbstract = true;")
  391. return code
  392. def generateViewNodeCode(node):
  393. code = []
  394. code.append("UA_ViewAttributes attr = UA_ViewAttributes_default;")
  395. if node.containsNoLoops:
  396. code.append("attr.containsNoLoops = true;")
  397. code.append("attr.eventNotifier = (UA_Byte)%s;" % str(node.eventNotifier))
  398. return code
  399. def getNodeTypeDefinition(node):
  400. for ref in node.references:
  401. # 40 = HasTypeDefinition
  402. if ref.referenceType.i == 40:
  403. return ref.target
  404. return None
  405. def generateSubtypeOfDefinitionCode(node):
  406. for ref in node.inverseReferences:
  407. # 45 = HasSubtype
  408. if ref.referenceType.i == 45:
  409. return generateNodeIdCode(ref.target)
  410. return "UA_NODEID_NULL"
  411. def generateNodeCode_begin(node, nodeset, max_string_length, generate_ns0, parentrefs):
  412. code = []
  413. code.append("UA_StatusCode retVal = UA_STATUSCODE_GOOD;")
  414. codeCleanup = []
  415. if isinstance(node, ReferenceTypeNode):
  416. code.extend(generateReferenceTypeNodeCode(node))
  417. elif isinstance(node, ObjectNode):
  418. code.extend(generateObjectNodeCode(node))
  419. elif isinstance(node, VariableNode) and not isinstance(node, VariableTypeNode):
  420. [code1, codeCleanup1] = generateVariableNodeCode(node, nodeset, max_string_length)
  421. code.extend(code1)
  422. codeCleanup.extend(codeCleanup1)
  423. elif isinstance(node, VariableTypeNode):
  424. [code1, codeCleanup1] = generateVariableTypeNodeCode(node, nodeset, max_string_length)
  425. code.extend(code1)
  426. codeCleanup.extend(codeCleanup1)
  427. elif isinstance(node, MethodNode):
  428. code.extend(generateMethodNodeCode(node))
  429. elif isinstance(node, ObjectTypeNode):
  430. code.extend(generateObjectTypeNodeCode(node))
  431. elif isinstance(node, DataTypeNode):
  432. code.extend(generateDataTypeNodeCode(node))
  433. elif isinstance(node, ViewNode):
  434. code.extend(generateViewNodeCode(node))
  435. code.append("attr.displayName = " + generateLocalizedTextCode(node.displayName, alloc=False, max_string_length=max_string_length) + ";")
  436. code.append("attr.description = " + generateLocalizedTextCode(node.description, alloc=False, max_string_length=max_string_length) + ";")
  437. code.append("attr.writeMask = %d;" % node.writeMask)
  438. code.append("attr.userWriteMask = %d;" % node.userWriteMask)
  439. typeDef = getNodeTypeDefinition(node)
  440. isDataTypeEncodingType = typeDef is not None and typeDef.ns == 0 and typeDef.i == 76
  441. # Object nodes of type DataTypeEncoding do not have any parent
  442. if not generate_ns0 and not isDataTypeEncodingType:
  443. (parentNode, parentRef) = extractNodeParent(node, parentrefs)
  444. if parentNode is None or parentRef is None:
  445. return None
  446. else:
  447. (parentNode, parentRef) = (NodeId(), NodeId())
  448. code.append("retVal |= UA_Server_addNode_begin(server, UA_NODECLASS_{},".format(node.__class__.__name__.upper().replace("NODE" ,"")))
  449. code.append(generateNodeIdCode(node.id) + ",")
  450. code.append(generateNodeIdCode(parentNode) + ",")
  451. code.append(generateNodeIdCode(parentRef) + ",")
  452. code.append(generateQualifiedNameCode(node.browseName, max_string_length=max_string_length) + ",")
  453. if isinstance(node, VariableTypeNode):
  454. # we need the HasSubtype reference
  455. code.append(generateSubtypeOfDefinitionCode(node) + ",")
  456. elif isinstance(node, VariableNode) or isinstance(node, ObjectNode):
  457. typeDefCode = "UA_NODEID_NULL" if typeDef is None else generateNodeIdCode(typeDef)
  458. code.append(typeDefCode + ",")
  459. # remove hasTypeDef reference from list to be printed
  460. for ref in node.printRefs:
  461. if ref.referenceType.i == 40:
  462. if (ref.isForward and ref.source == node.id) or (not ref.isForward and ref.target == node.id):
  463. node.printRefs.remove(ref)
  464. else:
  465. code.append("UA_NODEID_NULL,")
  466. code.append("(const UA_NodeAttributes*)&attr, &UA_TYPES[UA_TYPES_{}ATTRIBUTES],NULL, NULL);".format(node.__class__.__name__.upper().replace("NODE" ,"")))
  467. code.extend(codeCleanup)
  468. return "\n".join(code)
  469. def generateNodeCode_finish(node):
  470. code = []
  471. if isinstance(node, MethodNode):
  472. code.append("UA_Server_addMethodNode_finish(server, ")
  473. else:
  474. code.append("UA_Server_addNode_finish(server, ")
  475. code.append(generateNodeIdCode(node.id))
  476. if isinstance(node, MethodNode):
  477. code.append(", NULL, 0, NULL, 0, NULL);")
  478. else:
  479. code.append(");")
  480. return "\n".join(code)