nodeset.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  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 __future__ import print_function
  18. import sys
  19. import xml.dom.minidom as dom
  20. from struct import pack as structpack
  21. from time import struct_time, strftime, strptime, mktime
  22. import logging;
  23. logger = logging.getLogger(__name__)
  24. from nodes import *
  25. from opaque_type_mapping import opaque_type_mapping
  26. import codecs
  27. ####################
  28. # Helper Functions #
  29. ####################
  30. hassubtype = NodeId("ns=0;i=45")
  31. def getSubTypesOf(nodeset, node, skipNodes=[]):
  32. if node in skipNodes:
  33. return []
  34. re = [node]
  35. for ref in node.references:
  36. if ref.referenceType == hassubtype and ref.isForward:
  37. re = re + getSubTypesOf(nodeset, nodeset.nodes[ref.target], skipNodes=skipNodes)
  38. return re
  39. def extractNamespaces(xmlfile):
  40. # Extract a list of namespaces used. The first namespace is always
  41. # "http://opcfoundation.org/UA/". minidom gobbles up
  42. # <NamespaceUris></NamespaceUris> elements, without a decent way to reliably
  43. # access this dom2 <uri></uri> elements (only attribute xmlns= are accessible
  44. # using minidom). We need them for dereferencing though... This function
  45. # attempts to do just that.
  46. namespaces = ["http://opcfoundation.org/UA/"]
  47. infile = open(xmlfile.name)
  48. foundURIs = False
  49. nsline = ""
  50. line = infile.readline()
  51. for line in infile:
  52. if "<namespaceuris>" in line.lower():
  53. foundURIs = True
  54. elif "</namespaceuris>" in line.lower():
  55. foundURIs = False
  56. nsline = nsline + line
  57. break
  58. if foundURIs:
  59. nsline = nsline + line
  60. if len(nsline) > 0:
  61. ns = dom.parseString(nsline).getElementsByTagName("NamespaceUris")
  62. for uri in ns[0].childNodes:
  63. if uri.nodeType != uri.ELEMENT_NODE:
  64. continue
  65. if uri.firstChild.data in namespaces:
  66. continue
  67. namespaces.append(uri.firstChild.data)
  68. infile.close()
  69. return namespaces
  70. def buildAliasList(xmlelement):
  71. """Parses the <Alias> XML Element present in must XML NodeSet definitions.
  72. Contents the Alias element are stored in a dictionary for further
  73. dereferencing during pointer linkage (see linkOpenPointer())."""
  74. aliases = {}
  75. for al in xmlelement.childNodes:
  76. if al.nodeType == al.ELEMENT_NODE:
  77. if al.hasAttribute("Alias"):
  78. aliasst = al.getAttribute("Alias")
  79. aliasnd = unicode(al.firstChild.data)
  80. aliases[aliasst] = aliasnd
  81. return aliases
  82. class NodeSet(object):
  83. """ This class handles parsing XML description of namespaces, instantiating
  84. nodes, linking references, graphing the namespace and compiling a binary
  85. representation.
  86. Note that nodes assigned to this class are not restricted to having a
  87. single namespace ID. This class represents the entire physical address
  88. space of the binary representation and all nodes that are to be included
  89. in that segment of memory.
  90. """
  91. def __init__(self):
  92. self.nodes = {}
  93. self.aliases = {}
  94. self.namespaces = ["http://opcfoundation.org/UA/"]
  95. def sanitize(self):
  96. for n in self.nodes.values():
  97. if n.sanitize() == False:
  98. raise Exception("Failed to sanitize node " + str(n))
  99. # Sanitize reference consistency
  100. for n in self.nodes.values():
  101. for ref in n.references:
  102. if not ref.source == n.id:
  103. raise Exception("Reference " + str(ref) + " has an invalid source")
  104. if not ref.referenceType in self.nodes:
  105. raise Exception("Reference " + str(ref) + " has an unknown reference type")
  106. if not ref.target in self.nodes:
  107. raise Exception("Reference " + str(ref) + " has an unknown target")
  108. def addNamespace(self, nsURL):
  109. if not nsURL in self.namespaces:
  110. self.namespaces.append(nsURL)
  111. def createNamespaceMapping(self, orig_namespaces):
  112. """Creates a dict that maps from the nsindex in the original nodeset to the
  113. nsindex in the combined nodeset"""
  114. m = {}
  115. for index, name in enumerate(orig_namespaces):
  116. m[index] = self.namespaces.index(name)
  117. return m
  118. def getNodeByBrowseName(self, idstring):
  119. return next((n for n in self.nodes.values() if idstring == n.browseName.name), None)
  120. def getNodeById(self, namespace, id):
  121. nodeId = NodeId()
  122. nodeId.ns = namespace
  123. nodeId.i = id
  124. return self.nodes[nodeId]
  125. def getRoot(self):
  126. return self.getNodeByBrowseName("Root")
  127. def createNode(self, xmlelement, nsMapping, hidden=False):
  128. ndtype = xmlelement.localName.lower()
  129. if ndtype[:2] == "ua":
  130. ndtype = ndtype[2:]
  131. node = None
  132. if ndtype == 'variable':
  133. node = VariableNode(xmlelement)
  134. if ndtype == 'object':
  135. node = ObjectNode(xmlelement)
  136. if ndtype == 'method':
  137. node = MethodNode(xmlelement)
  138. if ndtype == 'objecttype':
  139. node = ObjectTypeNode(xmlelement)
  140. if ndtype == 'variabletype':
  141. node = VariableTypeNode(xmlelement)
  142. if ndtype == 'methodtype':
  143. node = MethodNode(xmlelement)
  144. if ndtype == 'datatype':
  145. node = DataTypeNode(xmlelement)
  146. if ndtype == 'referencetype':
  147. node = ReferenceTypeNode(xmlelement)
  148. if node and hidden:
  149. node.hidden = True
  150. # References from an existing nodeset are all suppressed
  151. for ref in node.references:
  152. ref.hidden = True
  153. for ref in node.inverseReferences:
  154. ref.hidden = True
  155. return node
  156. def hide_node(self, nodeId, hidden=True):
  157. if not nodeId in self.nodes:
  158. return False
  159. node = self.nodes[nodeId]
  160. node.hidden = hidden
  161. # References from an existing nodeset are all suppressed
  162. for ref in node.references:
  163. ref.hidden = hidden
  164. for ref in node.inverseReferences:
  165. ref.hidden = hidden
  166. return True
  167. def merge_dicts(self, *dict_args):
  168. """
  169. Given any number of dicts, shallow copy and merge into a new dict,
  170. precedence goes to key value pairs in latter dicts.
  171. """
  172. result = {}
  173. for dictionary in dict_args:
  174. result.update(dictionary)
  175. return result
  176. def addNodeSet(self, xmlfile, hidden=False, typesArray="UA_TYPES"):
  177. # Extract NodeSet DOM
  178. fileContent = xmlfile.read()
  179. # Remove BOM since the dom parser cannot handle it on python 3 windows
  180. if fileContent.startswith( codecs.BOM_UTF8 ):
  181. fileContent = fileContent.lstrip( codecs.BOM_UTF8 )
  182. nodesets = dom.parseString(fileContent).getElementsByTagName("UANodeSet")
  183. if len(nodesets) == 0 or len(nodesets) > 1:
  184. raise Exception(self, self.originXML + " contains no or more then 1 nodeset")
  185. nodeset = nodesets[0]
  186. # Create the namespace mapping
  187. orig_namespaces = extractNamespaces(xmlfile) # List of namespaces used in the xml file
  188. for ns in orig_namespaces:
  189. self.addNamespace(ns)
  190. nsMapping = self.createNamespaceMapping(orig_namespaces)
  191. # Extract the aliases
  192. for nd in nodeset.childNodes:
  193. if nd.nodeType != nd.ELEMENT_NODE:
  194. continue
  195. ndtype = nd.localName.lower()
  196. if 'aliases' in ndtype:
  197. self.aliases = self.merge_dicts(self.aliases, buildAliasList(nd))
  198. # Instantiate nodes
  199. newnodes = []
  200. for nd in nodeset.childNodes:
  201. if nd.nodeType != nd.ELEMENT_NODE:
  202. continue
  203. node = self.createNode(nd, nsMapping, hidden)
  204. if not node:
  205. continue
  206. node.replaceAliases(self.aliases)
  207. node.replaceNamespaces(nsMapping)
  208. node.typesArray = typesArray
  209. # Add the node the the global dict
  210. if node.id in self.nodes:
  211. raise Exception("XMLElement with duplicate ID " + str(node.id))
  212. self.nodes[node.id] = node
  213. newnodes.append(node)
  214. # add inverse references
  215. for node in newnodes:
  216. for ref in node.references:
  217. newsource = self.nodes[ref.target]
  218. hide = ref.hidden or (node.hidden and newsource.hidden)
  219. newref = Reference(newsource.id, ref.referenceType, ref.source, False, hide, inferred=True)
  220. newsource.inverseReferences.add(newref)
  221. for ref in node.inverseReferences:
  222. newsource = self.nodes[ref.target]
  223. hide = ref.hidden or (node.hidden and newsource.hidden)
  224. newref = Reference(newsource.id, ref.referenceType, ref.source, True, hide, inferred=True)
  225. newsource.references.add(newref)
  226. def getBinaryEncodingIdForNode(self, nodeId):
  227. """
  228. The node should have a 'HasEncoding' forward reference which points to the encoding ids.
  229. These can be XML Encoding or Binary Encoding. Therefore we also need to check if the SymbolicName
  230. of the target node is "DefaultBinary"
  231. """
  232. node = self.nodes[nodeId]
  233. refId = NodeId()
  234. for ref in node.references:
  235. if ref.referenceType.ns == 0 and ref.referenceType.i == 38:
  236. refNode = self.nodes[ref.target]
  237. if refNode.symbolicName.value == "DefaultBinary":
  238. return ref.target
  239. raise Exception("No DefaultBinary encoding defined for node " + str(nodeId))
  240. def buildEncodingRules(self):
  241. """ Calls buildEncoding() for all DataType nodes (opcua_node_dataType_t).
  242. No return value
  243. """
  244. stat = {True: 0, False: 0}
  245. for n in self.nodes.values():
  246. if isinstance(n, DataTypeNode):
  247. n.buildEncoding(self)
  248. stat[n.isEncodable()] = stat[n.isEncodable()] + 1
  249. logger.debug("Type definitions built/passed: " + str(stat))
  250. def allocateVariables(self):
  251. for n in self.nodes.values():
  252. if isinstance(n, VariableNode):
  253. n.allocateValue(self)
  254. def getBaseDataType(self, node):
  255. if node is None:
  256. return None
  257. if node.browseName.name not in opaque_type_mapping:
  258. return node
  259. for ref in node.inverseReferences:
  260. if ref.referenceType.i == 45:
  261. return self.getBaseDataType(self.nodes[ref.target])
  262. return node
  263. def getDataTypeNode(self, dataType):
  264. if isinstance(dataType, six.string_types):
  265. if not valueIsInternalType(dataType):
  266. logger.error("Not a valid dataType string: " + dataType)
  267. return None
  268. return self.nodes[NodeId(self.aliases[dataType])]
  269. if isinstance(dataType, NodeId):
  270. if dataType.i == 0:
  271. return None
  272. dataTypeNode = self.nodes[dataType]
  273. if not isinstance(dataTypeNode, DataTypeNode):
  274. logger.error("Node id " + str(dataType) + " is not reference a valid dataType.")
  275. return None
  276. if not dataTypeNode.isEncodable():
  277. logger.warn("DataType " + str(dataTypeNode.browseName) + " is not encodable.")
  278. return dataTypeNode
  279. return None
  280. def getRelevantOrderingReferences(self):
  281. relevant_types = getSubTypesOf(self,
  282. self.getNodeByBrowseName("HierarchicalReferences"),
  283. [])
  284. relevant_types += getSubTypesOf(self,
  285. self.getNodeByBrowseName("HasEncoding"),
  286. [])
  287. relevant_types = map(lambda x: x.id, relevant_types)
  288. return list(relevant_types)