ua_namespace.py 25 KB

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