ua_namespace.py 31 KB

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