ua_node_types.py 67 KB

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