ua_node_types.py 66 KB

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