ua_node_types.py 66 KB

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