ua_node_types.py 66 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772
  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. import sys
  21. import logging
  22. from ua_builtin_types import *;
  23. from open62541_MacroHelper import open62541_MacroHelper
  24. from ua_constants import *
  25. logger = logging.getLogger(__name__)
  26. def getNextElementNode(xmlvalue):
  27. if xmlvalue == None:
  28. return None
  29. xmlvalue = xmlvalue.nextSibling
  30. while not xmlvalue == None and not xmlvalue.nodeType == xmlvalue.ELEMENT_NODE:
  31. xmlvalue = xmlvalue.nextSibling
  32. return xmlvalue
  33. ###
  34. ### References are not really described by OPC-UA. This is how we
  35. ### use them here.
  36. ###
  37. class opcua_referencePointer_t():
  38. """ Representation of a pointer.
  39. A pointer consists of a target (which should be a node class),
  40. an optional reference type (which should be an instance of
  41. opcua_node_referenceType_t) and an optional isForward flag.
  42. """
  43. __reference_type__ = None
  44. __target__ = None
  45. __isForward__ = True
  46. __addr__ = 0
  47. __parentNode__ = None
  48. def __init__(self, target, hidden=False, parentNode=None):
  49. self.__target__ = target
  50. self.__reference_type__ = None
  51. self.__isForward__ = True
  52. self.__isHidden__ = hidden
  53. self.__parentNode__ = parentNode
  54. self.__addr__ = 0
  55. def isHidden(self, data=None):
  56. if isinstance(data, bool):
  57. self.__isHidden__ = data
  58. return self.__isHidden__
  59. def isForward(self, data=None):
  60. if isinstance(data, bool):
  61. self.__isForward__ = data
  62. return self.__isForward__
  63. def referenceType(self, type=None):
  64. if not type == None:
  65. self.__reference_type__ = type
  66. return self.__reference_type__
  67. def target(self, data=None):
  68. if not data == None:
  69. self.__target__ = data
  70. return self.__target__
  71. def address(self, data=None):
  72. if data != None:
  73. self.__addr__ = data
  74. return self.__addr__
  75. def parent(self):
  76. return self.__parentNode__
  77. def getCodePrintableID(self):
  78. src = "None"
  79. tgt = "None"
  80. type = "Unknown"
  81. if self.parent() != None:
  82. src = str(self.parent().id())
  83. if self.target() != None:
  84. tgt = str(self.target().id())
  85. if self.referenceType() != None:
  86. type = str(self.referenceType().id())
  87. tmp = src+"_"+type+"_"+tgt
  88. tmp = tmp.lower()
  89. refid = ""
  90. for i in tmp:
  91. if not i in "ABCDEFGHIJKLMOPQRSTUVWXYZ0123456789".lower():
  92. refid = refid + ("_")
  93. else:
  94. refid = refid + i
  95. return refid
  96. def __str__(self):
  97. retval=""
  98. if isinstance(self.parent(), opcua_node_t):
  99. if isinstance(self.parent().id(), opcua_node_id_t):
  100. retval=retval + str(self.parent().id()) + "--["
  101. else:
  102. retval=retval + "(?) --["
  103. else:
  104. retval=retval + "(?) --["
  105. if isinstance(self.referenceType(), opcua_node_t):
  106. retval=retval + str(self.referenceType().browseName()) + "]-->"
  107. else:
  108. retval=retval + "?]-->"
  109. if isinstance(self.target(), opcua_node_t):
  110. if isinstance(self.target().id(), opcua_node_id_t):
  111. retval=retval + str(self.target().id())
  112. else:
  113. retval=retval + "(?) "
  114. else:
  115. retval=retval + "(?) "
  116. if self.isForward() or self.isHidden():
  117. retval = retval + " <"
  118. if self.isForward():
  119. retval = retval + "F"
  120. if self.isHidden():
  121. retval = retval + "H"
  122. retval = retval + ">"
  123. return retval
  124. def __repr__(self):
  125. return self.__str__()
  126. def __cmp__(self, other):
  127. if not isinstance(other, opcua_referencePointer_t):
  128. return -1
  129. if other.target() == self.target():
  130. if other.referenceType() == self.referenceType():
  131. if other.isForward() == self.isForward():
  132. return 0
  133. return 1
  134. ###
  135. ### Node ID's as a builtin type are useless. using this one instead.
  136. ###
  137. class opcua_node_id_t():
  138. """ Implementation of a node ID.
  139. The ID will encoding itself appropriatly as string. If multiple ID's (numeric, string, guid)
  140. are defined, the order of preference for the ID string is always numeric, guid,
  141. bytestring, string. Binary encoding only applies to numeric values (UInt16).
  142. """
  143. i = -1
  144. o = ""
  145. g = ""
  146. s = ""
  147. ns = 0
  148. __mystrname__ = ""
  149. def __init__(self, idstring):
  150. idparts = idstring.split(";")
  151. self.i = None
  152. self.b = None
  153. self.g = None
  154. self.s = None
  155. self.ns = 0
  156. for p in idparts:
  157. if p[:2] == "ns":
  158. self.ns = int(p[3:])
  159. elif p[:2] == "i=":
  160. self.i = int(p[2:])
  161. elif p[:2] == "o=":
  162. self.b = p[2:]
  163. elif p[:2] == "g=":
  164. tmp = []
  165. self.g = p[2:].split("-")
  166. for i in self.g:
  167. i = "0x"+i
  168. tmp.append(int(i,16))
  169. self.g = tmp
  170. elif p[:2] == "s=":
  171. self.s = p[2:]
  172. self.__mystrname__ = ""
  173. self.toString()
  174. def toString(self):
  175. self.__mystrname__ = ""
  176. if self.ns != 0:
  177. self.__mystrname__ = "ns="+str(self.ns)+";"
  178. # Order of preference is numeric, guid, bytestring, string
  179. if self.i != None:
  180. self.__mystrname__ = self.__mystrname__ + "i="+str(self.i)
  181. elif self.g != None:
  182. self.__mystrname__ = self.__mystrname__ + "g="
  183. tmp = []
  184. for i in self.g:
  185. tmp.append(hex(i).replace("0x",""))
  186. for i in tmp:
  187. self.__mystrname__ = self.__mystrname__ + "-" + i
  188. self.__mystrname__ = self.__mystrname__.replace("g=-","g=")
  189. elif self.b != None:
  190. self.__mystrname__ = self.__mystrname__ + "b="+str(self.b)
  191. elif self.s != None:
  192. self.__mystrname__ = self.__mystrname__ + "s="+str(self.s)
  193. def __str__(self):
  194. return self.__mystrname__
  195. def __eq__(self, nodeId2):
  196. if not nodeId2:
  197. return False
  198. return (self.toString() == nodeId2.toString())
  199. def __repr__(self):
  200. return self.__mystrname__
  201. ###
  202. ### Actually existing node types
  203. ###
  204. class opcua_node_t:
  205. __node_id__ = None
  206. __node_class__ = 0
  207. __node_browseName__ = ""
  208. __node_displayName__ = ""
  209. __node_description__ = ""
  210. __node_writeMask__ = 0
  211. __node_userWriteMask__ = 0
  212. __node_namespace__ = None
  213. __node_references__ = []
  214. __node_referencedBy__ = []
  215. __binary__ = ""
  216. __address__ = 0
  217. def __init__(self, id, ns):
  218. self.__node_namespace__ = ns
  219. self.__node_id__ = id
  220. self.__node_class__ = 0
  221. self.__node_browseName__ = ""
  222. self.__node_displayName__ = ""
  223. self.__node_description__ = ""
  224. self.__node_writeMask__ = 0
  225. self.__node_userWriteMask__ = 0
  226. self.__node_references__ = []
  227. self.__node_referencedBy__ = []
  228. self.__init_subType__()
  229. self.FLAG_ISABSTRACT = 128
  230. self.FLAG_SYMMETRIC = 64
  231. self.FLAG_CONTAINSNOLOOPS = 32
  232. self.FLAG_EXECUTABLE = 16
  233. self.FLAG_USEREXECUTABLE = 8
  234. self.FLAG_HISTORIZING = 4
  235. self.__binary__ = ""
  236. def __init_subType__(self):
  237. self.nodeClass(0)
  238. def __str__(self):
  239. if isinstance(self.id(), opcua_node_id_t):
  240. return self.__class__.__name__ + "(" + str(self.id()) + ")"
  241. return self.__class__.__name__ + "( no ID )"
  242. def __repr__(self):
  243. if isinstance(self.id(), opcua_node_id_t):
  244. return self.__class__.__name__ + "(" + str(self.id()) + ")"
  245. return self.__class__.__name__ + "( no ID )"
  246. def getCodePrintableID(self):
  247. CodePrintable="NODE_"
  248. if isinstance(self.id(), opcua_node_id_t):
  249. CodePrintable = self.__class__.__name__ + "_" + str(self.id())
  250. else:
  251. CodePrintable = self.__class__.__name__ + "_unknown_nid"
  252. CodePrintable = CodePrintable.lower()
  253. cleanPrintable = ""
  254. for i in range(0,len(CodePrintable)):
  255. if not CodePrintable[i] in "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890_".lower():
  256. cleanPrintable = cleanPrintable + "_"
  257. else:
  258. cleanPrintable = cleanPrintable + CodePrintable[i]
  259. return cleanPrintable
  260. def addReference(self, ref):
  261. """ Add a opcua_referencePointer_t to the list of
  262. references this node carries.
  263. """
  264. if not ref in self.__node_references__:
  265. self.__node_references__.append(ref)
  266. def removeReference(self, ref):
  267. if ref in self.__node_references__:
  268. self.__node_references__.remove(ref)
  269. def removeReferenceToNode(self, targetNode):
  270. tmp = []
  271. if ref in self.__node_references__:
  272. if ref.target() != targetNode:
  273. tmp.append(ref)
  274. self.__node_references__ = tmp
  275. def addInverseReferenceTarget(self, node):
  276. """ Adds a reference to the inverse reference list of this node.
  277. Inverse references are considered as "this node is referenced by"
  278. and facilitate lookups when between nodes that reference this node,
  279. but are not referenced by this node. These references would
  280. require the namespace to be traversed by references to be found
  281. if this node was not aware of them.
  282. """
  283. # Only add this target if it is not already referenced
  284. if not node in self.__node_referencedBy__:
  285. if not self.hasReferenceTarget(node):
  286. self.__node_referencedBy__.append(opcua_referencePointer_t(node, hidden=True, parentNode=self))
  287. # logger.debug(self.__node_browseName__ + " added reverse reference to " + str(node.__node_browseName__))
  288. # else:
  289. # logger.debug(self.__node_browseName__ + " refusing reverse reference to " + str(node.__node_browseName__) + " (referenced normally)")
  290. # else:
  291. # logger.debug(self.__node_browseName__ + " refusing reverse reference to " + str(node.__node_browseName__) + " (already reversed referenced)")
  292. def getReferences(self):
  293. return self.__node_references__
  294. def getInverseReferences(self):
  295. return self.__node_referencedBy__
  296. def hasInverseReferenceTarget(self, node):
  297. for r in self.getInverseReferences():
  298. if node == r.target():
  299. return True
  300. return False
  301. def hasReferenceTarget(self, node):
  302. for r in self.getReferences():
  303. if node == r.target():
  304. return True
  305. return False
  306. def getFirstParentNode(self):
  307. """ getFirstParentNode
  308. return a tuple of (opcua_node_t, opcua_referencePointer_t) indicating
  309. the first node found that references this node. If this node is not
  310. referenced at all, None will be returned.
  311. This function requires a linked namespace.
  312. Note that there may be more than one nodes that reference this node.
  313. The parent returned will be determined by the first isInverse()
  314. Reference of this node found. If none exists, the first hidden
  315. reference will be returned.
  316. """
  317. parent = None
  318. revref = None
  319. for hiddenstatus in [False, True]:
  320. for r in self.getReferences():
  321. if r.isHidden() == hiddenstatus and r.isForward() == False:
  322. parent = r.target()
  323. for r in parent.getReferences():
  324. if r.target() == self:
  325. revref = r
  326. break
  327. if revref != None:
  328. return (parent, revref)
  329. return (parent, revref)
  330. def updateInverseReferences(self):
  331. """ Updates inverse references in all nodes referenced by this node.
  332. The function will look up all referenced nodes and check if they
  333. have a reference that points back at this node. If none is found,
  334. that means that the target is not aware that this node references
  335. it. In that case an inverse reference will be registered with
  336. the target node to point back to this node instance.
  337. """
  338. # Update inverse references in all nodes we have referenced
  339. for r in self.getReferences():
  340. if isinstance(r.target(), opcua_node_t):
  341. if not r.target().hasInverseReferenceTarget(self):
  342. #logger.debug(self.__node_browseName__ + " req. rev. referencing in" + str(r.target().__node_browseName__))
  343. r.target().addInverseReferenceTarget(self)
  344. #else:
  345. #logger.debug("Cannot register inverse link to " + str(r.target()) + " (not a node)")
  346. def id(self):
  347. return self.__node_id__
  348. def getNamespace(self):
  349. return self.__node_namespace__
  350. def nodeClass(self, c = 0):
  351. """ Sets the node class attribute if c is passed.
  352. Returns the current node class.
  353. """
  354. # Allow overwriting only if it is not set
  355. if isinstance(c, int):
  356. if self.__node_class__ == 0 and c < 256:
  357. self.__node_class__ = c
  358. return self.__node_class__
  359. def browseName(self, data=0):
  360. """ Sets the browse name attribute if data is passed.
  361. Returns the current browse name.
  362. """
  363. if isinstance(data, str):
  364. self.__node_browseName__ = data
  365. if sys.version_info[0] < 3:
  366. return self.__node_browseName__.encode('utf-8')
  367. return self.__node_browseName__
  368. def displayName(self, data=None):
  369. """ Sets the display name attribute if data is passed.
  370. Returns the current display name.
  371. """
  372. if data != None:
  373. self.__node_displayName__ = data
  374. return self.__node_displayName__.encode('utf-8')
  375. def description(self, data=None):
  376. """ Sets the description attribute if data is passed.
  377. Returns the current description.
  378. """
  379. if data != None:
  380. self.__node_description__ = data
  381. return self.__node_description__.encode('utf-8')
  382. def writeMask(self, data=None):
  383. """ Sets the write mask attribute if data is passed.
  384. Returns the current write mask.
  385. """
  386. if data != None:
  387. self.__node_writeMask__ = data
  388. return self.__node_writeMask__
  389. def userWriteMask(self, data=None):
  390. """ Sets the user write mask attribute if data is passed.
  391. Returns the current user write mask.
  392. """
  393. if data != None:
  394. self.__node_userWriteMask__ = data
  395. return self.__node_userWriteMask__
  396. def initiateDummyXMLReferences(self, xmlelement):
  397. """ Initiates references found in the XML <References> element.
  398. All references initiated will be registered with this node, but
  399. their targets will be strings extracted from the XML description
  400. (hence "dummy").
  401. References created will however be registered with the namespace
  402. for linkLater(), which will eventually replace the string target
  403. with an actual instance of an opcua_node_t.
  404. """
  405. if not xmlelement.tagName == "References":
  406. logger.error("XMLElement passed is not a reference list")
  407. return
  408. for ref in xmlelement.childNodes:
  409. if ref.nodeType == ref.ELEMENT_NODE:
  410. dummy = opcua_referencePointer_t(unicode(ref.firstChild.data), parentNode=self)
  411. self.addReference(dummy)
  412. self.getNamespace().linkLater(dummy)
  413. for (at, av) in ref.attributes.items():
  414. if at == "ReferenceType":
  415. dummy.referenceType(av)
  416. elif at == "IsForward":
  417. if "false" in av.lower():
  418. dummy.isForward(False)
  419. else:
  420. logger.error("Don't know how to process attribute " + at + "(" + av + ") for references.")
  421. def printDot(self):
  422. cleanname = "node_" + str(self.id()).replace(";","").replace("=","")
  423. dot = cleanname + " [label = \"{" + str(self.id()) + "|" + str(self.browseName()) + "}\", shape=\"record\"]"
  424. for r in self.__node_references__:
  425. if isinstance(r.target(), opcua_node_t):
  426. tgtname = "node_" + str(r.target().id()).replace(";","").replace("=","")
  427. dot = dot + "\n"
  428. if r.isForward() == True:
  429. dot = dot + cleanname + " -> " + tgtname + " [label=\"" + str(r.referenceType().browseName()) + "\"]\n"
  430. else:
  431. if len(r.referenceType().inverseName()) == 0:
  432. logger.warn("Inverse name of reference is null " + str(r.referenceType().id()))
  433. dot = dot + cleanname + " -> " + tgtname + " [label=\"" + str(r.referenceType().inverseName()) + "\"]\n"
  434. return dot
  435. def sanitize(self):
  436. """ Check the health of this node.
  437. Return True if all mandatory attributes are valid and all references have been
  438. correclty linked to nodes. Returns False on failure, which should indicate
  439. that this node needs to be removed from the namespace.
  440. """
  441. # Do we have an id?
  442. if not isinstance(self.id(), opcua_node_id_t):
  443. logger.error("HELP! I'm an id'less node!")
  444. return False
  445. # Remove unlinked references
  446. tmp = []
  447. for r in self.getReferences():
  448. if not isinstance(r, opcua_referencePointer_t):
  449. logger.error("Reference is not a reference!?.")
  450. elif not isinstance(r.referenceType(), opcua_node_t):
  451. logger.error("Reference has no valid reference type and will be removed.")
  452. elif not isinstance(r.target(), opcua_node_t):
  453. logger.warn("Reference to " + str(r.target()) + " is not a node. It has been removed.")
  454. else:
  455. tmp.append(r)
  456. self.__node_references__ = tmp
  457. # Make sure that every inverse referenced node actually does reference us
  458. tmp = []
  459. for r in self.getInverseReferences():
  460. if not isinstance(r.target(), opcua_node_t):
  461. logger.warn("Invers reference to " + str(r.target()) + " does not reference a real node. It has been removed.")
  462. else:
  463. if r.target().hasReferenceTarget(self):
  464. tmp.append(r)
  465. else:
  466. logger.warn("Node " + str(self.id()) + " was falsely under the impression that it is referenced by " + str(r.target().id()))
  467. self.__node_referencedBy__ = tmp
  468. # Remove references from inverse list if we can reach this not "the regular way"
  469. # over a normal reference
  470. tmp=[]
  471. for r in self.getInverseReferences():
  472. if not self.hasReferenceTarget(r.target()):
  473. tmp.append(r)
  474. else:
  475. logger.debug("Removing unnecessary inverse reference to " + str(r.target.id()))
  476. self.__node_referencedBy__ = tmp
  477. return self.sanitizeSubType()
  478. def sanitizeSubType(self):
  479. pass
  480. def address(self, addr = None):
  481. """ If addr is passed, the address of this node within the binary
  482. representation will be set.
  483. If an address within the binary representation is known/set, this
  484. function will return it. NoneType is returned if no address has been
  485. set.
  486. """
  487. if addr != None:
  488. self.__address__ = addr
  489. return self.__address__
  490. def parseXML(self, xmlelement):
  491. """ Extracts base attributes from the XML description of an element.
  492. Parsed basetype attributes are:
  493. * browseName
  494. * displayName
  495. * Description
  496. * writeMask
  497. * userWriteMask
  498. * eventNotifier
  499. ParentNodeIds are ignored.
  500. If recognized, attributes and elements found will be removed from
  501. the XML Element passed. Type-specific attributes and child elements
  502. are handled by the parseXMLSubType() functions of all classes deriving
  503. from this base type and will be called automatically.
  504. """
  505. thisxml = xmlelement
  506. for (at, av) in thisxml.attributes.items():
  507. if at == "NodeId":
  508. xmlelement.removeAttribute(at)
  509. elif at == "BrowseName":
  510. self.browseName(str(av))
  511. xmlelement.removeAttribute(at)
  512. elif at == "DisplayName":
  513. self.displayName(av)
  514. xmlelement.removeAttribute(at)
  515. elif at == "Description":
  516. self.description(av)
  517. xmlelement.removeAttribute(at)
  518. elif at == "WriteMask":
  519. self.writeMask(int(av))
  520. xmlelement.removeAttribute(at)
  521. elif at == "UserWriteMask":
  522. self.userWriteMask(int(av))
  523. xmlelement.removeAttribute(at)
  524. elif at == "EventNotifier":
  525. self.eventNotifier(int(av))
  526. xmlelement.removeAttribute(at)
  527. elif at == "ParentNodeId":
  528. # Silently ignore this one..
  529. xmlelement.removeAttribute(at)
  530. for x in thisxml.childNodes:
  531. if x.nodeType == x.ELEMENT_NODE:
  532. if x.firstChild:
  533. if x.tagName == "BrowseName":
  534. self.browseName(unicode(x.firstChild.data))
  535. xmlelement.removeChild(x)
  536. elif x.tagName == "DisplayName":
  537. self.displayName(unicode(x.firstChild.data))
  538. xmlelement.removeChild(x)
  539. elif x.tagName == "Description":
  540. self.description(unicode(x.firstChild.data))
  541. xmlelement.removeChild(x)
  542. elif x.tagName == "WriteMask":
  543. self.writeMask(int(unicode(x.firstChild.data)))
  544. xmlelement.removeChild(x)
  545. elif x.tagName == "UserWriteMask":
  546. self.userWriteMask(int(unicode(x.firstChild.data)))
  547. xmlelement.removeChild(x)
  548. if x.tagName == "References":
  549. self.initiateDummyXMLReferences(x)
  550. xmlelement.removeChild(x)
  551. self.parseXMLSubType(xmlelement)
  552. def parseXMLSubType(self, xmlelement):
  553. pass
  554. def printXML(self):
  555. pass
  556. def printOpen62541CCode_SubtypeEarly(self, bootstrapping = True):
  557. """ printOpen62541CCode_SubtypeEarly
  558. Initiate code segments for the nodes instantiotion that preceed
  559. the actual UA_Server_addNode or UA_NodeStore_insert calls.
  560. """
  561. return []
  562. def printOpen62541CCode_Subtype(self, unPrintedReferences=[], bootstrapping = True):
  563. """ printOpen62541CCode_Subtype
  564. Appends node type specific information to the nodes UA_Server_addNode
  565. or UA_NodeStore_insert calls.
  566. """
  567. return []
  568. def printOpen62541CCode(self, unPrintedNodes=[], unPrintedReferences=[], supressGenerationOfAttribute=[]):
  569. """ printOpen62541CCode
  570. Returns a list of strings containing the C-code necessary to intialize
  571. this node for the open62541 OPC-UA Stack.
  572. Note that this function will fail if the nodeid is non-numeric, as
  573. there is no UA_EXPANDEDNNODEID_[STRING|GUID|BYTESTRING] macro.
  574. """
  575. codegen = open62541_MacroHelper(supressGenerationOfAttribute=supressGenerationOfAttribute)
  576. code = []
  577. code.append("")
  578. code.append("do {")
  579. # Just to be sure...
  580. if not (self in unPrintedNodes):
  581. logger.warn(str(self) + " attempted to reprint already printed node " + str(self)+ ".")
  582. return []
  583. # If we are being passed a parent node by the namespace, use that for registering ourselves in the namespace
  584. # Note: getFirstParentNode will return [parentNode, referenceToChild]
  585. (parentNode, parentRef) = self.getFirstParentNode()
  586. if not (parentNode in unPrintedNodes) and (parentNode != None) and (parentRef.referenceType() != None):
  587. code.append("// Referencing node found and declared as parent: " + str(parentNode .id()) + "/" +
  588. str(parentNode .__node_browseName__) + " using " + str(parentRef.referenceType().id()) +
  589. "/" + str(parentRef.referenceType().__node_browseName__))
  590. code = code + codegen.getCreateNodeNoBootstrap(self, parentNode, parentRef, unPrintedNodes)
  591. # Parent to child reference is added by the server, do not reprint that reference
  592. if parentRef in unPrintedReferences:
  593. unPrintedReferences.remove(parentRef)
  594. # the UA_Server_addNode function will use addReference which creates a bidirectional reference; remove any inverse
  595. # references to our parent to avoid duplicate refs
  596. for ref in self.getReferences():
  597. if ref.target() == parentNode and ref.referenceType() == parentRef.referenceType() and ref.isForward() == False:
  598. while ref in unPrintedReferences:
  599. unPrintedReferences.remove(ref)
  600. # Otherwise use the "Bootstrapping" method and we will get registered with other nodes later.
  601. else:
  602. code.append("/* Omit bootstrapping the node %s */" % str(self.id()))
  603. # Try to print all references to nodes that already exist
  604. # Note: we know the reference types exist, because the namespace class made sure they were
  605. # the first ones being printed
  606. tmprefs = []
  607. for r in self.getReferences():
  608. #logger.debug("Checking if reference from " + str(r.parent()) + "can be created...")
  609. if not (r.target() in unPrintedNodes):
  610. if r in unPrintedReferences:
  611. if (len(tmprefs) == 0):
  612. code.append("// This node has the following references that can be created:")
  613. code = code + codegen.getCreateStandaloneReference(self, r)
  614. tmprefs.append(r)
  615. # Remove printed refs from list
  616. for r in tmprefs:
  617. unPrintedReferences.remove(r)
  618. # Again, but this time check if other nodes deffered their node creation because this node did
  619. # not exist...
  620. tmprefs = []
  621. for r in unPrintedReferences:
  622. #logger.debug("Checking if another reference " + str(r.target()) + "can be created...")
  623. if (r.target() == self) and not (r.parent() in unPrintedNodes):
  624. if not isinstance(r.parent(), opcua_node_t):
  625. logger.debug("Reference has no parent!")
  626. elif not isinstance(r.parent().id(), opcua_node_id_t):
  627. logger.debug("Parents nodeid is not a nodeID!")
  628. else:
  629. if (len(tmprefs) == 0):
  630. code.append("// Creating this node has resolved the following open references:")
  631. code = code + codegen.getCreateStandaloneReference(r.parent(), r)
  632. tmprefs.append(r)
  633. # Remove printed refs from list
  634. for r in tmprefs:
  635. unPrintedReferences.remove(r)
  636. # Again, just to be sure...
  637. if self in unPrintedNodes:
  638. # This is necessery to make printing work at all!
  639. unPrintedNodes.remove(self)
  640. code.append("} while(0);")
  641. return code
  642. class opcua_node_referenceType_t(opcua_node_t):
  643. __isAbstract__ = False
  644. __symmetric__ = False
  645. __reference_inverseName__ = ""
  646. __reference_referenceType__ = None
  647. def __init_subType__(self):
  648. self.nodeClass(NODE_CLASS_REFERENCETYPE)
  649. self.__reference_isAbstract__ = False
  650. self.__reference_symmetric__ = False
  651. self.__reference_inverseName__ = ""
  652. self.__reference_referenceType__ = None
  653. def referenceType(self,data=None):
  654. if isinstance(data, opcua_node_t):
  655. self.__reference_referenceType__ = data
  656. return self.__reference_referenceType__
  657. def isAbstract(self,data=None):
  658. if isinstance(data, bool):
  659. self.__isAbstract__ = data
  660. return self.__isAbstract__
  661. def symmetric(self,data=None):
  662. if isinstance(data, bool):
  663. self.__symmetric__ = data
  664. return self.__symmetric__
  665. def inverseName(self,data=None):
  666. if isinstance(data, str):
  667. self.__reference_inverseName__ = data
  668. return self.__reference_inverseName__
  669. def sanitizeSubType(self):
  670. if not isinstance(self.referenceType(), opcua_referencePointer_t):
  671. logger.error("ReferenceType " + str(self.referenceType()) + " of " + str(self.id()) + " is not a pointer (ReferenceType is mandatory for references).")
  672. self.__reference_referenceType__ = None
  673. return False
  674. return True
  675. def parseXMLSubType(self, xmlelement):
  676. for (at, av) in xmlelement.attributes.items():
  677. if at == "Symmetric":
  678. if "false" in av.lower():
  679. self.symmetric(False)
  680. else:
  681. self.symmetric(True)
  682. xmlelement.removeAttribute(at)
  683. elif at == "InverseName":
  684. self.inverseName(str(av))
  685. xmlelement.removeAttribute(at)
  686. elif at == "IsAbstract":
  687. if "false" in str(av).lower():
  688. self.isAbstract(False)
  689. else:
  690. self.isAbstract(True)
  691. xmlelement.removeAttribute(at)
  692. else:
  693. logger.warn("Don't know how to process attribute " + at + " (" + av + ")")
  694. for x in xmlelement.childNodes:
  695. if x.nodeType == x.ELEMENT_NODE:
  696. if x.tagName == "InverseName" and x.firstChild:
  697. self.inverseName(str(unicode(x.firstChild.data)))
  698. else:
  699. logger.warn( "Unprocessable XML Element: " + x.tagName)
  700. def printOpen62541CCode_Subtype(self, unPrintedReferences=[], bootstrapping = True):
  701. code = []
  702. codegen = open62541_MacroHelper()
  703. # Detect if this is bootstrapping or if we are attempting to use userspace...
  704. if bootstrapping == False:
  705. typeDefs = self.getNamespace().getSubTypesOf() # defaults to TypeDefinition
  706. myTypeRef = None
  707. for ref in self.getReferences():
  708. if ref.referenceType() in typeDefs:
  709. myTypeRef = ref
  710. break
  711. if myTypeRef==None:
  712. for ref in self.getReferences():
  713. if ref.referenceType().browseName() == "HasSubtype" and ref.isForward() == False:
  714. myTypeRef = ref
  715. break
  716. if myTypeRef==None:
  717. logger.warn(str(self) + " failed to locate a type definition, assuming BaseDataType.")
  718. code.append(" // No valid typeDefinition found; assuming BaseDataType")
  719. code.append(" UA_EXPANDEDNODEID_NUMERIC(0, UA_NS0ID_BASEDATATYPE),")
  720. else:
  721. code.append(" " + codegen.getCreateExpandedNodeIDMacro(myTypeRef.target()) + ",")
  722. while myTypeRef in unPrintedReferences:
  723. unPrintedReferences.remove(myTypeRef)
  724. code.append(" UA_LOCALIZEDTEXT(\"\",\"" + str(self.inverseName()) + "\"),");
  725. code.append(" // FIXME: Missing, isAbstract")
  726. code.append(" // FIXME: Missing, symmetric")
  727. return code
  728. if self.isAbstract():
  729. code.append(self.getCodePrintableID() + "->isAbstract = true;")
  730. if self.symmetric():
  731. code.append(self.getCodePrintableID() + "->symmetric = true;")
  732. if self.__reference_inverseName__ != "":
  733. code.append(self.getCodePrintableID() + "->inverseName = UA_LOCALIZEDTEXT_ALLOC(\"\", \"" + self.__reference_inverseName__ + "\");")
  734. return code;
  735. class opcua_node_object_t(opcua_node_t):
  736. __object_eventNotifier__ = 0
  737. def __init_subType__(self):
  738. self.nodeClass(NODE_CLASS_OBJECT)
  739. self.__object_eventNotifier__ = 0
  740. def eventNotifier(self, data=""):
  741. if isinstance(data, int):
  742. self.__object_eventNotifier__ == data
  743. return self.__object_eventNotifier__
  744. def parseXMLSubType(self, xmlelement):
  745. for (at, av) in xmlelement.attributes.items():
  746. if at == "EventNotifier":
  747. self.eventNotifier(int(av))
  748. xmlelement.removeAttribute(at)
  749. elif at == "SymbolicName":
  750. # Silently ignore this one
  751. xmlelement.removeAttribute(at)
  752. else:
  753. logger.error("Don't know how to process attribute " + at + " (" + av + ")")
  754. for x in xmlelement.childNodes:
  755. if x.nodeType == x.ELEMENT_NODE:
  756. logger.info( "Unprocessable XML Element: " + x.tagName)
  757. def printOpen62541CCode_Subtype(self, unPrintedReferences=[], bootstrapping = True):
  758. code = []
  759. codegen = open62541_MacroHelper()
  760. # Detect if this is bootstrapping or if we are attempting to use userspace...
  761. if bootstrapping == False:
  762. typeDefs = self.getNamespace().getSubTypesOf() # defaults to TypeDefinition
  763. myTypeRef = None
  764. for ref in self.getReferences():
  765. if ref.referenceType() in typeDefs:
  766. myTypeRef = ref
  767. break
  768. if myTypeRef==None:
  769. for ref in self.getReferences():
  770. if ref.referenceType().browseName() == "HasSubtype" and ref.isForward() == False:
  771. myTypeRef = ref
  772. break
  773. if myTypeRef==None:
  774. logger.warn(str(self) + " failed to locate a type definition, assuming BaseObjectType.")
  775. code.append(" // No valid typeDefinition found; assuming BaseObjectType")
  776. code.append(" UA_EXPANDEDNODEID_NUMERIC(0, UA_NS0ID_BASEOBJECTTYPE),")
  777. else:
  778. code.append(" " + codegen.getCreateExpandedNodeIDMacro(myTypeRef.target()) + ",")
  779. while myTypeRef in unPrintedReferences:
  780. unPrintedReferences.remove(myTypeRef)
  781. #FIXME: No event notifier in UA_Server_addNode call!
  782. return code
  783. # We are being bootstrapped! Add the raw attributes to the node.
  784. code.append(self.getCodePrintableID() + "->eventNotifier = (UA_Byte) " + str(self.eventNotifier()) + ";")
  785. return code
  786. if sys.version_info[0] >= 3:
  787. # strings are already parsed to unicode
  788. def unicode(s):
  789. return s
  790. class opcua_node_variable_t(opcua_node_t):
  791. __value__ = 0
  792. __dataType__ = None
  793. __valueRank__ = 0
  794. __arrayDimensions__ = 0
  795. __accessLevel__ = 0
  796. __userAccessLevel__ = 0
  797. __minimumSamplingInterval__ = 0
  798. __historizing__ = False
  799. def __init_subType__(self):
  800. self.nodeClass(NODE_CLASS_VARIABLE)
  801. self.__value__ = None
  802. self.__dataType__ = None
  803. self.__valueRank__ = -1
  804. self.__arrayDimensions__ = []
  805. self.__accessLevel__ = 3
  806. self.__userAccessLevel__ = 3
  807. self.__minimumSamplingInterval__ = 0.0
  808. self.__historizing__ = False
  809. self.__xmlValueDef__ = None
  810. def value(self, data=0):
  811. if isinstance(data, opcua_value_t):
  812. self.__value__ = data
  813. return self.__value__
  814. def dataType(self, data=None):
  815. if data != None:
  816. self.__dataType__ = data
  817. return self.__dataType__
  818. def valueRank(self, data=""):
  819. if isinstance(data, int):
  820. self.__valueRank__ = data
  821. return self.__valueRank__
  822. def arrayDimensions(self, data=None):
  823. if not data==None:
  824. self.__arrayDimensions__ = data
  825. return self.__arrayDimensions__
  826. def accessLevel(self, data=None):
  827. if not data==None:
  828. self.__accessLevel__ = data
  829. return self.__accessLevel__
  830. def userAccessLevel(self, data=None):
  831. if not data==None:
  832. self.__userAccessLevel__ = data
  833. return self.__userAccessLevel__
  834. def minimumSamplingInterval(self, data=None):
  835. if not data==None:
  836. self.__minimumSamplingInterval__ = data
  837. return self.__minimumSamplingInterval__
  838. def historizing(self, data=None):
  839. if data != None:
  840. self.__historizing__ = data
  841. return self.__historizing__
  842. def sanitizeSubType(self):
  843. if not isinstance(self.dataType(), opcua_referencePointer_t):
  844. logger.error("DataType " + str(self.dataType()) + " of " + str(self.id()) + " is not a pointer (DataType is mandatory for variables).")
  845. self.__dataType__ = None
  846. return False
  847. if not isinstance(self.dataType().target(), opcua_node_t):
  848. logger.error("DataType " + str(self.dataType().target()) + " of " + str(self.id()) + " does not point to a node (DataType is mandatory for variables).")
  849. self.__dataType__ = None
  850. return False
  851. return True
  852. def allocateValue(self):
  853. if not isinstance(self.dataType(), opcua_referencePointer_t):
  854. logger.error("Variable " + self.browseName() + "/" + str(self.id()) + " does not reference a valid dataType.")
  855. return False
  856. if not isinstance(self.dataType().target(), opcua_node_dataType_t):
  857. logger.error("Variable " + self.browseName() + "/" + str(self.id()) + " does not have a valid dataType reference.")
  858. return False
  859. if not self.dataType().target().isEncodable():
  860. logger.error("DataType for Variable " + self.browseName() + "/" + str(self.id()) + " is not encodable.")
  861. return False
  862. # FIXME: Don't build at all or allocate "defaults"? I'm for not building at all.
  863. if self.__xmlValueDef__ == None:
  864. #logger.warn("Variable " + self.browseName() + "/" + str(self.id()) + " is not initialized. No memory will be allocated.")
  865. return False
  866. self.value(opcua_value_t(self))
  867. self.value().parseXML(self.__xmlValueDef__)
  868. # Array Dimensions must accurately represent the value and will be patched
  869. # reflect the exaxt dimensions attached binary stream.
  870. if not isinstance(self.value(), opcua_value_t) or len(self.value().value) == 0:
  871. self.arrayDimensions([])
  872. else:
  873. # Parser only permits 1-d arrays, which means we do not have to check further dimensions
  874. self.arrayDimensions([len(self.value().value)])
  875. return True
  876. def parseXMLSubType(self, xmlelement):
  877. for (at, av) in xmlelement.attributes.items():
  878. if at == "ValueRank":
  879. self.valueRank(int(av))
  880. xmlelement.removeAttribute(at)
  881. elif at == "AccessLevel":
  882. self.accessLevel(int(av))
  883. xmlelement.removeAttribute(at)
  884. elif at == "UserAccessLevel":
  885. self.userAccessLevel(int(av))
  886. xmlelement.removeAttribute(at)
  887. elif at == "MinimumSamplingInterval":
  888. self.minimumSamplingInterval(float(av))
  889. xmlelement.removeAttribute(at)
  890. elif at == "DataType":
  891. self.dataType(opcua_referencePointer_t(str(av), parentNode=self))
  892. # dataType needs to be linked to a node once the namespace is read
  893. self.getNamespace().linkLater(self.dataType())
  894. xmlelement.removeAttribute(at)
  895. elif at == "SymbolicName":
  896. # Silently ignore this one
  897. xmlelement.removeAttribute(at)
  898. else:
  899. logger.error("Don't know how to process attribute " + at + " (" + av + ")")
  900. for x in xmlelement.childNodes:
  901. if x.nodeType == x.ELEMENT_NODE:
  902. if x.tagName == "Value":
  903. # We need to be able to parse the DataType to build the variable value,
  904. # which can only be done if the namespace is linked.
  905. # Store the Value for later parsing
  906. self.__xmlValueDef__ = x
  907. #logger.debug( "Value description stored for later elaboration.")
  908. elif x.tagName == "DataType":
  909. self.dataType(opcua_referencePointer_t(str(av), parentNode=self))
  910. # dataType needs to be linked to a node once the namespace is read
  911. self.getNamespace().linkLater(self.dataType())
  912. elif x.tagName == "ValueRank":
  913. self.valueRank(int(unicode(x.firstChild.data)))
  914. elif x.tagName == "ArrayDimensions":
  915. self.arrayDimensions(int(unicode(x.firstChild.data)))
  916. elif x.tagName == "AccessLevel":
  917. self.accessLevel(int(unicode(x.firstChild.data)))
  918. elif x.tagName == "UserAccessLevel":
  919. self.userAccessLevel(int(unicode(x.firstChild.data)))
  920. elif x.tagName == "MinimumSamplingInterval":
  921. self.minimumSamplingInterval(float(unicode(x.firstChild.data)))
  922. elif x.tagName == "Historizing":
  923. if "true" in x.firstChild.data.lower():
  924. self.historizing(True)
  925. else:
  926. logger.info( "Unprocessable XML Element: " + x.tagName)
  927. def printOpen62541CCode_SubtypeEarly(self, bootstrapping = True):
  928. code = []
  929. # If we have an encodable value, try to encode that
  930. if self.dataType() != None and isinstance(self.dataType().target(), opcua_node_dataType_t):
  931. # Delegate the encoding of the datavalue to the helper if we have
  932. # determined a valid encoding
  933. if self.dataType().target().isEncodable():
  934. if self.value() != None:
  935. code = code + self.value().printOpen62541CCode(bootstrapping)
  936. return code
  937. if(bootstrapping):
  938. code.append("UA_Variant *" + self.getCodePrintableID() + "_variant = (UA_Variant*)UA_alloca(sizeof(UA_Variant));")
  939. code.append("UA_Variant_init(" + self.getCodePrintableID() + "_variant);")
  940. return code
  941. def printOpen62541CCode_Subtype(self, unPrintedReferences=[], bootstrapping = True):
  942. code = []
  943. codegen = open62541_MacroHelper()
  944. # Detect if this is bootstrapping or if we are attempting to use userspace...
  945. if bootstrapping == False:
  946. code.append(" " + self.getCodePrintableID() + "_variant, ")
  947. code.append(" // FIXME: missing minimumSamplingInterval")
  948. code.append(" // FIXME: missing accessLevel")
  949. code.append(" // FIXME: missing userAccessLevel")
  950. code.append(" // FIXME: missing valueRank")
  951. return code
  952. if self.historizing():
  953. code.append(self.getCodePrintableID() + "->historizing = true;")
  954. code.append(self.getCodePrintableID() + "->minimumSamplingInterval = (UA_Double) " + str(self.minimumSamplingInterval()) + ";")
  955. code.append(self.getCodePrintableID() + "->accessLevel = (UA_Int32) " + str(self.accessLevel()) + ";")
  956. code.append(self.getCodePrintableID() + "->valueRank = (UA_Int32) " + str(self.valueRank()) + ";")
  957. # The variant is guaranteed to exist by SubtypeEarly()
  958. code.append("UA_Variant_copy(" + self.getCodePrintableID() + "_variant, &" + self.getCodePrintableID() + "->value.data.value.value );")
  959. code.append(self.getCodePrintableID() + "->valueSource = UA_VALUESOURCE_DATA;")
  960. return code
  961. class opcua_node_method_t(opcua_node_t):
  962. __executable__ = True
  963. __userExecutable__ = True
  964. __methodDecalaration__ = None
  965. def __init_subType__(self):
  966. self.nodeClass(NODE_CLASS_METHOD)
  967. self.__executable__ = True
  968. self.__userExecutable__ = True
  969. self.__methodDecalaration__ = None
  970. def methodDeclaration(self, data=None):
  971. if not data==None:
  972. self.__methodDecalaration__ = data
  973. return self.__methodDecalaration__
  974. def executable(self, data=None):
  975. if isinstance(data, bool):
  976. self.__executable__ == data
  977. return self.__executable__
  978. def userExecutable(self, data=None):
  979. if isinstance(data, bool):
  980. self.__userExecutable__ == data
  981. return self.__userExecutable__
  982. def sanitizeSubType(self):
  983. if self.methodDeclaration() != None:
  984. if not isinstance(self.methodDeclaration().target(), opcua_node_t):
  985. return False
  986. else:
  987. #FIXME: Is this even permitted!?
  988. pass
  989. def parseXMLSubType(self, xmlelement):
  990. for (at, av) in xmlelement.attributes.items():
  991. if at == "MethodDeclarationId":
  992. self.methodDeclaration(opcua_referencePointer_t(str(av), parentNode=self))
  993. # dataType needs to be linked to a node once the namespace is read
  994. self.getNamespace().linkLater(self.methodDeclaration())
  995. else:
  996. logger.error("Don't know how to process attribute " + at + " (" + av + ")")
  997. for x in xmlelement.childNodes:
  998. if x.nodeType == x.ELEMENT_NODE:
  999. logger.info( "Unprocessable XML Element: " + x.tagName)
  1000. def printOpen62541CCode_Subtype(self, unPrintedReferences=[], bootstrapping = True):
  1001. code = []
  1002. # Detect if this is bootstrapping or if we are attempting to use userspace...
  1003. if bootstrapping == False:
  1004. code.append(" // Note: in/outputArguments are added by attaching the variable nodes,")
  1005. code.append(" // not by including the in the addMethodNode() call.")
  1006. code.append(" NULL,")
  1007. code.append(" NULL,")
  1008. code.append(" 0, NULL,")
  1009. code.append(" 0, NULL,")
  1010. code.append(" // FIXME: Missing executable")
  1011. code.append(" // FIXME: Missing userExecutable")
  1012. return code
  1013. # UA_False is default for booleans on _init()
  1014. if self.executable():
  1015. code.append(self.getCodePrintableID() + "->executable = true;")
  1016. return code
  1017. class opcua_node_objectType_t(opcua_node_t):
  1018. __isAbstract__ = False
  1019. def __init_subType__(self):
  1020. self.nodeClass(NODE_CLASS_OBJECTTYPE)
  1021. self.__isAbstract__ == False
  1022. def isAbstract(self, data=None):
  1023. if isinstance(data, bool):
  1024. self.__isAbstract__ = data
  1025. return self.__isAbstract__
  1026. def parseXMLSubType(self, xmlelement):
  1027. for (at, av) in xmlelement.attributes.items():
  1028. if at == "IsAbstract":
  1029. if "false" in av.lower():
  1030. self.isAbstract(False)
  1031. xmlelement.removeAttribute(at)
  1032. else:
  1033. logger.error("Don't know how to process attribute " + at + " (" + av + ")")
  1034. for x in xmlelement.childNodes:
  1035. if x.nodeType == x.ELEMENT_NODE:
  1036. logger.info( "Unprocessable XML Element: " + x.tagName)
  1037. def printOpen62541CCode_Subtype(self, unPrintedReferences=[], bootstrapping = True):
  1038. code = []
  1039. codegen = open62541_MacroHelper();
  1040. # Detect if this is bootstrapping or if we are attempting to use userspace...
  1041. if bootstrapping == False:
  1042. typeDefs = self.getNamespace().getSubTypesOf() # defaults to TypeDefinition
  1043. myTypeRef = None
  1044. for ref in self.getReferences():
  1045. if ref.referenceType() in typeDefs:
  1046. myTypeRef = ref
  1047. break
  1048. if myTypeRef==None:
  1049. for ref in self.getReferences():
  1050. if ref.referenceType().browseName() == "HasSubtype" and ref.isForward() == False:
  1051. myTypeRef = ref
  1052. break
  1053. if myTypeRef==None:
  1054. logger.warn(str(self) + " failed to locate a type definition, assuming BaseObjectType.")
  1055. code.append(" // No valid typeDefinition found; assuming BaseObjectType")
  1056. code.append(" UA_EXPANDEDNODEID_NUMERIC(0, UA_NS0ID_BASEOBJECTTYPE),")
  1057. else:
  1058. code.append(" " + codegen.getCreateExpandedNodeIDMacro(myTypeRef.target()) + ",")
  1059. while myTypeRef in unPrintedReferences:
  1060. code.append(" // removed " + str(myTypeRef))
  1061. unPrintedReferences.remove(myTypeRef)
  1062. if (self.isAbstract()):
  1063. code.append(" true,")
  1064. else:
  1065. code.append(" false,")
  1066. # Fallback mode for bootstrapping
  1067. if (self.isAbstract()):
  1068. code.append(self.getCodePrintableID() + "->isAbstract = true;")
  1069. return code
  1070. class opcua_node_variableType_t(opcua_node_t):
  1071. __value__ = 0
  1072. __dataType__ = None
  1073. __valueRank__ = 0
  1074. __arrayDimensions__ = 0
  1075. __isAbstract__ = False
  1076. __xmlDefinition__ = None
  1077. def __init_subType__(self):
  1078. self.nodeClass(NODE_CLASS_VARIABLETYPE)
  1079. self.__value__ = 0
  1080. self.__dataType__ = None
  1081. self.__valueRank__ = -1
  1082. self.__arrayDimensions__ = 0
  1083. self.__isAbstract__ = False
  1084. self.__xmlDefinition__ = None
  1085. def value(self, data=None):
  1086. logger.error("Setting data not implemented!")
  1087. def dataType(self, data=None):
  1088. if data != None:
  1089. self.__dataType__ = data
  1090. return self.__dataType__
  1091. def valueRank(self,data=None):
  1092. if isinstance(data, int):
  1093. self.__valueRank__ = data
  1094. return self.__valueRank__
  1095. def arrayDimensions(self,data=None):
  1096. if isinstance(data, int):
  1097. self.__arrayDimensions__ = data
  1098. return self.__arrayDimensions__
  1099. def isAbstract(self,data=None):
  1100. if isinstance(data, bool):
  1101. self.__isAbstract__ = data
  1102. return self.__isAbstract__
  1103. def sanitizeSubType(self):
  1104. # DataType fields appear to be optional for VariableTypes
  1105. # but if it does have a node set, it must obviously be a valid node
  1106. if not self.dataType() != None:
  1107. if not isinstance(self.dataType(), opcua_referencePointer_t):
  1108. logger.error("DataType attribute of " + str(self.id()) + " is not a pointer")
  1109. return False
  1110. else:
  1111. if not isinstance(self.dataType().target(), opcua_node_t):
  1112. logger.error("DataType attribute of " + str(self.id()) + " does not point to a node")
  1113. return False
  1114. else:
  1115. # FIXME: It's unclear wether this is ok or not.
  1116. logger.warn("DataType attribute of variableType " + str(self.id()) + " is not defined.")
  1117. return False
  1118. def parseXMLSubType(self, xmlelement):
  1119. for (at, av) in xmlelement.attributes.items():
  1120. if at == "IsAbstract":
  1121. if "false" in av.lower():
  1122. self.isAbstract(False)
  1123. else:
  1124. self.isAbstract(True)
  1125. xmlelement.removeAttribute(at)
  1126. elif at == "ValueRank":
  1127. self.valueRank(int(av))
  1128. if self.valueRank() != -1:
  1129. logger.warn("Array's or matrices are only permitted in variables and not supported for variableTypes. This attribute (" + at + "=" + av + ") will effectively be ignored.")
  1130. xmlelement.removeAttribute(at)
  1131. elif at == "DataType":
  1132. self.dataType(opcua_referencePointer_t(str(av), parentNode=self))
  1133. # dataType needs to be linked to a node once the namespace is read
  1134. self.getNamespace().linkLater(self.dataType())
  1135. else:
  1136. logger.error("Don't know how to process attribute " + at + " (" + av + ")")
  1137. for x in xmlelement.childNodes:
  1138. if x.nodeType == x.ELEMENT_NODE:
  1139. if x.tagName == "Definition":
  1140. self.__xmlDefinition__ = x
  1141. logger.debug( "Definition stored for future processing")
  1142. else:
  1143. logger.info( "Unprocessable XML Element: " + x.tagName)
  1144. def printOpen62541CCode_SubtypeEarly(self, bootstrapping = True):
  1145. code = []
  1146. # If we have an encodable value, try to encode that
  1147. if self.dataType() != None and isinstance(self.dataType().target(), opcua_node_dataType_t):
  1148. # Delegate the encoding of the datavalue to the helper if we have
  1149. # determined a valid encoding
  1150. if self.dataType().target().isEncodable():
  1151. if self.value() != None:
  1152. code = code + self.value().printOpen62541CCode(bootstrapping)
  1153. return code
  1154. if(bootstrapping):
  1155. code.append("UA_Variant *" + self.getCodePrintableID() + "_variant = (UA_Variant*)UA_alloca(sizeof(UA_Variant));")
  1156. code.append("UA_Variant_init(" + self.getCodePrintableID() + "_variant);")
  1157. return code
  1158. def printOpen62541CCode_Subtype(self, unPrintedReferences=[], bootstrapping = True):
  1159. code = []
  1160. codegen = open62541_MacroHelper()
  1161. if bootstrapping == False:
  1162. code.append(" " + self.getCodePrintableID() + "_variant, ")
  1163. code.append(" " + str(self.valueRank()) + ",")
  1164. if self.isAbstract():
  1165. code.append(" true,")
  1166. else:
  1167. code.append(" false,")
  1168. return code
  1169. if (self.isAbstract()):
  1170. code.append(self.getCodePrintableID() + "->isAbstract = true;")
  1171. else:
  1172. code.append(self.getCodePrintableID() + "->isAbstract = false;")
  1173. # The variant is guaranteed to exist by SubtypeEarly()
  1174. code.append("UA_Variant_copy(" + self.getCodePrintableID() + "_variant, &" + self.getCodePrintableID() + "->value.data.value.value );")
  1175. code.append(self.getCodePrintableID() + "->valueSource = UA_VALUESOURCE_DATA;")
  1176. return code
  1177. class opcua_node_dataType_t(opcua_node_t):
  1178. """ opcua_node_dataType_t is a subtype of opcua_note_t describing DataType nodes.
  1179. DataType contain definitions and structure information usable for Variables.
  1180. The format of this structure is determined by buildEncoding()
  1181. Two definition styles are distinguished in XML:
  1182. 1) A DataType can be a structure of fields, each field having a name and a type.
  1183. The type must be either an encodable builtin node (ex. UInt32) or point to
  1184. another DataType node that inherits its encoding from a builtin type using
  1185. a inverse "hasSubtype" (hasSuperType) reference.
  1186. 2) A DataType may be an enumeration, in which each field has a name and a numeric
  1187. value.
  1188. The definition is stored as an ordered list of tuples. Depending on which
  1189. definition style was used, the __definition__ will hold
  1190. 1) A list of ("Fieldname", opcua_node_t) tuples.
  1191. 2) A list of ("Fieldname", int) tuples.
  1192. A DataType (and in consequence all Variables using it) shall be deemed not
  1193. encodable if any of its fields cannot be traced to an encodable builtin type.
  1194. A DataType shall be further deemed not encodable if it contains mixed structure/
  1195. enumaration definitions.
  1196. If encodable, the encoding can be retrieved using getEncoding().
  1197. """
  1198. __isAbstract__ = False
  1199. __isEnum__ = False
  1200. __xmlDefinition__ = None
  1201. __baseTypeEncoding__ = []
  1202. __encodable__ = False
  1203. __encodingBuilt__ = False
  1204. __definition__ = []
  1205. def __init_subType__(self):
  1206. self.nodeClass(NODE_CLASS_DATATYPE)
  1207. self.__isAbstract__ == False
  1208. self.__xmlDefinition__ = None
  1209. self.__baseTypeEncoding__ = []
  1210. self.__encodable__ = None
  1211. self.__encodingBuilt__ = False
  1212. self.__definition__ = []
  1213. self.__isEnum__ = False
  1214. def isAbstract(self,data=None):
  1215. """ Will return True if isAbstract was defined.
  1216. Calling this function with an arbitrary data parameter will set
  1217. isAbstract = data.
  1218. """
  1219. if isinstance(data, bool):
  1220. self.__isAbstract__ = data
  1221. return self.__isAbstract__
  1222. def isEncodable(self):
  1223. """ Will return True if buildEncoding() was able to determine which builtin
  1224. type corresponds to all fields of this DataType.
  1225. If no encoding has been build yet, this function will call buildEncoding()
  1226. and return True if it succeeds.
  1227. """
  1228. return self.__encodable__
  1229. def getEncoding(self):
  1230. """ If the dataType is encodable, getEncoding() returns a nested list
  1231. containing the encoding the structure definition for this type.
  1232. If no encoding has been build yet, this function will call buildEncoding()
  1233. and return the encoding if buildEncoding() succeeds.
  1234. If buildEncoding() fails or has failed, an empty list will be returned.
  1235. """
  1236. if self.__encodable__ == False:
  1237. if self.__encodingBuilt__ == False:
  1238. return self.buildEncoding()
  1239. return []
  1240. else:
  1241. return self.__baseTypeEncoding__
  1242. def buildEncoding(self, indent=0, force=False):
  1243. """ buildEncoding() determines the structure and aliases used for variables
  1244. of this DataType.
  1245. The function will parse the XML <Definition> of the dataType and extract
  1246. "Name"-"Type" tuples. If successfull, buildEncoding will return a nested
  1247. list of the following format:
  1248. [['Alias1', ['Alias2', ['BuiltinType']]], [Alias2, ['BuiltinType']], ...]
  1249. Aliases are fieldnames defined by this DataType or DataTypes referenced. A
  1250. list such as ['DataPoint', ['Int32']] indicates that a value will encode
  1251. an Int32 with the alias 'DataPoint' such as <DataPoint>12827</DataPoint>.
  1252. Only the first Alias of a nested list is considered valid for the BuiltinType.
  1253. Single-Elemented lists are always BuiltinTypes. Every nested list must
  1254. converge in a builtin type to be encodable. buildEncoding will follow
  1255. the first type inheritance reference (hasSupertype) of the dataType if
  1256. necessary;
  1257. If instead to "DataType" a numeric "Value" attribute is encountered,
  1258. the DataType will be considered an enumeration and all Variables using
  1259. it will be encoded as Int32.
  1260. DataTypes can be either structures or enumeration - mixed definitions will
  1261. be unencodable.
  1262. Calls to getEncoding() will be iterative. buildEncoding() can be called
  1263. only once per dataType, with all following calls returning the predetermined
  1264. value. Use of the 'force=True' parameter will force the Definition to be
  1265. reparsed.
  1266. After parsing, __definition__ holds the field definition as a list. Note
  1267. that this might deviate from the encoding, especially if inheritance was
  1268. used.
  1269. """
  1270. proxy = opcua_value_t(None)
  1271. prefix = " " + "|"*indent+ "+"
  1272. if force==True:
  1273. self.__encodingBuilt__ = False
  1274. if self.__encodingBuilt__ == True:
  1275. if self.isEncodable():
  1276. logger.debug(prefix + str(self.__baseTypeEncoding__) + " (already analyzed)")
  1277. else:
  1278. logger.debug( prefix + str(self.__baseTypeEncoding__) + "(already analyzed, not encodable!)")
  1279. return self.__baseTypeEncoding__
  1280. self.__encodingBuilt__ = True # signify that we have attempted to built this type
  1281. self.__encodable__ = True
  1282. if indent==0:
  1283. logger.debug("Parsing DataType " + self.browseName() + " (" + str(self.id()) + ")")
  1284. if proxy.isBuiltinByString(self.browseName()):
  1285. self.__baseTypeEncoding__ = [self.browseName()]
  1286. self.__encodable__ = True
  1287. logger.debug( prefix + self.browseName() + "*")
  1288. logger.debug("Encodable as: " + str(self.__baseTypeEncoding__))
  1289. logger.debug("")
  1290. return self.__baseTypeEncoding__
  1291. if self.__xmlDefinition__ == None:
  1292. # Check if there is a supertype available
  1293. for ref in self.getReferences():
  1294. if "hassubtype" in ref.referenceType().browseName().lower() and ref.isForward() == False:
  1295. if isinstance(ref.target(), opcua_node_dataType_t):
  1296. logger.debug( prefix + "Attempting definition using supertype " + ref.target().browseName() + " for DataType " + " " + self.browseName())
  1297. subenc = ref.target().buildEncoding(indent=indent+1)
  1298. if not ref.target().isEncodable():
  1299. self.__encodable__ = False
  1300. break
  1301. else:
  1302. self.__baseTypeEncoding__ = self.__baseTypeEncoding__ + [self.browseName(), subenc, 0]
  1303. if len(self.__baseTypeEncoding__) == 0:
  1304. logger.debug(prefix + "No viable definition for " + self.browseName() + " " + str(self.id()) + " found.")
  1305. self.__encodable__ = False
  1306. if indent==0:
  1307. if not self.__encodable__:
  1308. logger.debug("Not encodable (partial): " + str(self.__baseTypeEncoding__))
  1309. else:
  1310. logger.debug("Encodable as: " + str(self.__baseTypeEncoding__))
  1311. logger.debug( "")
  1312. return self.__baseTypeEncoding__
  1313. isEnum = True
  1314. isSubType = True
  1315. hasValueRank = 0
  1316. # We need to store the definition as ordered data, but can't use orderedDict
  1317. # for backward compatibility with Python 2.6 and 3.4
  1318. enumDict = []
  1319. typeDict = []
  1320. # An XML Definition is provided and will be parsed... now
  1321. for x in self.__xmlDefinition__.childNodes:
  1322. if x.nodeType == x.ELEMENT_NODE:
  1323. fname = ""
  1324. fdtype = ""
  1325. enumVal = ""
  1326. hasValueRank = 0
  1327. for at,av in x.attributes.items():
  1328. if at == "DataType":
  1329. fdtype = str(av)
  1330. isEnum = False
  1331. elif at == "Name":
  1332. fname = str(av)
  1333. elif at == "Value":
  1334. enumVal = int(av)
  1335. isSubType = False
  1336. elif at == "ValueRank":
  1337. hasValueRank = int(av)
  1338. logger.warn("Arrays or matrices (ValueRank) are not supported for datatypes. This DT will become scalar.")
  1339. else:
  1340. logger.warn("Unknown Field Attribute " + str(at))
  1341. # This can either be an enumeration OR a structure, not both.
  1342. # Figure out which of the dictionaries gets the newly read value pair
  1343. if isEnum == isSubType:
  1344. # This is an error
  1345. logger.warn("DataType contains both enumeration and subtype (or neither)")
  1346. self.__encodable__ = False
  1347. break
  1348. elif isEnum:
  1349. # This is an enumeration
  1350. enumDict.append((fname, enumVal))
  1351. continue
  1352. else:
  1353. # This might be a subtype... follow the node defined as datatype to find out
  1354. # what encoding to use
  1355. dtnode = self.getNamespace().getNodeByIDString(fdtype)
  1356. if dtnode == None:
  1357. # Node found in datatype element is invalid
  1358. logger.debug( prefix + fname + " ?? " + av + " ??")
  1359. self.__encodable__ = False
  1360. else:
  1361. # The node in the datatype element was found. we inherit its encoding,
  1362. # but must still ensure that the dtnode is itself validly encodable
  1363. typeDict.append([fname, dtnode])
  1364. if hasValueRank < 0:
  1365. hasValueRank = 0
  1366. fdtype = str(dtnode.browseName()) + "+"*hasValueRank
  1367. logger.debug( prefix + fname + " : " + fdtype + " -> " + str(dtnode.id()))
  1368. subenc = dtnode.buildEncoding(indent=indent+1)
  1369. self.__baseTypeEncoding__ = self.__baseTypeEncoding__ + [[fname, subenc, hasValueRank]]
  1370. if not dtnode.isEncodable():
  1371. # If we inherit an encoding from an unencodable not, this node is
  1372. # also not encodable
  1373. self.__encodable__ = False
  1374. break
  1375. # If we used inheritance to determine an encoding without alias, there is a
  1376. # the possibility that lists got double-nested despite of only one element
  1377. # being encoded, such as [['Int32']] or [['alias',['int32']]]. Remove that
  1378. # enclosing list.
  1379. while len(self.__baseTypeEncoding__) == 1 and isinstance(self.__baseTypeEncoding__[0], list):
  1380. self.__baseTypeEncoding__ = self.__baseTypeEncoding__[0]
  1381. if isEnum == True:
  1382. self.__baseTypeEncoding__ = self.__baseTypeEncoding__ + ['Int32']
  1383. self.__definition__ = enumDict
  1384. self.__isEnum__ = True
  1385. logger.debug( prefix+"Int32* -> enumeration with dictionary " + str(enumDict) + " encodable " + str(self.__encodable__))
  1386. return self.__baseTypeEncoding__
  1387. if indent==0:
  1388. if not self.__encodable__:
  1389. logger.debug( "Not encodable (partial): " + str(self.__baseTypeEncoding__))
  1390. else:
  1391. logger.debug( "Encodable as: " + str(self.__baseTypeEncoding__))
  1392. self.__isEnum__ = False
  1393. self.__definition__ = typeDict
  1394. logger.debug( "")
  1395. return self.__baseTypeEncoding__
  1396. def parseXMLSubType(self, xmlelement):
  1397. """ Parses all XML data that is not considered part of the base node attributes.
  1398. XML attributes fields processed are "isAbstract"
  1399. XML elements processed are "Definition"
  1400. """
  1401. for (at, av) in xmlelement.attributes.items():
  1402. if at == "IsAbstract":
  1403. if "true" in str(av).lower():
  1404. self.isAbstract(True)
  1405. else:
  1406. self.isAbstract(False)
  1407. xmlelement.removeAttribute(at)
  1408. else:
  1409. logger.warn("Don't know how to process attribute " + at + " (" + av + ")")
  1410. for x in xmlelement.childNodes:
  1411. if x.nodeType == x.ELEMENT_NODE:
  1412. if x.tagName == "Definition":
  1413. self.__xmlDefinition__ = x
  1414. #logger.debug( "Definition stored for future processing")
  1415. else:
  1416. logger.warn( "Unprocessable XML Element: " + x.tagName)
  1417. def encodedTypeId(self):
  1418. """ Returns a number of the builtin Type that should be used
  1419. to represent this datatype.
  1420. """
  1421. if self.isEncodable() != True or len(self.getEncoding()) == 0:
  1422. # Encoding is []
  1423. return 0
  1424. else:
  1425. enc = self.getEncoding()
  1426. if len(enc) > 1 and isinstance(enc[0], list):
  1427. # [ [?], [?], [?] ]
  1428. # Encoding is a list representing an extensionobject
  1429. return opcua_BuiltinType_extensionObject_t(None).getNumericRepresentation()
  1430. else:
  1431. if len(enc)==1 and isinstance(enc[0], str):
  1432. # [ 'BuiltinType' ]
  1433. return opcua_value_t(None).getTypeByString(enc[0]).getNumericRepresentation()
  1434. else:
  1435. # [ ['Alias', [?]] ]
  1436. # Determine if [?] is reducable to a builtin type or if [?] is an aliased
  1437. # extensionobject
  1438. while len(enc) > 1 and isinstance(enc[0], str):
  1439. enc = enc[1]
  1440. if len(enc) > 1:
  1441. return opcua_BuiltinType_extensionObject_t(None).getNumericRepresentation()
  1442. else:
  1443. return opcua_value_t(None).getTypeByString(enc[0]).getNumericRepresentation()
  1444. def printOpen62541CCode_Subtype(self, unPrintedReferences=[], bootstrapping = True):
  1445. code = []
  1446. codegen = open62541_MacroHelper()
  1447. # Detect if this is bootstrapping or if we are attempting to use userspace...
  1448. if bootstrapping == False:
  1449. typeDefs = self.getNamespace().getSubTypesOf() # defaults to TypeDefinition
  1450. myTypeRef = None
  1451. for ref in self.getReferences():
  1452. if ref.referenceType() in typeDefs:
  1453. myTypeRef = ref
  1454. break
  1455. if myTypeRef==None:
  1456. for ref in self.getReferences():
  1457. if ref.referenceType().browseName() == "HasSubtype" and ref.isForward() == False:
  1458. myTypeRef = ref
  1459. break
  1460. if myTypeRef==None:
  1461. logger.warn(str(self) + " failed to locate a type definition, assuming BaseDataType.")
  1462. code.append(" // No valid typeDefinition found; assuming BaseDataType")
  1463. code.append(" UA_EXPANDEDNODEID_NUMERIC(0, UA_NS0ID_BASEDATATYPE),")
  1464. else:
  1465. code.append(" " + codegen.getCreateExpandedNodeIDMacro(myTypeRef.target()) + ",")
  1466. while myTypeRef in unPrintedReferences:
  1467. unPrintedReferences.remove(myTypeRef)
  1468. if (self.isAbstract()):
  1469. code.append(" true,")
  1470. else:
  1471. code.append(" false,")
  1472. return code
  1473. if (self.isAbstract()):
  1474. code.append(self.getCodePrintableID() + "->isAbstract = true;")
  1475. else:
  1476. code.append(self.getCodePrintableID() + "->isAbstract = false;")
  1477. return code
  1478. class opcua_node_view_t(opcua_node_t):
  1479. __containsNoLoops__ = True
  1480. __eventNotifier__ = 0
  1481. def __init_subType__(self):
  1482. self.nodeClass(NODE_CLASS_VIEW)
  1483. self.__containsNoLoops__ == False
  1484. self.__eventNotifier__ == False
  1485. def containsNoLoops(self,data=None):
  1486. if isinstance(data, bool):
  1487. self.__containsNoLoops__ = data
  1488. return self.__containsNoLoops__
  1489. def eventNotifier(self,data=None):
  1490. if isinstance(data, int):
  1491. self.__eventNotifier__ = data
  1492. return self.__eventNotifier__
  1493. def parseXMLSubtype(self, xmlelement):
  1494. for (at, av) in xmlelement.attributes.items():
  1495. logger.error("Don't know how to process attribute " + at + " (" + av + ")")
  1496. for x in xmlelement.childNodes:
  1497. if x.nodeType == x.ELEMENT_NODE:
  1498. logger.info( "Unprocessable XML Element: " + x.tagName)
  1499. def printOpen62541CCode_Subtype(self, unPrintedReferences=[], bootstrapping = True):
  1500. code = []
  1501. codegen = open62541_MacroHelper()
  1502. # Detect if this is bootstrapping or if we are attempting to use userspace...
  1503. if bootstrapping == False:
  1504. typeDefs = self.getNamespace().getSubTypesOf() # defaults to TypeDefinition
  1505. myTypeRef = None
  1506. for ref in self.getReferences():
  1507. if ref.referenceType() in typeDefs:
  1508. myTypeRef = ref
  1509. break
  1510. if myTypeRef==None:
  1511. for ref in self.getReferences():
  1512. if ref.referenceType().browseName() == "HasSubtype" and ref.isForward() == False:
  1513. myTypeRef = ref
  1514. break
  1515. if myTypeRef==None:
  1516. logger.warn(str(self) + " failed to locate a type definition, assuming BaseViewType.")
  1517. code.append(" // No valid typeDefinition found; assuming BaseViewType")
  1518. code.append(" UA_EXPANDEDNODEID_NUMERIC(0, UA_NS0ID_BASEViewTYPE),")
  1519. else:
  1520. code.append(" " + codegen.getCreateExpandedNodeIDMacro(myTypeRef.target()) + ",")
  1521. while myTypeRef in unPrintedReferences:
  1522. unPrintedReferences.remove(myTypeRef)
  1523. code.append(" // FIXME: Missing eventNotifier")
  1524. code.append(" // FIXME: Missing containsNoLoops")
  1525. return code
  1526. if self.containsNoLoops():
  1527. code.append(self.getCodePrintableID() + "->containsNoLoops = true;")
  1528. else:
  1529. code.append(self.getCodePrintableID() + "->containsNoLoops = false;")
  1530. code.append(self.getCodePrintableID() + "->eventNotifier = (UA_Byte) " + str(self.eventNotifier()) + ";")
  1531. return code