ua_node_types.py 67 KB

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