ua_node_types.py 66 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774
  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() + "->accessLevel = (UA_Int32) " + str(self.accessLevel()) + ";")
  959. code.append(self.getCodePrintableID() + "->valueRank = (UA_Int32) " + str(self.valueRank()) + ";")
  960. # The variant is guaranteed to exist by SubtypeEarly()
  961. code.append("UA_Variant_copy(" + self.getCodePrintableID() + "_variant, &" + self.getCodePrintableID() + "->value.data.value.value );")
  962. code.append(self.getCodePrintableID() + "->valueSource = UA_VALUESOURCE_DATA;")
  963. return code
  964. class opcua_node_method_t(opcua_node_t):
  965. __executable__ = True
  966. __userExecutable__ = True
  967. __methodDecalaration__ = None
  968. def __init_subType__(self):
  969. self.nodeClass(NODE_CLASS_METHOD)
  970. self.__executable__ = True
  971. self.__userExecutable__ = True
  972. self.__methodDecalaration__ = None
  973. def methodDeclaration(self, data=None):
  974. if not data==None:
  975. self.__methodDecalaration__ = data
  976. return self.__methodDecalaration__
  977. def executable(self, data=None):
  978. if isinstance(data, bool):
  979. self.__executable__ == data
  980. return self.__executable__
  981. def userExecutable(self, data=None):
  982. if isinstance(data, bool):
  983. self.__userExecutable__ == data
  984. return self.__userExecutable__
  985. def sanitizeSubType(self):
  986. if self.methodDeclaration() != None:
  987. if not isinstance(self.methodDeclaration().target(), opcua_node_t):
  988. return False
  989. else:
  990. #FIXME: Is this even permitted!?
  991. pass
  992. def parseXMLSubType(self, xmlelement):
  993. for (at, av) in xmlelement.attributes.items():
  994. if at == "MethodDeclarationId":
  995. self.methodDeclaration(opcua_referencePointer_t(str(av), parentNode=self))
  996. # dataType needs to be linked to a node once the namespace is read
  997. self.getNamespace().linkLater(self.methodDeclaration())
  998. else:
  999. logger.error("Don't know how to process attribute " + at + " (" + av + ")")
  1000. for x in xmlelement.childNodes:
  1001. if x.nodeType == x.ELEMENT_NODE:
  1002. logger.info( "Unprocessable XML Element: " + x.tagName)
  1003. def printOpen62541CCode_Subtype(self, unPrintedReferences=[], bootstrapping = True):
  1004. code = []
  1005. # Detect if this is bootstrapping or if we are attempting to use userspace...
  1006. if bootstrapping == False:
  1007. code.append(" // Note: in/outputArguments are added by attaching the variable nodes,")
  1008. code.append(" // not by including the in the addMethodNode() call.")
  1009. code.append(" NULL,")
  1010. code.append(" NULL,")
  1011. code.append(" 0, NULL,")
  1012. code.append(" 0, NULL,")
  1013. code.append(" // FIXME: Missing executable")
  1014. code.append(" // FIXME: Missing userExecutable")
  1015. return code
  1016. # UA_False is default for booleans on _init()
  1017. if self.executable():
  1018. code.append(self.getCodePrintableID() + "->executable = true;")
  1019. return code
  1020. class opcua_node_objectType_t(opcua_node_t):
  1021. __isAbstract__ = False
  1022. def __init_subType__(self):
  1023. self.nodeClass(NODE_CLASS_OBJECTTYPE)
  1024. self.__isAbstract__ == False
  1025. def isAbstract(self, data=None):
  1026. if isinstance(data, bool):
  1027. self.__isAbstract__ = data
  1028. return self.__isAbstract__
  1029. def parseXMLSubType(self, xmlelement):
  1030. for (at, av) in xmlelement.attributes.items():
  1031. if at == "IsAbstract":
  1032. if "false" in av.lower():
  1033. self.isAbstract(False)
  1034. xmlelement.removeAttribute(at)
  1035. else:
  1036. logger.error("Don't know how to process attribute " + at + " (" + av + ")")
  1037. for x in xmlelement.childNodes:
  1038. if x.nodeType == x.ELEMENT_NODE:
  1039. logger.info( "Unprocessable XML Element: " + x.tagName)
  1040. def printOpen62541CCode_Subtype(self, unPrintedReferences=[], bootstrapping = True):
  1041. code = []
  1042. codegen = open62541_MacroHelper();
  1043. # Detect if this is bootstrapping or if we are attempting to use userspace...
  1044. if bootstrapping == False:
  1045. typeDefs = self.getNamespace().getSubTypesOf() # defaults to TypeDefinition
  1046. myTypeRef = None
  1047. for ref in self.getReferences():
  1048. if ref.referenceType() in typeDefs:
  1049. myTypeRef = ref
  1050. break
  1051. if myTypeRef==None:
  1052. for ref in self.getReferences():
  1053. if ref.referenceType().browseName() == "HasSubtype" and ref.isForward() == False:
  1054. myTypeRef = ref
  1055. break
  1056. if myTypeRef==None:
  1057. logger.warn(str(self) + " failed to locate a type definition, assuming BaseObjectType.")
  1058. code.append(" // No valid typeDefinition found; assuming BaseObjectType")
  1059. code.append(" UA_EXPANDEDNODEID_NUMERIC(0, UA_NS0ID_BASEOBJECTTYPE),")
  1060. else:
  1061. code.append(" " + codegen.getCreateExpandedNodeIDMacro(myTypeRef.target()) + ",")
  1062. while myTypeRef in unPrintedReferences:
  1063. code.append(" // removed " + str(myTypeRef))
  1064. unPrintedReferences.remove(myTypeRef)
  1065. if (self.isAbstract()):
  1066. code.append(" true,")
  1067. else:
  1068. code.append(" false,")
  1069. # Fallback mode for bootstrapping
  1070. if (self.isAbstract()):
  1071. code.append(self.getCodePrintableID() + "->isAbstract = true;")
  1072. return code
  1073. class opcua_node_variableType_t(opcua_node_t):
  1074. __value__ = 0
  1075. __dataType__ = None
  1076. __valueRank__ = 0
  1077. __arrayDimensions__ = 0
  1078. __isAbstract__ = False
  1079. __xmlDefinition__ = None
  1080. def __init_subType__(self):
  1081. self.nodeClass(NODE_CLASS_VARIABLETYPE)
  1082. self.__value__ = 0
  1083. self.__dataType__ = None
  1084. self.__valueRank__ = -1
  1085. self.__arrayDimensions__ = 0
  1086. self.__isAbstract__ = False
  1087. self.__xmlDefinition__ = None
  1088. def value(self, data=None):
  1089. logger.error("Setting data not implemented!")
  1090. def dataType(self, data=None):
  1091. if data != None:
  1092. self.__dataType__ = data
  1093. return self.__dataType__
  1094. def valueRank(self,data=None):
  1095. if isinstance(data, int):
  1096. self.__valueRank__ = data
  1097. return self.__valueRank__
  1098. def arrayDimensions(self,data=None):
  1099. if isinstance(data, int):
  1100. self.__arrayDimensions__ = data
  1101. return self.__arrayDimensions__
  1102. def isAbstract(self,data=None):
  1103. if isinstance(data, bool):
  1104. self.__isAbstract__ = data
  1105. return self.__isAbstract__
  1106. def sanitizeSubType(self):
  1107. # DataType fields appear to be optional for VariableTypes
  1108. # but if it does have a node set, it must obviously be a valid node
  1109. if not self.dataType() != None:
  1110. if not isinstance(self.dataType(), opcua_referencePointer_t):
  1111. logger.error("DataType attribute of " + str(self.id()) + " is not a pointer")
  1112. return False
  1113. else:
  1114. if not isinstance(self.dataType().target(), opcua_node_t):
  1115. logger.error("DataType attribute of " + str(self.id()) + " does not point to a node")
  1116. return False
  1117. else:
  1118. # FIXME: It's unclear wether this is ok or not.
  1119. logger.warn("DataType attribute of variableType " + str(self.id()) + " is not defined.")
  1120. return False
  1121. def parseXMLSubType(self, xmlelement):
  1122. for (at, av) in xmlelement.attributes.items():
  1123. if at == "IsAbstract":
  1124. if "false" in av.lower():
  1125. self.isAbstract(False)
  1126. else:
  1127. self.isAbstract(True)
  1128. xmlelement.removeAttribute(at)
  1129. elif at == "ValueRank":
  1130. self.valueRank(int(av))
  1131. if self.valueRank() != -1:
  1132. logger.warn("Array's or matrices are only permitted in variables and not supported for variableTypes. This attribute (" + at + "=" + av + ") will effectively be ignored.")
  1133. xmlelement.removeAttribute(at)
  1134. elif at == "DataType":
  1135. self.dataType(opcua_referencePointer_t(str(av), parentNode=self))
  1136. # dataType needs to be linked to a node once the namespace is read
  1137. self.getNamespace().linkLater(self.dataType())
  1138. else:
  1139. logger.error("Don't know how to process attribute " + at + " (" + av + ")")
  1140. for x in xmlelement.childNodes:
  1141. if x.nodeType == x.ELEMENT_NODE:
  1142. if x.tagName == "Definition":
  1143. self.__xmlDefinition__ = x
  1144. logger.debug( "Definition stored for future processing")
  1145. else:
  1146. logger.info( "Unprocessable XML Element: " + x.tagName)
  1147. def printOpen62541CCode_SubtypeEarly(self, bootstrapping = True):
  1148. code = []
  1149. # If we have an encodable value, try to encode that
  1150. if self.dataType() != None and isinstance(self.dataType().target(), opcua_node_dataType_t):
  1151. # Delegate the encoding of the datavalue to the helper if we have
  1152. # determined a valid encoding
  1153. if self.dataType().target().isEncodable():
  1154. if self.value() != None:
  1155. code = code + self.value().printOpen62541CCode(bootstrapping)
  1156. return code
  1157. if(bootstrapping):
  1158. code.append("UA_Variant *" + self.getCodePrintableID() + "_variant = UA_alloca(sizeof(UA_Variant));")
  1159. code.append("UA_Variant_init(" + self.getCodePrintableID() + "_variant);")
  1160. return code
  1161. def printOpen62541CCode_Subtype(self, unPrintedReferences=[], bootstrapping = True):
  1162. code = []
  1163. codegen = open62541_MacroHelper()
  1164. if bootstrapping == False:
  1165. code.append(" " + self.getCodePrintableID() + "_variant, ")
  1166. code.append(" " + str(self.valueRank()) + ",")
  1167. if self.isAbstract():
  1168. code.append(" true,")
  1169. else:
  1170. code.append(" false,")
  1171. return code
  1172. if (self.isAbstract()):
  1173. code.append(self.getCodePrintableID() + "->isAbstract = true;")
  1174. else:
  1175. code.append(self.getCodePrintableID() + "->isAbstract = false;")
  1176. # The variant is guaranteed to exist by SubtypeEarly()
  1177. code.append("UA_Variant_copy(" + self.getCodePrintableID() + "_variant, &" + self.getCodePrintableID() + "->value.data.value.value );")
  1178. code.append(self.getCodePrintableID() + "->valueSource = UA_VALUESOURCE_DATA;")
  1179. return code
  1180. class opcua_node_dataType_t(opcua_node_t):
  1181. """ opcua_node_dataType_t is a subtype of opcua_note_t describing DataType nodes.
  1182. DataType contain definitions and structure information usable for Variables.
  1183. The format of this structure is determined by buildEncoding()
  1184. Two definition styles are distinguished in XML:
  1185. 1) A DataType can be a structure of fields, each field having a name and a type.
  1186. The type must be either an encodable builtin node (ex. UInt32) or point to
  1187. another DataType node that inherits its encoding from a builtin type using
  1188. a inverse "hasSubtype" (hasSuperType) reference.
  1189. 2) A DataType may be an enumeration, in which each field has a name and a numeric
  1190. value.
  1191. The definition is stored as an ordered list of tuples. Depending on which
  1192. definition style was used, the __definition__ will hold
  1193. 1) A list of ("Fieldname", opcua_node_t) tuples.
  1194. 2) A list of ("Fieldname", int) tuples.
  1195. A DataType (and in consequence all Variables using it) shall be deemed not
  1196. encodable if any of its fields cannot be traced to an encodable builtin type.
  1197. A DataType shall be further deemed not encodable if it contains mixed structure/
  1198. enumaration definitions.
  1199. If encodable, the encoding can be retrieved using getEncoding().
  1200. """
  1201. __isAbstract__ = False
  1202. __isEnum__ = False
  1203. __xmlDefinition__ = None
  1204. __baseTypeEncoding__ = []
  1205. __encodable__ = False
  1206. __encodingBuilt__ = False
  1207. __definition__ = []
  1208. def __init_subType__(self):
  1209. self.nodeClass(NODE_CLASS_DATATYPE)
  1210. self.__isAbstract__ == False
  1211. self.__xmlDefinition__ = None
  1212. self.__baseTypeEncoding__ = []
  1213. self.__encodable__ = None
  1214. self.__encodingBuilt__ = False
  1215. self.__definition__ = []
  1216. self.__isEnum__ = False
  1217. def isAbstract(self,data=None):
  1218. """ Will return True if isAbstract was defined.
  1219. Calling this function with an arbitrary data parameter will set
  1220. isAbstract = data.
  1221. """
  1222. if isinstance(data, bool):
  1223. self.__isAbstract__ = data
  1224. return self.__isAbstract__
  1225. def isEncodable(self):
  1226. """ Will return True if buildEncoding() was able to determine which builtin
  1227. type corresponds to all fields of this DataType.
  1228. If no encoding has been build yet, this function will call buildEncoding()
  1229. and return True if it succeeds.
  1230. """
  1231. return self.__encodable__
  1232. def getEncoding(self):
  1233. """ If the dataType is encodable, getEncoding() returns a nested list
  1234. containing the encoding the structure definition for this type.
  1235. If no encoding has been build yet, this function will call buildEncoding()
  1236. and return the encoding if buildEncoding() succeeds.
  1237. If buildEncoding() fails or has failed, an empty list will be returned.
  1238. """
  1239. if self.__encodable__ == False:
  1240. if self.__encodingBuilt__ == False:
  1241. return self.buildEncoding()
  1242. return []
  1243. else:
  1244. return self.__baseTypeEncoding__
  1245. def buildEncoding(self, indent=0, force=False):
  1246. """ buildEncoding() determines the structure and aliases used for variables
  1247. of this DataType.
  1248. The function will parse the XML <Definition> of the dataType and extract
  1249. "Name"-"Type" tuples. If successfull, buildEncoding will return a nested
  1250. list of the following format:
  1251. [['Alias1', ['Alias2', ['BuiltinType']]], [Alias2, ['BuiltinType']], ...]
  1252. Aliases are fieldnames defined by this DataType or DataTypes referenced. A
  1253. list such as ['DataPoint', ['Int32']] indicates that a value will encode
  1254. an Int32 with the alias 'DataPoint' such as <DataPoint>12827</DataPoint>.
  1255. Only the first Alias of a nested list is considered valid for the BuiltinType.
  1256. Single-Elemented lists are always BuiltinTypes. Every nested list must
  1257. converge in a builtin type to be encodable. buildEncoding will follow
  1258. the first type inheritance reference (hasSupertype) of the dataType if
  1259. necessary;
  1260. If instead to "DataType" a numeric "Value" attribute is encountered,
  1261. the DataType will be considered an enumeration and all Variables using
  1262. it will be encoded as Int32.
  1263. DataTypes can be either structures or enumeration - mixed definitions will
  1264. be unencodable.
  1265. Calls to getEncoding() will be iterative. buildEncoding() can be called
  1266. only once per dataType, with all following calls returning the predetermined
  1267. value. Use of the 'force=True' parameter will force the Definition to be
  1268. reparsed.
  1269. After parsing, __definition__ holds the field definition as a list. Note
  1270. that this might deviate from the encoding, especially if inheritance was
  1271. used.
  1272. """
  1273. proxy = opcua_value_t(None)
  1274. prefix = " " + "|"*indent+ "+"
  1275. if force==True:
  1276. self.__encodingBuilt__ = False
  1277. if self.__encodingBuilt__ == True:
  1278. if self.isEncodable():
  1279. logger.debug(prefix + str(self.__baseTypeEncoding__) + " (already analyzed)")
  1280. else:
  1281. logger.debug( prefix + str(self.__baseTypeEncoding__) + "(already analyzed, not encodable!)")
  1282. return self.__baseTypeEncoding__
  1283. self.__encodingBuilt__ = True # signify that we have attempted to built this type
  1284. self.__encodable__ = True
  1285. if indent==0:
  1286. logger.debug("Parsing DataType " + self.browseName() + " (" + str(self.id()) + ")")
  1287. if proxy.isBuiltinByString(self.browseName()):
  1288. self.__baseTypeEncoding__ = [self.browseName()]
  1289. self.__encodable__ = True
  1290. logger.debug( prefix + self.browseName() + "*")
  1291. logger.debug("Encodable as: " + str(self.__baseTypeEncoding__))
  1292. logger.debug("")
  1293. return self.__baseTypeEncoding__
  1294. if self.__xmlDefinition__ == None:
  1295. # Check if there is a supertype available
  1296. for ref in self.getReferences():
  1297. if "hassubtype" in ref.referenceType().browseName().lower() and ref.isForward() == False:
  1298. if isinstance(ref.target(), opcua_node_dataType_t):
  1299. logger.debug( prefix + "Attempting definition using supertype " + ref.target().browseName() + " for DataType " + " " + self.browseName())
  1300. subenc = ref.target().buildEncoding(indent=indent+1)
  1301. if not ref.target().isEncodable():
  1302. self.__encodable__ = False
  1303. break
  1304. else:
  1305. self.__baseTypeEncoding__ = self.__baseTypeEncoding__ + [self.browseName(), subenc, 0]
  1306. if len(self.__baseTypeEncoding__) == 0:
  1307. logger.debug(prefix + "No viable definition for " + self.browseName() + " " + str(self.id()) + " found.")
  1308. self.__encodable__ = False
  1309. if indent==0:
  1310. if not self.__encodable__:
  1311. logger.debug("Not encodable (partial): " + str(self.__baseTypeEncoding__))
  1312. else:
  1313. logger.debug("Encodable as: " + str(self.__baseTypeEncoding__))
  1314. logger.debug( "")
  1315. return self.__baseTypeEncoding__
  1316. isEnum = True
  1317. isSubType = True
  1318. hasValueRank = 0
  1319. # We need to store the definition as ordered data, but can't use orderedDict
  1320. # for backward compatibility with Python 2.6 and 3.4
  1321. enumDict = []
  1322. typeDict = []
  1323. # An XML Definition is provided and will be parsed... now
  1324. for x in self.__xmlDefinition__.childNodes:
  1325. if x.nodeType == x.ELEMENT_NODE:
  1326. fname = ""
  1327. fdtype = ""
  1328. enumVal = ""
  1329. hasValueRank = 0
  1330. for at,av in x.attributes.items():
  1331. if at == "DataType":
  1332. fdtype = str(av)
  1333. isEnum = False
  1334. elif at == "Name":
  1335. fname = str(av)
  1336. elif at == "Value":
  1337. enumVal = int(av)
  1338. isSubType = False
  1339. elif at == "ValueRank":
  1340. hasValueRank = int(av)
  1341. logger.warn("Arrays or matrices (ValueRank) are not supported for datatypes. This DT will become scalar.")
  1342. else:
  1343. logger.warn("Unknown Field Attribute " + str(at))
  1344. # This can either be an enumeration OR a structure, not both.
  1345. # Figure out which of the dictionaries gets the newly read value pair
  1346. if isEnum == isSubType:
  1347. # This is an error
  1348. logger.warn("DataType contains both enumeration and subtype (or neither)")
  1349. self.__encodable__ = False
  1350. break
  1351. elif isEnum:
  1352. # This is an enumeration
  1353. enumDict.append((fname, enumVal))
  1354. continue
  1355. else:
  1356. # This might be a subtype... follow the node defined as datatype to find out
  1357. # what encoding to use
  1358. dtnode = self.getNamespace().getNodeByIDString(fdtype)
  1359. if dtnode == None:
  1360. # Node found in datatype element is invalid
  1361. logger.debug( prefix + fname + " ?? " + av + " ??")
  1362. self.__encodable__ = False
  1363. else:
  1364. # The node in the datatype element was found. we inherit its encoding,
  1365. # but must still ensure that the dtnode is itself validly encodable
  1366. typeDict.append([fname, dtnode])
  1367. if hasValueRank < 0:
  1368. hasValueRank = 0
  1369. fdtype = str(dtnode.browseName()) + "+"*hasValueRank
  1370. logger.debug( prefix + fname + " : " + fdtype + " -> " + str(dtnode.id()))
  1371. subenc = dtnode.buildEncoding(indent=indent+1)
  1372. self.__baseTypeEncoding__ = self.__baseTypeEncoding__ + [[fname, subenc, hasValueRank]]
  1373. if not dtnode.isEncodable():
  1374. # If we inherit an encoding from an unencodable not, this node is
  1375. # also not encodable
  1376. self.__encodable__ = False
  1377. break
  1378. # If we used inheritance to determine an encoding without alias, there is a
  1379. # the possibility that lists got double-nested despite of only one element
  1380. # being encoded, such as [['Int32']] or [['alias',['int32']]]. Remove that
  1381. # enclosing list.
  1382. while len(self.__baseTypeEncoding__) == 1 and isinstance(self.__baseTypeEncoding__[0], list):
  1383. self.__baseTypeEncoding__ = self.__baseTypeEncoding__[0]
  1384. if isEnum == True:
  1385. self.__baseTypeEncoding__ = self.__baseTypeEncoding__ + ['Int32']
  1386. self.__definition__ = enumDict
  1387. self.__isEnum__ = True
  1388. logger.debug( prefix+"Int32* -> enumeration with dictionary " + str(enumDict) + " encodable " + str(self.__encodable__))
  1389. return self.__baseTypeEncoding__
  1390. if indent==0:
  1391. if not self.__encodable__:
  1392. logger.debug( "Not encodable (partial): " + str(self.__baseTypeEncoding__))
  1393. else:
  1394. logger.debug( "Encodable as: " + str(self.__baseTypeEncoding__))
  1395. self.__isEnum__ = False
  1396. self.__definition__ = typeDict
  1397. logger.debug( "")
  1398. return self.__baseTypeEncoding__
  1399. def parseXMLSubType(self, xmlelement):
  1400. """ Parses all XML data that is not considered part of the base node attributes.
  1401. XML attributes fields processed are "isAbstract"
  1402. XML elements processed are "Definition"
  1403. """
  1404. for (at, av) in xmlelement.attributes.items():
  1405. if at == "IsAbstract":
  1406. if "true" in str(av).lower():
  1407. self.isAbstract(True)
  1408. else:
  1409. self.isAbstract(False)
  1410. xmlelement.removeAttribute(at)
  1411. else:
  1412. logger.warn("Don't know how to process attribute " + at + " (" + av + ")")
  1413. for x in xmlelement.childNodes:
  1414. if x.nodeType == x.ELEMENT_NODE:
  1415. if x.tagName == "Definition":
  1416. self.__xmlDefinition__ = x
  1417. #logger.debug( "Definition stored for future processing")
  1418. else:
  1419. logger.warn( "Unprocessable XML Element: " + x.tagName)
  1420. def encodedTypeId(self):
  1421. """ Returns a number of the builtin Type that should be used
  1422. to represent this datatype.
  1423. """
  1424. if self.isEncodable() != True or len(self.getEncoding()) == 0:
  1425. # Encoding is []
  1426. return 0
  1427. else:
  1428. enc = self.getEncoding()
  1429. if len(enc) > 1 and isinstance(enc[0], list):
  1430. # [ [?], [?], [?] ]
  1431. # Encoding is a list representing an extensionobject
  1432. return opcua_BuiltinType_extensionObject_t(None).getNumericRepresentation()
  1433. else:
  1434. if len(enc)==1 and isinstance(enc[0], str):
  1435. # [ 'BuiltinType' ]
  1436. return opcua_value_t(None).getTypeByString(enc[0]).getNumericRepresentation()
  1437. else:
  1438. # [ ['Alias', [?]] ]
  1439. # Determine if [?] is reducable to a builtin type or if [?] is an aliased
  1440. # extensionobject
  1441. while len(enc) > 1 and isinstance(enc[0], str):
  1442. enc = enc[1]
  1443. if len(enc) > 1:
  1444. return opcua_BuiltinType_extensionObject_t(None).getNumericRepresentation()
  1445. else:
  1446. return opcua_value_t(None).getTypeByString(enc[0]).getNumericRepresentation()
  1447. def printOpen62541CCode_Subtype(self, unPrintedReferences=[], bootstrapping = True):
  1448. code = []
  1449. codegen = open62541_MacroHelper()
  1450. # Detect if this is bootstrapping or if we are attempting to use userspace...
  1451. if bootstrapping == False:
  1452. typeDefs = self.getNamespace().getSubTypesOf() # defaults to TypeDefinition
  1453. myTypeRef = None
  1454. for ref in self.getReferences():
  1455. if ref.referenceType() in typeDefs:
  1456. myTypeRef = ref
  1457. break
  1458. if myTypeRef==None:
  1459. for ref in self.getReferences():
  1460. if ref.referenceType().browseName() == "HasSubtype" and ref.isForward() == False:
  1461. myTypeRef = ref
  1462. break
  1463. if myTypeRef==None:
  1464. logger.warn(str(self) + " failed to locate a type definition, assuming BaseDataType.")
  1465. code.append(" // No valid typeDefinition found; assuming BaseDataType")
  1466. code.append(" UA_EXPANDEDNODEID_NUMERIC(0, UA_NS0ID_BASEDATATYPE),")
  1467. else:
  1468. code.append(" " + codegen.getCreateExpandedNodeIDMacro(myTypeRef.target()) + ",")
  1469. while myTypeRef in unPrintedReferences:
  1470. unPrintedReferences.remove(myTypeRef)
  1471. if (self.isAbstract()):
  1472. code.append(" true,")
  1473. else:
  1474. code.append(" false,")
  1475. return code
  1476. if (self.isAbstract()):
  1477. code.append(self.getCodePrintableID() + "->isAbstract = true;")
  1478. else:
  1479. code.append(self.getCodePrintableID() + "->isAbstract = false;")
  1480. return code
  1481. class opcua_node_view_t(opcua_node_t):
  1482. __containsNoLoops__ = True
  1483. __eventNotifier__ = 0
  1484. def __init_subType__(self):
  1485. self.nodeClass(NODE_CLASS_VIEW)
  1486. self.__containsNoLoops__ == False
  1487. self.__eventNotifier__ == False
  1488. def containsNoLoops(self,data=None):
  1489. if isinstance(data, bool):
  1490. self.__containsNoLoops__ = data
  1491. return self.__containsNoLoops__
  1492. def eventNotifier(self,data=None):
  1493. if isinstance(data, int):
  1494. self.__eventNotifier__ = data
  1495. return self.__eventNotifier__
  1496. def parseXMLSubtype(self, xmlelement):
  1497. for (at, av) in xmlelement.attributes.items():
  1498. logger.error("Don't know how to process attribute " + at + " (" + av + ")")
  1499. for x in xmlelement.childNodes:
  1500. if x.nodeType == x.ELEMENT_NODE:
  1501. logger.info( "Unprocessable XML Element: " + x.tagName)
  1502. def printOpen62541CCode_Subtype(self, unPrintedReferences=[], bootstrapping = True):
  1503. code = []
  1504. codegen = open62541_MacroHelper()
  1505. # Detect if this is bootstrapping or if we are attempting to use userspace...
  1506. if bootstrapping == False:
  1507. typeDefs = self.getNamespace().getSubTypesOf() # defaults to TypeDefinition
  1508. myTypeRef = None
  1509. for ref in self.getReferences():
  1510. if ref.referenceType() in typeDefs:
  1511. myTypeRef = ref
  1512. break
  1513. if myTypeRef==None:
  1514. for ref in self.getReferences():
  1515. if ref.referenceType().browseName() == "HasSubtype" and ref.isForward() == False:
  1516. myTypeRef = ref
  1517. break
  1518. if myTypeRef==None:
  1519. logger.warn(str(self) + " failed to locate a type definition, assuming BaseViewType.")
  1520. code.append(" // No valid typeDefinition found; assuming BaseViewType")
  1521. code.append(" UA_EXPANDEDNODEID_NUMERIC(0, UA_NS0ID_BASEViewTYPE),")
  1522. else:
  1523. code.append(" " + codegen.getCreateExpandedNodeIDMacro(myTypeRef.target()) + ",")
  1524. while myTypeRef in unPrintedReferences:
  1525. unPrintedReferences.remove(myTypeRef)
  1526. code.append(" // FIXME: Missing eventNotifier")
  1527. code.append(" // FIXME: Missing containsNoLoops")
  1528. return code
  1529. if self.containsNoLoops():
  1530. code.append(self.getCodePrintableID() + "->containsNoLoops = true;")
  1531. else:
  1532. code.append(self.getCodePrintableID() + "->containsNoLoops = false;")
  1533. code.append(self.getCodePrintableID() + "->eventNotifier = (UA_Byte) " + str(self.eventNotifier()) + ";")
  1534. return code