ua_node_types.py 67 KB

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