ua_namespace.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795
  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. from time import struct_time, strftime, strptime, mktime
  20. from struct import pack as structpack
  21. from logger import *;
  22. from ua_builtin_types import *;
  23. from ua_node_types import *;
  24. from ua_constants import *;
  25. from open62541_MacroHelper import open62541_MacroHelper
  26. def getNextElementNode(xmlvalue):
  27. if xmlvalue == None:
  28. return None
  29. xmlvalue = xmlvalue.nextSibling
  30. while not xmlvalue == None and not xmlvalue.nodeType == xmlvalue.ELEMENT_NODE:
  31. xmlvalue = xmlvalue.nextSibling
  32. return xmlvalue
  33. ###
  34. ### Namespace Organizer
  35. ###
  36. class opcua_namespace():
  37. """ Class holding and managing a set of OPCUA nodes.
  38. This class handles parsing XML description of namespaces, instantiating
  39. nodes, linking references, graphing the namespace and compiling a binary
  40. representation.
  41. Note that nodes assigned to this class are not restricted to having a
  42. single namespace ID. This class represents the entire physical address
  43. space of the binary representation and all nodes that are to be included
  44. in that segment of memory.
  45. """
  46. nodes = []
  47. nodeids = {}
  48. aliases = {}
  49. __linkLater__ = []
  50. __binaryIndirectPointers__ = []
  51. name = ""
  52. knownNodeTypes = ""
  53. def __init__(self, name):
  54. self.nodes = []
  55. self.knownNodeTypes = ['variable', 'object', 'method', 'referencetype', \
  56. 'objecttype', 'variabletype', 'methodtype', \
  57. 'datatype', 'referencetype', 'aliases']
  58. self.name = name
  59. self.nodeids = {}
  60. self.aliases = {}
  61. self.__binaryIndirectPointers__ = []
  62. def linkLater(self, pointer):
  63. """ Called by nodes or references who have parsed an XML reference to a
  64. node represented by a string.
  65. No return value
  66. XML String representations of references have the form 'i=xy' or
  67. 'ns=1;s="This unique Node"'. Since during the parsing of this attribute
  68. only a subset of nodes are known/parsed, this reference string cannot be
  69. linked when encountered.
  70. References register themselves with the namespace to have their target
  71. attribute (string) parsed by linkOpenPointers() when all nodes are
  72. created, so that target can be dereferenced an point to an actual node.
  73. """
  74. self.__linkLater__.append(pointer)
  75. def getUnlinkedPointers(self):
  76. """ Return the list of references registered for linking during the next call
  77. of linkOpenPointers()
  78. """
  79. return self.__linkLater__
  80. def unlinkedItemCount(self):
  81. """ Returns the number of unlinked references that will be processed during
  82. the next call of linkOpenPointers()
  83. """
  84. return len(self.__linkLater__)
  85. def buildAliasList(self, xmlelement):
  86. """ Parses the <Alias> XML Element present in must XML NodeSet definitions.
  87. No return value
  88. Contents the Alias element are stored in a dictionary for further
  89. dereferencing during pointer linkage (see linkOpenPointer()).
  90. """
  91. if not xmlelement.tagName == "Aliases":
  92. log(self, "XMLElement passed is not an Aliaslist", LOG_LEVEL_ERROR)
  93. return
  94. for al in xmlelement.childNodes:
  95. if al.nodeType == al.ELEMENT_NODE:
  96. if al.hasAttribute("Alias"):
  97. aliasst = al.getAttribute("Alias")
  98. if sys.version_info[0] < 3:
  99. aliasnd = unicode(al.firstChild.data)
  100. else:
  101. aliasnd = al.firstChild.data
  102. if not aliasst in self.aliases:
  103. self.aliases[aliasst] = aliasnd
  104. log(self, "Added new alias \"" + str(aliasst) + "\" == \"" + str(aliasnd) + "\"")
  105. else:
  106. if self.aliases[aliasst] != aliasnd:
  107. log(self, "Alias definitions for " + aliasst + " differ. Have " + self.aliases[aliasst] + " but XML defines " + aliasnd + ". Keeping current definition.", LOG_LEVEL_ERROR)
  108. def getNodeByBrowseName(self, idstring):
  109. """ Returns the first node in the nodelist whose browseName matches idstring.
  110. """
  111. matches = []
  112. for n in self.nodes:
  113. if idstring==str(n.browseName()):
  114. matches.append(n)
  115. if len(matches) > 1:
  116. log(self, "Found multiple nodes with same ID!?", LOG_LEVEL_ERROR)
  117. if len(matches) == 0:
  118. return None
  119. else:
  120. return matches[0]
  121. def getNodeByIDString(self, idstring):
  122. """ Returns the first node in the nodelist whose id string representation
  123. matches idstring.
  124. """
  125. matches = []
  126. for n in self.nodes:
  127. if idstring==str(n.id()):
  128. matches.append(n)
  129. if len(matches) > 1:
  130. log(self, "Found multiple nodes with same ID!?", LOG_LEVEL_ERROR)
  131. if len(matches) == 0:
  132. return None
  133. else:
  134. return matches[0]
  135. def createNode(self, ndtype, xmlelement):
  136. """ createNode is instantiates a node described by xmlelement, its type being
  137. defined by the string ndtype.
  138. No return value
  139. If the xmlelement is an <Alias>, the contents will be parsed and stored
  140. for later dereferencing during pointer linking (see linkOpenPointers).
  141. Recognized types are:
  142. * UAVariable
  143. * UAObject
  144. * UAMethod
  145. * UAView
  146. * UAVariableType
  147. * UAObjectType
  148. * UAMethodType
  149. * UAReferenceType
  150. * UADataType
  151. For every recognized type, an appropriate node class is added to the node
  152. list of the namespace. The NodeId of the given node is created and parsing
  153. of the node attributes and elements is delegated to the parseXML() and
  154. parseXMLSubType() functions of the instantiated class.
  155. If the NodeID attribute is non-unique in the node list, the creation is
  156. deferred and an error is logged.
  157. """
  158. if not isinstance(xmlelement, dom.Element):
  159. log(self, "Error: Can not create node from invalid XMLElement", LOG_LEVEL_ERROR)
  160. return
  161. # An ID is manditory for everything but aliases!
  162. id = None
  163. for idname in ['NodeId', 'NodeID', 'nodeid']:
  164. if xmlelement.hasAttribute(idname):
  165. id = xmlelement.getAttribute(idname)
  166. if ndtype == 'aliases':
  167. self.buildAliasList(xmlelement)
  168. return
  169. elif id == None:
  170. log(self, "Error: XMLElement has no id, node will not be created!", LOG_LEVEL_INFO)
  171. return
  172. else:
  173. id = opcua_node_id_t(id)
  174. if str(id) in self.nodeids:
  175. # Normal behavior: Do not allow duplicates, first one wins
  176. #log(self, "XMLElement with duplicate ID " + str(id) + " found, node will not be created!", LOG_LEVEL_ERROR)
  177. #return
  178. # Open62541 behavior for header generation: Replace the duplicate with the new node
  179. log(self, "XMLElement with duplicate ID " + str(id) + " found, node will be replaced!", LOG_LEVEL_INFO)
  180. nd = self.getNodeByIDString(str(id))
  181. self.nodes.remove(nd)
  182. self.nodeids.pop(str(nd.id()))
  183. node = None
  184. if (ndtype == 'variable'):
  185. node = opcua_node_variable_t(id, self)
  186. elif (ndtype == 'object'):
  187. node = opcua_node_object_t(id, self)
  188. elif (ndtype == 'method'):
  189. node = opcua_node_method_t(id, self)
  190. elif (ndtype == 'objecttype'):
  191. node = opcua_node_objectType_t(id, self)
  192. elif (ndtype == 'variabletype'):
  193. node = opcua_node_variableType_t(id, self)
  194. elif (ndtype == 'methodtype'):
  195. node = opcua_node_methodType_t(id, self)
  196. elif (ndtype == 'datatype'):
  197. node = opcua_node_dataType_t(id, self)
  198. elif (ndtype == 'referencetype'):
  199. node = opcua_node_referenceType_t(id, self)
  200. else:
  201. log(self, "No node constructor for type " + ndtype, LOG_LEVEL_ERROR)
  202. if node != None:
  203. node.parseXML(xmlelement)
  204. self.nodes.append(node)
  205. self.nodeids[str(node.id())] = node
  206. def removeNodeById(self, nodeId):
  207. nd = self.getNodeByIDString(nodeId)
  208. if nd == None:
  209. return False
  210. log(self, "Removing nodeId " + str(nodeId), LOG_LEVEL_DEBUG)
  211. self.nodes.remove(nd)
  212. if nd.getInverseReferences() != None:
  213. for ref in nd.getInverseReferences():
  214. src = ref.target();
  215. src.removeReferenceToNode(nd)
  216. return True
  217. def registerBinaryIndirectPointer(self, node):
  218. """ Appends a node to the list of nodes that should be contained in the
  219. first 765 bytes (255 pointer slots a 3 bytes) in the binary
  220. representation (indirect referencing space).
  221. This function is reserved for references and dataType pointers.
  222. """
  223. if not node in self.__binaryIndirectPointers__:
  224. self.__binaryIndirectPointers__.append(node)
  225. return self.__binaryIndirectPointers__.index(node)
  226. def getBinaryIndirectPointerIndex(self, node):
  227. """ Returns the slot/index of a pointer in the indirect referencing space
  228. (first 765 Bytes) of the binary representation.
  229. """
  230. if not node in self.__binaryIndirectPointers__:
  231. return -1
  232. return self.__binaryIndirectPointers__.index(node)
  233. def parseXML(self, xmldoc):
  234. """ Reads an XML Namespace definition and instantiates node.
  235. No return value
  236. parseXML open the file xmldoc using xml.dom.minidom and searches for
  237. the first UANodeSet Element. For every Element encountered, createNode
  238. is called to instantiate a node of the appropriate type.
  239. """
  240. typedict = {}
  241. UANodeSet = dom.parse(xmldoc).getElementsByTagName("UANodeSet")
  242. if len(UANodeSet) == 0:
  243. log(self, "Error: No NodeSets found", LOG_LEVEL_ERROR)
  244. return
  245. if len(UANodeSet) != 1:
  246. log(self, "Error: Found more than 1 Nodeset in XML File", LOG_LEVEL_ERROR)
  247. UANodeSet = UANodeSet[0]
  248. for nd in UANodeSet.childNodes:
  249. if nd.nodeType != nd.ELEMENT_NODE:
  250. continue
  251. ndType = nd.tagName.lower()
  252. if ndType[:2] == "ua":
  253. ndType = ndType[2:]
  254. elif not ndType in self.knownNodeTypes:
  255. log(self, "XML Element or NodeType " + ndType + " is unknown and will be ignored", LOG_LEVEL_WARN)
  256. continue
  257. if not ndType in typedict:
  258. typedict[ndType] = 1
  259. else:
  260. typedict[ndType] = typedict[ndType] + 1
  261. self.createNode(ndType, nd)
  262. log(self, "Currently " + str(len(self.nodes)) + " nodes in address space. Type distribution for this run was: " + str(typedict))
  263. def linkOpenPointers(self):
  264. """ Substitutes symbolic NodeIds in references for actual node instances.
  265. No return value
  266. References that have registered themselves with linkLater() to have
  267. their symbolic NodeId targets ("ns=2; i=32") substited for an actual
  268. node will be iterated by this function. For each reference encountered
  269. in the list of unlinked/open references, the target string will be
  270. evaluated and searched for in the node list of this namespace. If found,
  271. the target attribute of the reference will be substituted for the
  272. found node.
  273. If a reference fails to get linked, it will remain in the list of
  274. unlinked references. The individual items in this list can be
  275. retrieved using getUnlinkedPointers().
  276. """
  277. linked = []
  278. log(self, str(self.unlinkedItemCount()) + " pointers need to get linked.")
  279. for l in self.__linkLater__:
  280. targetLinked = False
  281. if not l.target() == None and not isinstance(l.target(), opcua_node_t):
  282. if isinstance(l.target(),str) or isinstance(l.target(),unicode):
  283. # If is not a node ID, it should be an alias. Try replacing it
  284. # with a proper node ID
  285. if l.target() in self.aliases:
  286. l.target(self.aliases[l.target()])
  287. # If the link is a node ID, try to find it hopening that no ass has
  288. # defined more than one kind of id for that sucker
  289. if l.target()[:2] == "i=" or l.target()[:2] == "g=" or \
  290. l.target()[:2] == "b=" or l.target()[:2] == "s=" or \
  291. l.target()[:3] == "ns=" :
  292. tgt = self.getNodeByIDString(str(l.target()))
  293. if tgt == None:
  294. log(self, "Failed to link pointer to target (node not found) " + l.target(), LOG_LEVEL_ERROR)
  295. else:
  296. l.target(tgt)
  297. targetLinked = True
  298. else:
  299. log(self, "Failed to link pointer to target (target not Alias or Node) " + l.target(), LOG_LEVEL_ERROR)
  300. else:
  301. log(self, "Failed to link pointer to target (don't know dummy type + " + str(type(l.target())) + " +) " + str(l.target()), LOG_LEVEL_ERROR)
  302. else:
  303. log(self, "Pointer has null target: " + str(l), LOG_LEVEL_ERROR)
  304. referenceLinked = False
  305. if not l.referenceType() == None:
  306. if l.referenceType() in self.aliases:
  307. l.referenceType(self.aliases[l.referenceType()])
  308. if l.referenceType()[:2] == "i=" or l.referenceType()[:2] == "g=" or \
  309. l.referenceType()[:2] == "b=" or l.referenceType()[:2] == "s=":
  310. tgt = self.getNodeByIDString(str(l.referenceType()))
  311. if tgt == None:
  312. log(self, "Failed to link reference type to target (node not found) " + l.referenceType(), LOG_LEVEL_ERROR)
  313. else:
  314. l.referenceType(tgt)
  315. referenceLinked = True
  316. else:
  317. referenceLinked = True
  318. if referenceLinked == True and targetLinked == True:
  319. linked.append(l)
  320. # References marked as "not forward" must be inverted (removed from source node, assigned to target node and relinked)
  321. log(self, "Inverting reference direction for all references with isForward==False attribute (is this correct!?)", LOG_LEVEL_WARN)
  322. for n in self.nodes:
  323. for r in n.getReferences():
  324. if r.isForward() == False:
  325. tgt = r.target()
  326. if isinstance(tgt, opcua_node_t):
  327. nref = opcua_referencePointer_t(n, parentNode=tgt)
  328. nref.referenceType(r.referenceType())
  329. tgt.addReference(nref)
  330. # Create inverse references for all nodes
  331. log(self, "Updating all referencedBy fields in nodes for inverse lookups.")
  332. for n in self.nodes:
  333. n.updateInverseReferences()
  334. for l in linked:
  335. self.__linkLater__.remove(l)
  336. if len(self.__linkLater__) != 0:
  337. log(self, str(len(self.__linkLater__)) + " could not be linked.", LOG_LEVEL_WARN)
  338. def sanitize(self):
  339. remove = []
  340. log(self, "Sanitizing nodes and references...")
  341. for n in self.nodes:
  342. if n.sanitize() == False:
  343. remove.append(n)
  344. if not len(remove) == 0:
  345. log(self, str(len(remove)) + " nodes will be removed because they failed sanitation.", LOG_LEVEL_WARN)
  346. # FIXME: Some variable ns=0 nodes fail because they don't have DataType fields...
  347. # How should this be handles!?
  348. log(self, "Not actually removing nodes... it's unclear if this is valid or not", LOG_LEVEL_WARN)
  349. def getRoot(self):
  350. """ Returns the first node instance with the browseName "Root".
  351. """
  352. return self.getNodeByBrowseName("Root")
  353. def buildEncodingRules(self):
  354. """ Calls buildEncoding() for all DataType nodes (opcua_node_dataType_t).
  355. No return value
  356. """
  357. stat = {True: 0, False: 0}
  358. for n in self.nodes:
  359. if isinstance(n, opcua_node_dataType_t):
  360. n.buildEncoding()
  361. stat[n.isEncodable()] = stat[n.isEncodable()] + 1
  362. log(self, "Type definitions built/passed: " + str(stat), LOG_LEVEL_DEBUG)
  363. def allocateVariables(self):
  364. for n in self.nodes:
  365. if isinstance(n, opcua_node_variable_t):
  366. n.allocateValue()
  367. def printDot(self, filename="namespace.dot"):
  368. """ Outputs a graphiz/dot description of all nodes in the namespace.
  369. Output will written into filename to be parsed by dot/neato...
  370. Note that for namespaces with more then 20 nodes the reference structure
  371. will lead to a mostly illegible and huge graph. Use printDotGraphWalk()
  372. for plotting specific portions of a large namespace.
  373. """
  374. file=open(filename, 'w+')
  375. file.write("digraph ns {\n")
  376. for n in self.nodes:
  377. file.write(n.printDot())
  378. file.write("}\n")
  379. file.close()
  380. def getSubTypesOf(self, tdNodes = None, currentNode = None, hasSubtypeRefNode = None):
  381. # If this is a toplevel call, collect the following information as defaults
  382. if tdNodes == None:
  383. tdNodes = []
  384. if currentNode == None:
  385. currentNode = self.getNodeByBrowseName("HasTypeDefinition")
  386. tdNodes.append(currentNode)
  387. if len(tdNodes) < 1:
  388. return []
  389. if hasSubtypeRefNode == None:
  390. hasSubtypeRefNode = self.getNodeByBrowseName("HasSubtype")
  391. if hasSubtypeRefNode == None:
  392. return tdNodes
  393. # collect all subtypes of this node
  394. for ref in currentNode.getReferences():
  395. if ref.isForward() and ref.referenceType().id() == hasSubtypeRefNode.id():
  396. tdNodes.append(ref.target())
  397. self.getTypeDefinitionNodes(tdNodes=tdNodes, currentNode = ref.target(), hasSubtypeRefNode=hasSubtypeRefNode)
  398. return tdNodes
  399. def printDotGraphWalk(self, depth=1, filename="out.dot", rootNode=None, followInverse = False, excludeNodeIds=[]):
  400. """ Outputs a graphiz/dot description the nodes centered around rootNode.
  401. References beginning from rootNode will be followed for depth steps. If
  402. "followInverse = True" is passed, then inverse (not Forward) references
  403. will also be followed.
  404. Nodes can be excluded from the graph by passing a list of NodeIds as
  405. string representation using excludeNodeIds (ex ["i=53", "ns=2;i=453"]).
  406. Output is written into filename to be parsed by dot/neato/srfp...
  407. """
  408. iter = depth
  409. processed = []
  410. if rootNode == None or \
  411. not isinstance(rootNode, opcua_node_t) or \
  412. not rootNode in self.nodes:
  413. root = self.getRoot()
  414. else:
  415. root = rootNode
  416. file=open(filename, 'w+')
  417. if root == None:
  418. return
  419. file.write("digraph ns {\n")
  420. file.write(root.printDot())
  421. refs=[]
  422. if followInverse == True:
  423. refs = root.getReferences(); # + root.getInverseReferences()
  424. else:
  425. for ref in root.getReferences():
  426. if ref.isForward():
  427. refs.append(ref)
  428. while iter > 0:
  429. tmp = []
  430. for ref in refs:
  431. if isinstance(ref.target(), opcua_node_t):
  432. tgt = ref.target()
  433. if not str(tgt.id()) in excludeNodeIds:
  434. if not tgt in processed:
  435. file.write(tgt.printDot())
  436. processed.append(tgt)
  437. if ref.isForward() == False and followInverse == True:
  438. tmp = tmp + tgt.getReferences(); # + tgt.getInverseReferences()
  439. elif ref.isForward() == True :
  440. tmp = tmp + tgt.getReferences();
  441. refs = tmp
  442. iter = iter - 1
  443. file.write("}\n")
  444. file.close()
  445. def __reorder_getMinWeightNode__(self, nmatrix):
  446. rcind = -1
  447. rind = -1
  448. minweight = -1
  449. minweightnd = None
  450. for row in nmatrix:
  451. rcind += 1
  452. if row[0] == None:
  453. continue
  454. w = sum(row[1:])
  455. if minweight < 0:
  456. rind = rcind
  457. minweight = w
  458. minweightnd = row[0]
  459. elif w < minweight:
  460. rind = rcind
  461. minweight = w
  462. minweightnd = row[0]
  463. return (rind, minweightnd, minweight)
  464. def reorderNodesMinDependencies(self):
  465. # create a matrix represtantion of all node
  466. #
  467. nmatrix = []
  468. for n in range(0,len(self.nodes)):
  469. nmatrix.append([None] + [0]*len(self.nodes))
  470. typeRefs = []
  471. tn = self.getNodeByBrowseName("HasTypeDefinition")
  472. if tn != None:
  473. typeRefs.append(tn)
  474. typeRefs = typeRefs + self.getSubTypesOf(currentNode=tn)
  475. subTypeRefs = []
  476. tn = self.getNodeByBrowseName("HasSubtype")
  477. if tn != None:
  478. subTypeRefs.append(tn)
  479. subTypeRefs = subTypeRefs + self.getSubTypesOf(currentNode=tn)
  480. log(self, "Building connectivity matrix for node order optimization.")
  481. # Set column 0 to contain the node
  482. for node in self.nodes:
  483. nind = self.nodes.index(node)
  484. nmatrix[nind][0] = node
  485. # Determine the dependencies of all nodes
  486. for node in self.nodes:
  487. nind = self.nodes.index(node)
  488. #print "Examining node " + str(nind) + " " + str(node)
  489. for ref in node.getReferences():
  490. if isinstance(ref.target(), opcua_node_t):
  491. tind = self.nodes.index(ref.target())
  492. # Typedefinition of this node has precedence over this node
  493. if ref.referenceType() in typeRefs and ref.isForward():
  494. nmatrix[nind][tind+1] += 1
  495. # isSubTypeOf/typeDefinition of this node has precedence over this node
  496. elif ref.referenceType() in subTypeRefs and not ref.isForward():
  497. nmatrix[nind][tind+1] += 1
  498. # Else the target depends on us
  499. elif ref.isForward():
  500. nmatrix[tind][nind+1] += 1
  501. log(self, "Using Djikstra topological sorting to determine printing order.")
  502. reorder = []
  503. while len(reorder) < len(self.nodes):
  504. (nind, node, w) = self.__reorder_getMinWeightNode__(nmatrix)
  505. #print str(100*float(len(reorder))/len(self.nodes)) + "% " + str(w) + " " + str(node) + " " + str(node.browseName())
  506. reorder.append(node)
  507. for ref in node.getReferences():
  508. if isinstance(ref.target(), opcua_node_t):
  509. tind = self.nodes.index(ref.target())
  510. if ref.referenceType() in typeRefs and ref.isForward():
  511. nmatrix[nind][tind+1] -= 1
  512. elif ref.referenceType() in subTypeRefs and not ref.isForward():
  513. nmatrix[nind][tind+1] -= 1
  514. elif ref.isForward():
  515. nmatrix[tind][nind+1] -= 1
  516. nmatrix[nind][0] = None
  517. self.nodes = reorder
  518. log(self, "Nodes reordered.")
  519. return
  520. def printOpen62541Header(self, printedExternally=[], supressGenerationOfAttribute=[], outfilename=""):
  521. unPrintedNodes = []
  522. unPrintedRefs = []
  523. code = []
  524. header = []
  525. # Reorder our nodes to produce a bare minimum of bootstrapping dependencies
  526. log(self, "Reordering nodes for minimal dependencies during printing.")
  527. self.reorderNodesMinDependencies()
  528. # Some macros (UA_EXPANDEDNODEID_MACRO()...) are easily created, but
  529. # bulky. This class will help to offload some code.
  530. codegen = open62541_MacroHelper(supressGenerationOfAttribute=supressGenerationOfAttribute)
  531. # Populate the unPrinted-Lists with everything we have.
  532. # Every Time a nodes printfunction is called, it will pop itself and
  533. # all printed references from these lists.
  534. for n in self.nodes:
  535. if not n in printedExternally:
  536. unPrintedNodes.append(n)
  537. else:
  538. log(self, "Node " + str(n.id()) + " is being ignored.", LOG_LEVEL_DEBUG)
  539. for n in unPrintedNodes:
  540. for r in n.getReferences():
  541. if (r.target() != None) and (r.target().id() != None) and (r.parent() != None):
  542. unPrintedRefs.append(r)
  543. log(self, str(len(unPrintedNodes)) + " Nodes, " + str(len(unPrintedRefs)) + "References need to get printed.", LOG_LEVEL_DEBUG)
  544. header.append("/* WARNING: This is a generated file.\n * Any manual changes will be overwritten.\n\n */")
  545. code.append("/* WARNING: This is a generated file.\n * Any manual changes will be overwritten.\n\n */")
  546. header.append('#ifndef '+outfilename.upper()+'_H_')
  547. header.append('#define '+outfilename.upper()+'_H_')
  548. header.append('#ifdef UA_NO_AMALGAMATION')
  549. header.append('#include "server/ua_server_internal.h"')
  550. header.append('#include "server/ua_nodes.h"')
  551. header.append('#include "ua_util.h"')
  552. header.append('#include "ua_types.h"')
  553. header.append('#else')
  554. header.append('#include "open62541.h"')
  555. header.append('#define UA_NULL ((void *)0)')
  556. header.append('#endif')
  557. code.append('#include "'+outfilename+'.h"')
  558. code.append("UA_INLINE void "+outfilename+"(UA_Server *server) {")
  559. # Find all references necessary to create the namespace and
  560. # "Bootstrap" them so all other nodes can safely use these referencetypes whenever
  561. # they can locate both source and target of the reference.
  562. log(self, "Collecting all references used in the namespace.", LOG_LEVEL_DEBUG)
  563. refsUsed = []
  564. for n in self.nodes:
  565. # Since we are already looping over all nodes, use this chance to print NodeId defines
  566. if n.id().ns != 0:
  567. nc = n.nodeClass()
  568. if nc != NODE_CLASS_OBJECT and nc != NODE_CLASS_VARIABLE and nc != NODE_CLASS_VIEW:
  569. header = header + codegen.getNodeIdDefineString(n)
  570. # Now for the actual references...
  571. for r in n.getReferences():
  572. # Only print valid refernces in namespace 0 (users will not want their refs bootstrapped)
  573. if not r.referenceType() in refsUsed and r.referenceType() != None and r.referenceType().id().ns == 0:
  574. refsUsed.append(r.referenceType())
  575. log(self, str(len(refsUsed)) + " reference types are used in the namespace, which will now get bootstrapped.", LOG_LEVEL_DEBUG)
  576. for r in refsUsed:
  577. code = code + r.printOpen62541CCode(unPrintedNodes, unPrintedRefs);
  578. header.append("extern void "+outfilename+"(UA_Server *server);\n")
  579. header.append("#endif /* "+outfilename.upper()+"_H_ */")
  580. # Note to self: do NOT - NOT! - try to iterate over unPrintedNodes!
  581. # Nodes remove themselves from this list when printed.
  582. log(self, "Printing all other nodes.", LOG_LEVEL_DEBUG)
  583. for n in self.nodes:
  584. code = code + n.printOpen62541CCode(unPrintedNodes, unPrintedRefs, supressGenerationOfAttribute=supressGenerationOfAttribute)
  585. if len(unPrintedNodes) != 0:
  586. log(self, "" + str(len(unPrintedNodes)) + " nodes could not be translated to code.", LOG_LEVEL_WARN)
  587. else:
  588. log(self, "Printing suceeded for all nodes", LOG_LEVEL_DEBUG)
  589. if len(unPrintedRefs) != 0:
  590. log(self, "Attempting to print " + str(len(unPrintedRefs)) + " unprinted references.", LOG_LEVEL_DEBUG)
  591. tmprefs = []
  592. for r in unPrintedRefs:
  593. if not (r.target() not in unPrintedNodes) and not (r.parent() in unPrintedNodes):
  594. if not isinstance(r.parent(), opcua_node_t):
  595. log(self, "Reference has no parent!", LOG_LEVEL_DEBUG)
  596. elif not isinstance(r.parent().id(), opcua_node_id_t):
  597. log(self, "Parents nodeid is not a nodeID!", LOG_LEVEL_DEBUG)
  598. else:
  599. if (len(tmprefs) == 0):
  600. code.append("// Creating leftover references:")
  601. code = code + codegen.getCreateStandaloneReference(r.parent(), r)
  602. code.append("")
  603. tmprefs.append(r)
  604. # Remove printed refs from list
  605. for r in tmprefs:
  606. unPrintedRefs.remove(r)
  607. if len(unPrintedRefs) != 0:
  608. log(self, "" + str(len(unPrintedRefs)) + " references could not be translated to code.", LOG_LEVEL_WARN)
  609. else:
  610. log(self, "Printing succeeded for all references", LOG_LEVEL_DEBUG)
  611. code.append("}")
  612. return (header,code)
  613. ###
  614. ### Testing
  615. ###
  616. class testing:
  617. def __init__(self):
  618. self.namespace = opcua_namespace("testing")
  619. log(self, "Phase 1: Reading XML file nodessets")
  620. self.namespace.parseXML("Opc.Ua.NodeSet2.xml")
  621. #self.namespace.parseXML("Opc.Ua.NodeSet2.Part4.xml")
  622. #self.namespace.parseXML("Opc.Ua.NodeSet2.Part5.xml")
  623. #self.namespace.parseXML("Opc.Ua.SimulationNodeSet2.xml")
  624. log(self, "Phase 2: Linking address space references and datatypes")
  625. self.namespace.linkOpenPointers()
  626. self.namespace.sanitize()
  627. log(self, "Phase 3: Comprehending DataType encoding rules")
  628. self.namespace.buildEncodingRules()
  629. log(self, "Phase 4: Allocating variable value data")
  630. self.namespace.allocateVariables()
  631. bin = self.namespace.buildBinary()
  632. f = open("binary.base64","w+")
  633. f.write(bin.encode("base64"))
  634. f.close()
  635. allnodes = self.namespace.nodes;
  636. ns = [self.namespace.getRoot()]
  637. i = 0
  638. #print "Starting depth search on " + str(len(allnodes)) + " nodes starting with from " + str(ns)
  639. while (len(ns) < len(allnodes)):
  640. i = i + 1;
  641. tmp = [];
  642. print("Iteration: " + str(i))
  643. for n in ns:
  644. tmp.append(n)
  645. for r in n.getReferences():
  646. if (not r.target() in tmp):
  647. tmp.append(r.target())
  648. print("...tmp, " + str(len(tmp)) + " nodes discovered")
  649. ns = []
  650. for n in tmp:
  651. ns.append(n)
  652. print("...done, " + str(len(ns)) + " nodes discovered")
  653. log(self, "Phase 5: Printing pretty graph")
  654. self.namespace.printDotGraphWalk(depth=1, rootNode=self.namespace.getNodeByIDString("i=84"), followInverse=False, excludeNodeIds=["i=29", "i=22", "i=25"])
  655. #self.namespace.printDot()
  656. class testing_open62541_header:
  657. def __init__(self):
  658. self.namespace = opcua_namespace("testing")
  659. log(self, "Phase 1: Reading XML file nodessets")
  660. self.namespace.parseXML("Opc.Ua.NodeSet2.xml")
  661. #self.namespace.parseXML("Opc.Ua.NodeSet2.Part4.xml")
  662. #self.namespace.parseXML("Opc.Ua.NodeSet2.Part5.xml")
  663. #self.namespace.parseXML("Opc.Ua.SimulationNodeSet2.xml")
  664. log(self, "Phase 2: Linking address space references and datatypes")
  665. self.namespace.linkOpenPointers()
  666. self.namespace.sanitize()
  667. log(self, "Phase 3: Calling C Printers")
  668. code = self.namespace.printOpen62541Header()
  669. codeout = open("./open62541_namespace.c", "w+")
  670. for line in code:
  671. codeout.write(line + "\n")
  672. codeout.close()
  673. return
  674. # Call testing routine if invoked standalone.
  675. # For better debugging, it is advised to import this file using an interactive
  676. # python shell and instantiating a namespace.
  677. #
  678. # import ua_types.py as ua; ns=ua.testing().namespace
  679. if __name__ == '__main__':
  680. tst = testing_open62541_header()