nodeset.py 13 KB

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