nodeset.py 12 KB

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