ua_namespace.py 29 KB

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