ua_namespace.py 30 KB

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