ua_namespace.py 30 KB

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