backend_open62541_nodes.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556
  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 logging
  21. import sys
  22. if sys.version_info[0] >= 3:
  23. # strings are already parsed to unicode
  24. def unicode(s):
  25. return s
  26. logger = logging.getLogger(__name__)
  27. #################
  28. # Generate Code #
  29. #################
  30. def generateNodeIdPrintable(node):
  31. if isinstance(node.id, NodeId):
  32. CodePrintable = node.__class__.__name__ + "_" + str(node.id)
  33. else:
  34. CodePrintable = node.__class__.__name__ + "_unknown_nid"
  35. return re.sub('[^0-9a-z_]+', '_', CodePrintable.lower())
  36. def generateNodeValueInstanceName(node, parent, arrayIndex):
  37. return generateNodeIdPrintable(parent) + "_" + str(node.alias) + "_" + str(arrayIndex)
  38. def generateReferenceCode(reference):
  39. if reference.isForward:
  40. return "retVal |= UA_Server_addReference(server, %s, %s, %s, true);" % \
  41. (generateNodeIdCode(reference.source),
  42. generateNodeIdCode(reference.referenceType),
  43. generateExpandedNodeIdCode(reference.target))
  44. else:
  45. return "retVal |= UA_Server_addReference(server, %s, %s, %s, false);" % \
  46. (generateNodeIdCode(reference.source),
  47. generateNodeIdCode(reference.referenceType),
  48. generateExpandedNodeIdCode(reference.target))
  49. def generateReferenceTypeNodeCode(node):
  50. code = []
  51. code.append("UA_ReferenceTypeAttributes attr = UA_ReferenceTypeAttributes_default;")
  52. if node.isAbstract:
  53. code.append("attr.isAbstract = true;")
  54. if node.symmetric:
  55. code.append("attr.symmetric = true;")
  56. if node.inverseName != "":
  57. code.append("attr.inverseName = UA_LOCALIZEDTEXT(\"\", \"%s\");" % \
  58. node.inverseName)
  59. return code
  60. def generateObjectNodeCode(node):
  61. code = []
  62. code.append("UA_ObjectAttributes attr = UA_ObjectAttributes_default;")
  63. if node.eventNotifier:
  64. code.append("attr.eventNotifier = true;")
  65. return code
  66. def setNodeDatatypeRecursive(node, nodeset):
  67. if not isinstance(node, VariableNode) and not isinstance(node, VariableTypeNode):
  68. raise RuntimeError("Node {}: DataType can only be set for VariableNode and VariableTypeNode".format(str(node.id)))
  69. if node.dataType is not None:
  70. return
  71. # If BaseVariableType
  72. if node.id == NodeId("ns=0;i=62"):
  73. if node.dataType is None:
  74. # Set to default BaseDataType
  75. node.dataType = NodeId("ns=0;i=24")
  76. return
  77. if isinstance(node, VariableNode) and not isinstance(node, VariableTypeNode):
  78. typeDefNode = nodeset.getNodeTypeDefinition(node)
  79. if typeDefNode is None:
  80. # Use the parent type.
  81. raise RuntimeError("Cannot get node for HasTypeDefinition of VariableNode " + node.browseName.name + " " + str(node.id))
  82. setNodeDatatypeRecursive(typeDefNode, nodeset)
  83. node.dataType = typeDefNode.dataType
  84. else:
  85. # Use the parent type.
  86. if node.parent is None:
  87. raise RuntimeError("Parent node not defined for " + node.browseName.name + " " + str(node.id))
  88. setNodeDatatypeRecursive(node.parent, nodeset)
  89. node.dataType = node.parent.dataType
  90. def setNodeValueRankRecursive(node, nodeset):
  91. if not isinstance(node, VariableNode) and not isinstance(node, VariableTypeNode):
  92. raise RuntimeError("Node {}: ValueRank can only be set for VariableNode and VariableTypeNode".format(str(node.id)))
  93. if node.valueRank is not None:
  94. return
  95. # If BaseVariableType
  96. if node.id == NodeId("ns=0;i=62"):
  97. if node.valueRank is None:
  98. # BaseVariableType always has -2
  99. node.valueRank = -2
  100. return
  101. if isinstance(node, VariableNode) and not isinstance(node, VariableTypeNode):
  102. typeDefNode = nodeset.getNodeTypeDefinition(node)
  103. if typeDefNode is None:
  104. # Use the parent type.
  105. raise RuntimeError("Cannot get node for HasTypeDefinition of VariableNode " + node.browseName.name + " " + str(node.id))
  106. if not isinstance(typeDefNode, VariableTypeNode):
  107. raise RuntimeError("Node {} ({}) has an invalid type definition. {} is not a VariableType node.".format(
  108. str(node.id), node.browseName.name, str(typeDefNode.id)))
  109. setNodeValueRankRecursive(typeDefNode, nodeset)
  110. if typeDefNode.valueRank is not None and typeDefNode.valueRank > -1:
  111. node.valueRank = typeDefNode.valueRank
  112. else:
  113. # Default value
  114. node.valueRank = -1
  115. else:
  116. # Check if parent node limits the value rank
  117. setNodeValueRankRecursive(node.parent, nodeset)
  118. if node.parent.valueRank is not None and node.parent.valueRank > -1:
  119. node.valueRank = node.parent.valueRank
  120. else:
  121. # Default value
  122. node.valueRank = -1
  123. def generateCommonVariableCode(node, nodeset):
  124. code = []
  125. codeCleanup = []
  126. codeGlobal = []
  127. if node.valueRank is None:
  128. # Set the constrained value rank from the type/parent node
  129. setNodeValueRankRecursive(node, nodeset)
  130. code.append("/* Value rank inherited */")
  131. code.append("attr.valueRank = %d;" % node.valueRank)
  132. if node.valueRank > 0:
  133. code.append("attr.arrayDimensionsSize = %d;" % node.valueRank)
  134. code.append("UA_UInt32 arrayDimensions[{}];".format(node.valueRank))
  135. if len(node.arrayDimensions) == node.valueRank:
  136. for idx, v in enumerate(node.arrayDimensions):
  137. code.append("arrayDimensions[{}] = {};".format(idx, int(str(v))))
  138. else:
  139. for dim in range(0, node.valueRank):
  140. code.append("arrayDimensions[{}] = 0;".format(dim))
  141. code.append("attr.arrayDimensions = &arrayDimensions[0];")
  142. if node.dataType is None:
  143. # Inherit the datatype from the HasTypeDefinition reference, as stated in the OPC UA Spec:
  144. # 6.4.2
  145. # "Instances inherit the initial values for the Attributes that they have in common with the
  146. # TypeDefinitionNode from which they are instantiated, with the exceptions of the NodeClass and
  147. # NodeId."
  148. setNodeDatatypeRecursive(node, nodeset)
  149. code.append("/* DataType inherited */")
  150. dataTypeNode = nodeset.getBaseDataType(nodeset.getDataTypeNode(node.dataType))
  151. if dataTypeNode is None:
  152. raise RuntimeError("Cannot get BaseDataType for dataType : " + str(node.dataType) + " of node " + node.browseName.name + " " + str(node.id))
  153. code.append("attr.dataType = %s;" % generateNodeIdCode(node.dataType))
  154. if dataTypeNode.isEncodable():
  155. if node.value is not None:
  156. [code1, codeCleanup1, codeGlobal1] = generateValueCode(node.value, nodeset.nodes[node.id], nodeset)
  157. code += code1
  158. codeCleanup += codeCleanup1
  159. codeGlobal += codeGlobal1
  160. # #1978 Variant arrayDimensions are only required to properly decode multidimensional arrays
  161. # (valueRank > 1) from data stored as one-dimensional array of arrayLength elements.
  162. # One-dimensional arrays are already completely defined by arraylength attribute so setting
  163. # also arrayDimensions, even if not explicitly forbidden, can confuse clients
  164. if node.valueRank is not None and node.valueRank > 1 and len(node.arrayDimensions) == node.valueRank and len(node.value.value) > 0:
  165. numElements = 1
  166. hasZero = False
  167. for v in node.arrayDimensions:
  168. dim = int(unicode(v))
  169. if dim > 0:
  170. numElements = numElements * dim
  171. else:
  172. hasZero = True
  173. if hasZero == False and len(node.value.value) == numElements:
  174. code.append("attr.value.arrayDimensionsSize = attr.arrayDimensionsSize;")
  175. code.append("attr.value.arrayDimensions = attr.arrayDimensions;")
  176. elif node.value is not None:
  177. raise RuntimeError("Cannot encode dataTypeNode: " + dataTypeNode.browseName.name + " for value of node " + node.browseName.name + " " + str(node.id))
  178. return [code, codeCleanup, codeGlobal]
  179. def generateVariableNodeCode(node, nodeset):
  180. code = []
  181. codeCleanup = []
  182. codeGlobal = []
  183. code.append("UA_VariableAttributes attr = UA_VariableAttributes_default;")
  184. if node.historizing:
  185. code.append("attr.historizing = true;")
  186. code.append("attr.minimumSamplingInterval = %f;" % node.minimumSamplingInterval)
  187. code.append("attr.userAccessLevel = %d;" % node.userAccessLevel)
  188. code.append("attr.accessLevel = %d;" % node.accessLevel)
  189. # in order to be compatible with mostly OPC UA client
  190. # force valueRank = -1 for scalar VariableNode
  191. if node.valueRank == -2 and node.value is not None and len(node.value.value) == 1:
  192. node.valueRank = -1
  193. [code1, codeCleanup1, codeGlobal1] = generateCommonVariableCode(node, nodeset)
  194. code += code1
  195. codeCleanup += codeCleanup1
  196. codeGlobal += codeGlobal1
  197. return [code, codeCleanup, codeGlobal]
  198. def generateVariableTypeNodeCode(node, nodeset):
  199. code = []
  200. codeCleanup = []
  201. codeGlobal = []
  202. code.append("UA_VariableTypeAttributes attr = UA_VariableTypeAttributes_default;")
  203. if node.isAbstract:
  204. code.append("attr.isAbstract = true;")
  205. [code1, codeCleanup1, codeGlobal1] = generateCommonVariableCode(node, nodeset)
  206. code += code1
  207. codeCleanup += codeCleanup1
  208. codeGlobal += codeGlobal1
  209. return [code, codeCleanup, codeGlobal]
  210. def lowerFirstChar(inputString):
  211. return inputString[0].lower() + inputString[1:]
  212. def generateExtensionObjectSubtypeCode(node, parent, nodeset, global_var_code, instanceName=None, isArrayElement=False):
  213. code = [""]
  214. codeCleanup = [""]
  215. logger.debug("Building extensionObject for " + str(parent.id))
  216. logger.debug("Value " + str(node.value))
  217. logger.debug("Encoding " + str(node.encodingRule))
  218. typeBrowseNode = makeCIdentifier(nodeset.getDataTypeNode(parent.dataType).browseName.name)
  219. #TODO: review this
  220. if typeBrowseNode == "NumericRange":
  221. # in the stack we define a separate structure for the numeric range, but
  222. # the value itself is just a string
  223. typeBrowseNode = "String"
  224. typeString = "UA_" + typeBrowseNode
  225. if instanceName is None:
  226. instanceName = generateNodeValueInstanceName(node, parent, 0)
  227. code.append("UA_STACKARRAY(" + typeString + ", " + instanceName + ", 1);")
  228. typeArr = nodeset.getDataTypeNode(parent.dataType).typesArray
  229. typeString = nodeset.getDataTypeNode(parent.dataType).browseName.name.upper()
  230. typeArrayString = typeArr + "[" + typeArr + "_" + typeString + "]"
  231. code.append("UA_init({ref}{instanceName}, &{typeArrayString});".format(ref="&" if isArrayElement else "",
  232. instanceName=instanceName,
  233. typeArrayString=typeArrayString))
  234. # Assign data to the struct contents
  235. # Track the encoding rule definition to detect arrays and/or ExtensionObjects
  236. encFieldIdx = 0
  237. for subv in node.value:
  238. encField = node.encodingRule[encFieldIdx]
  239. encFieldIdx = encFieldIdx + 1
  240. memberName = lowerFirstChar(encField[0])
  241. # Check if this is an array
  242. accessor = "." if isArrayElement else "->"
  243. if isinstance(subv, list):
  244. if len(subv) == 0:
  245. continue
  246. logger.info("ExtensionObject contains array")
  247. memberName = lowerFirstChar(encField[0])
  248. encTypeString = "UA_" + subv[0].__class__.__name__
  249. instanceNameSafe = makeCIdentifier(instanceName)
  250. code.append("UA_STACKARRAY(" + encTypeString + ", " + instanceNameSafe + "_" + memberName+", {0});".format(len(subv)))
  251. encTypeArr = nodeset.getDataTypeNode(subv[0].__class__.__name__).typesArray
  252. encTypeArrayString = encTypeArr + "[" + encTypeArr + "_" + subv[0].__class__.__name__.upper() + "]"
  253. code.append("UA_init({instanceName}, &{typeArrayString});".format(
  254. instanceName=instanceNameSafe + "_" + memberName,
  255. typeArrayString=encTypeArrayString))
  256. subArrayIdx = 0
  257. for val in subv:
  258. code.append(generateNodeValueCode(instanceNameSafe + "_" + memberName + "[" + str(subArrayIdx) + "]" +" = ", val, instanceName,instanceName + "_gehtNed_member", global_var_code, asIndirect=False))
  259. subArrayIdx = subArrayIdx + 1
  260. code.append(instanceName + accessor + memberName + "Size = {0};".format(len(subv)))
  261. code.append(instanceName + accessor + memberName + " = " + instanceNameSafe+"_"+ memberName+";")
  262. continue
  263. else:
  264. logger.debug(
  265. "Encoding of field " + memberName + " is " + str(subv.encodingRule) + "defined by " + str(encField))
  266. if subv.valueRank is None or subv.valueRank == 0:
  267. if not subv.isNone():
  268. # Some values can be optional
  269. valueName = instanceName + accessor + memberName
  270. code.append(generateNodeValueCode(valueName + " = " ,
  271. subv, instanceName,valueName, global_var_code, asIndirect=False))
  272. else:
  273. memberName = lowerFirstChar(encField[0])
  274. code.append(generateNodeValueCode(instanceName + accessor + memberName + "Size = ", subv, instanceName,valueName, global_var_code, asIndirect=False))
  275. if not isArrayElement:
  276. code.append("UA_Variant_setScalar(&attr.value, " + instanceName + ", &" + typeArrayString + ");")
  277. return [code, codeCleanup]
  278. def getTypeBrowseName(dataTypeNode):
  279. typeBrowseName = makeCIdentifier(dataTypeNode.browseName.name)
  280. #TODO: review this
  281. if typeBrowseName == "NumericRange":
  282. # in the stack we define a separate structure for the numeric range, but
  283. # the value itself is just a string
  284. typeBrowseName = "String"
  285. return typeBrowseName
  286. def getTypesArrayForValue(nodeset, value):
  287. typeNode = nodeset.getNodeByBrowseName(value.__class__.__name__)
  288. if typeNode is None or value.isInternal:
  289. typesArray = "UA_TYPES"
  290. else:
  291. typesArray = typeNode.typesArray
  292. typeName = makeCIdentifier(value.__class__.__name__.upper())
  293. return "&" + typesArray + "[" + typesArray + "_" + typeName + "]"
  294. def isArrayVariableNode(node, parentNode):
  295. return parentNode.valueRank is not None and (parentNode.valueRank != -1 and (parentNode.valueRank >= 0
  296. or (len(node.value) > 1
  297. and (parentNode.valueRank != -2 or parentNode.valueRank != -3))))
  298. def generateValueCode(node, parentNode, nodeset, bootstrapping=True):
  299. code = []
  300. codeCleanup = []
  301. codeGlobal = []
  302. valueName = generateNodeIdPrintable(parentNode) + "_variant_DataContents"
  303. # node.value either contains a list of multiple identical BUILTINTYPES, or it
  304. # contains a single builtintype (which may be a container); choose if we need
  305. # to create an array or a single variable.
  306. # Note that some genious defined that there are arrays of size 1, which are
  307. # distinctly different then a single value, so we need to check that as well
  308. # Semantics:
  309. # -3: Scalar or 1-dim
  310. # -2: Scalar or x-dim | x>0
  311. # -1: Scalar
  312. # 0: x-dim | x>0
  313. # n: n-dim | n>0
  314. if (len(node.value) == 0):
  315. return ["", "", ""]
  316. if not isinstance(node.value[0], Value):
  317. return ["", "", ""]
  318. dataTypeNode = nodeset.getDataTypeNode(parentNode.dataType)
  319. if isArrayVariableNode(node, parentNode):
  320. # User the following strategy for all directly mappable values a la 'UA_Type MyInt = (UA_Type) 23;'
  321. if isinstance(node.value[0], Guid):
  322. logger.warn("Don't know how to print array of GUID in node " + str(parentNode.id))
  323. elif isinstance(node.value[0], DiagnosticInfo):
  324. logger.warn("Don't know how to print array of DiagnosticInfo in node " + str(parentNode.id))
  325. elif isinstance(node.value[0], StatusCode):
  326. logger.warn("Don't know how to print array of StatusCode in node " + str(parentNode.id))
  327. else:
  328. if isinstance(node.value[0], ExtensionObject):
  329. code.append("UA_" + getTypeBrowseName(dataTypeNode) + " " + valueName + "[" + str(len(node.value)) + "];")
  330. for idx, v in enumerate(node.value):
  331. logger.debug("Building extObj array index " + str(idx))
  332. instanceName = valueName + "[" + str(idx) + "]"
  333. [code1, codeCleanup1] = generateExtensionObjectSubtypeCode(v, parent=parentNode, nodeset=nodeset,
  334. global_var_code=codeGlobal, instanceName=instanceName,
  335. isArrayElement=True)
  336. code = code + code1
  337. codeCleanup = codeCleanup + codeCleanup1
  338. else:
  339. code.append("UA_" + node.value[0].__class__.__name__ + " " + valueName + "[" + str(len(node.value)) + "];")
  340. for idx, v in enumerate(node.value):
  341. instanceName = generateNodeValueInstanceName(v, parentNode, idx)
  342. code.append(generateNodeValueCode(
  343. valueName + "[" + str(idx) + "] = " , v, instanceName, valueName, codeGlobal))
  344. code.append("UA_Variant_setArray(&attr.value, &" + valueName +
  345. ", (UA_Int32) " + str(len(node.value)) + ", " + "&" +
  346. dataTypeNode.typesArray + "["+dataTypeNode.typesArray + "_" + getTypeBrowseName(dataTypeNode).upper() +"]);")
  347. #scalar value
  348. else:
  349. # User the following strategy for all directly mappable values a la 'UA_Type MyInt = (UA_Type) 23;'
  350. if isinstance(node.value[0], Guid):
  351. logger.warn("Don't know how to print scalar GUID in node " + str(parentNode.id))
  352. elif isinstance(node.value[0], DiagnosticInfo):
  353. logger.warn("Don't know how to print scalar DiagnosticInfo in node " + str(parentNode.id))
  354. elif isinstance(node.value[0], StatusCode):
  355. logger.warn("Don't know how to print scalar StatusCode in node " + str(parentNode.id))
  356. else:
  357. # The following strategy applies to all other types, in particular strings and numerics.
  358. if isinstance(node.value[0], ExtensionObject):
  359. [code1, codeCleanup1] = generateExtensionObjectSubtypeCode(node.value[0], parent=parentNode, nodeset=nodeset, global_var_code=codeGlobal, isArrayElement=False)
  360. code = code + code1
  361. codeCleanup = codeCleanup + codeCleanup1
  362. instanceName = generateNodeValueInstanceName(node.value[0], parentNode, 0)
  363. if not node.value[0].isNone() and not(isinstance(node.value[0], ExtensionObject)):
  364. code.append("UA_" + node.value[0].__class__.__name__ + " *" + valueName + " = UA_" + node.value[
  365. 0].__class__.__name__ + "_new();")
  366. code.append("if (!" + valueName + ") return UA_STATUSCODE_BADOUTOFMEMORY;")
  367. code.append("UA_" + node.value[0].__class__.__name__ + "_init(" + valueName + ");")
  368. code.append(generateNodeValueCode("*" + valueName + " = " , node.value[0], instanceName, valueName, codeGlobal, asIndirect=True))
  369. code.append(
  370. "UA_Variant_setScalar(&attr.value, " + valueName + ", " +
  371. getTypesArrayForValue(nodeset, node.value[0]) + ");")
  372. if node.value[0].__class__.__name__ == "ByteString":
  373. # The data is on the stack, not heap, so we can not delete the ByteString
  374. codeCleanup.append("{}->data = NULL;".format(valueName))
  375. codeCleanup.append("{}->length = 0;".format(valueName))
  376. codeCleanup.append("UA_{0}_delete({1});".format(
  377. node.value[0].__class__.__name__, valueName))
  378. return [code, codeCleanup, codeGlobal]
  379. def generateMethodNodeCode(node):
  380. code = []
  381. code.append("UA_MethodAttributes attr = UA_MethodAttributes_default;")
  382. if node.executable:
  383. code.append("attr.executable = true;")
  384. if node.userExecutable:
  385. code.append("attr.userExecutable = true;")
  386. return code
  387. def generateObjectTypeNodeCode(node):
  388. code = []
  389. code.append("UA_ObjectTypeAttributes attr = UA_ObjectTypeAttributes_default;")
  390. if node.isAbstract:
  391. code.append("attr.isAbstract = true;")
  392. return code
  393. def generateDataTypeNodeCode(node):
  394. code = []
  395. code.append("UA_DataTypeAttributes attr = UA_DataTypeAttributes_default;")
  396. if node.isAbstract:
  397. code.append("attr.isAbstract = true;")
  398. return code
  399. def generateViewNodeCode(node):
  400. code = []
  401. code.append("UA_ViewAttributes attr = UA_ViewAttributes_default;")
  402. if node.containsNoLoops:
  403. code.append("attr.containsNoLoops = true;")
  404. code.append("attr.eventNotifier = (UA_Byte)%s;" % str(node.eventNotifier))
  405. return code
  406. def generateSubtypeOfDefinitionCode(node):
  407. for ref in node.inverseReferences:
  408. # 45 = HasSubtype
  409. if ref.referenceType.i == 45:
  410. return generateNodeIdCode(ref.target)
  411. return "UA_NODEID_NULL"
  412. def generateNodeCode_begin(node, nodeset, code_global):
  413. code = []
  414. codeCleanup = []
  415. code.append("UA_StatusCode retVal = UA_STATUSCODE_GOOD;")
  416. # Attributes
  417. if isinstance(node, ReferenceTypeNode):
  418. code.extend(generateReferenceTypeNodeCode(node))
  419. elif isinstance(node, ObjectNode):
  420. code.extend(generateObjectNodeCode(node))
  421. elif isinstance(node, VariableNode) and not isinstance(node, VariableTypeNode):
  422. [code1, codeCleanup1, codeGlobal1] = generateVariableNodeCode(node, nodeset)
  423. code.extend(code1)
  424. codeCleanup.extend(codeCleanup1)
  425. code_global.extend(codeGlobal1)
  426. elif isinstance(node, VariableTypeNode):
  427. [code1, codeCleanup1, codeGlobal1] = generateVariableTypeNodeCode(node, nodeset)
  428. code.extend(code1)
  429. codeCleanup.extend(codeCleanup1)
  430. code_global.extend(codeGlobal1)
  431. elif isinstance(node, MethodNode):
  432. code.extend(generateMethodNodeCode(node))
  433. elif isinstance(node, ObjectTypeNode):
  434. code.extend(generateObjectTypeNodeCode(node))
  435. elif isinstance(node, DataTypeNode):
  436. code.extend(generateDataTypeNodeCode(node))
  437. elif isinstance(node, ViewNode):
  438. code.extend(generateViewNodeCode(node))
  439. if node.displayName is not None:
  440. code.append("attr.displayName = " + generateLocalizedTextCode(node.displayName, alloc=False) + ";")
  441. if node.description is not None:
  442. code.append("#ifdef UA_ENABLE_NODESET_COMPILER_DESCRIPTIONS")
  443. code.append("attr.description = " + generateLocalizedTextCode(node.description, alloc=False) + ";")
  444. code.append("#endif")
  445. if node.writeMask is not None:
  446. code.append("attr.writeMask = %d;" % node.writeMask)
  447. if node.userWriteMask is not None:
  448. code.append("attr.userWriteMask = %d;" % node.userWriteMask)
  449. # AddNodes call
  450. code.append("retVal |= UA_Server_addNode_begin(server, UA_NODECLASS_{},".
  451. format(makeCIdentifier(node.__class__.__name__.upper().replace("NODE" ,""))))
  452. code.append(generateNodeIdCode(node.id) + ",")
  453. code.append(generateNodeIdCode(node.parent.id if node.parent else NodeId()) + ",")
  454. code.append(generateNodeIdCode(node.parentReference.id if node.parent else NodeId()) + ",")
  455. code.append(generateQualifiedNameCode(node.browseName) + ",")
  456. if isinstance(node, VariableNode) or isinstance(node, ObjectNode):
  457. typeDefRef = node.popTypeDef()
  458. code.append(generateNodeIdCode(typeDefRef.target) + ",")
  459. else:
  460. code.append(" UA_NODEID_NULL,")
  461. code.append("(const UA_NodeAttributes*)&attr, &UA_TYPES[UA_TYPES_{}ATTRIBUTES],NULL, NULL);".
  462. format(makeCIdentifier(node.__class__.__name__.upper().replace("NODE" ,""))))
  463. code.extend(codeCleanup)
  464. return "\n".join(code)
  465. def generateNodeCode_finish(node):
  466. code = []
  467. if isinstance(node, MethodNode):
  468. code.append("UA_Server_addMethodNode_finish(server, ")
  469. else:
  470. code.append("UA_Server_addNode_finish(server, ")
  471. code.append(generateNodeIdCode(node.id))
  472. if isinstance(node, MethodNode):
  473. code.append(", NULL, 0, NULL, 0, NULL);")
  474. else:
  475. code.append(");")
  476. return "\n".join(code)