datatypes.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731
  1. #!/usr/bin/env/python
  2. # -*- coding: utf-8 -*-
  3. ###
  4. ### Author: Chris Iatrou (ichrispa@core-vector.net)
  5. ### Version: rev 13
  6. ###
  7. ### This program was created for educational purposes and has been
  8. ### contributed to the open62541 project by the author. All licensing
  9. ### terms for this source is inherited by the terms and conditions
  10. ### specified for by the open62541 project (see the projects readme
  11. ### file for more information on the LGPL terms and restrictions).
  12. ###
  13. ### This program is not meant to be used in a production environment. The
  14. ### author is not liable for any complications arising due to the use of
  15. ### this program.
  16. ###
  17. import sys
  18. import logging
  19. from datetime import datetime
  20. logger = logging.getLogger(__name__)
  21. import xml.dom.minidom as dom
  22. from constants import *
  23. from base64 import *
  24. import six
  25. if sys.version_info[0] >= 3:
  26. # strings are already parsed to unicode
  27. def unicode(s):
  28. return s
  29. def getNextElementNode(xmlvalue):
  30. if xmlvalue == None:
  31. return None
  32. xmlvalue = xmlvalue.nextSibling
  33. while not xmlvalue == None and not xmlvalue.nodeType == xmlvalue.ELEMENT_NODE:
  34. xmlvalue = xmlvalue.nextSibling
  35. return xmlvalue
  36. def valueIsInternalType(valueTypeString):
  37. return valueTypeString.lower() in ['boolean', 'number', 'int32', 'uint32', 'int16', 'uint16',
  38. 'int64', 'uint64', 'byte', 'sbyte', 'float', 'double',
  39. 'string', 'bytestring', 'localizedtext', 'statuscode',
  40. 'diagnosticinfo', 'nodeid', 'guid', 'datetime',
  41. 'qualifiedname', 'expandednodeid', 'xmlelement', 'integer', 'uinteger']
  42. class Value(object):
  43. def __init__(self, xmlelement=None):
  44. self.value = None
  45. self.numericRepresentation = 0
  46. self.alias = None
  47. self.dataType = None
  48. self.encodingRule = []
  49. self.isInternal = False
  50. if xmlelement:
  51. self.parseXML(xmlelement)
  52. def getValueFieldByAlias(self, fieldname):
  53. if not isinstance(self.value, list):
  54. return None
  55. if not isinstance(self.value[0], Value):
  56. return None
  57. for val in self.value:
  58. if val.alias() == fieldname:
  59. return val.value
  60. return None
  61. def getTypeByString(self, stringName, encodingRule):
  62. stringName = str(stringName.lower())
  63. if stringName == 'boolean':
  64. t = Boolean()
  65. elif stringName == 'number':
  66. t = Number()
  67. elif stringName == 'integer':
  68. t = Integer()
  69. elif stringName == 'uinteger':
  70. t = UInteger()
  71. elif stringName == 'int32':
  72. t = Int32()
  73. elif stringName == 'uint32':
  74. t = UInt32()
  75. elif stringName == 'int16':
  76. t = Int16()
  77. elif stringName == 'uint16':
  78. t = UInt16()
  79. elif stringName == 'int64':
  80. t = Int64()
  81. elif stringName == 'uint64':
  82. t = UInt64()
  83. elif stringName == 'byte':
  84. t = Byte()
  85. elif stringName == 'sbyte':
  86. t = SByte()
  87. elif stringName == 'float':
  88. t = Float()
  89. elif stringName == 'double':
  90. t = Double()
  91. elif stringName == 'string':
  92. t = String()
  93. elif stringName == 'bytestring':
  94. t = ByteString()
  95. elif stringName == 'localizedtext':
  96. t = LocalizedText()
  97. elif stringName == 'statuscode':
  98. t = StatusCode()
  99. elif stringName == 'diagnosticinfo':
  100. t = DiagnosticInfo()
  101. elif stringName == 'nodeid':
  102. t = NodeId()
  103. elif stringName == 'guid':
  104. t = Guid()
  105. elif stringName == 'datetime':
  106. t = DateTime()
  107. elif stringName == 'qualifiedname':
  108. t = QualifiedName()
  109. elif stringName == 'expandednodeid':
  110. t = ExpandedNodeId()
  111. elif stringName == 'xmlelement':
  112. t = XmlElement()
  113. else:
  114. logger.debug("No class representing stringName " + stringName + " was found. Cannot create builtinType.")
  115. return None
  116. t.encodingRule = encodingRule
  117. return t
  118. def checkXML(self, xmlvalue):
  119. if xmlvalue == None or xmlvalue.nodeType != xmlvalue.ELEMENT_NODE:
  120. logger.error("Expected XML Element, but got junk...")
  121. return
  122. def parseXML(self, xmlvalue):
  123. raise Exception("Cannot parse arbitrary value of no type.")
  124. def parseXMLEncoding(self, xmlvalue, parentDataTypeNode, parent):
  125. self.checkXML(xmlvalue)
  126. if not "value" in xmlvalue.localName.lower():
  127. logger.error("Expected <Value> , but found " + xmlvalue.localName + \
  128. " instead. Value will not be parsed.")
  129. return
  130. if len(xmlvalue.childNodes) == 0:
  131. logger.error("Expected childnodes for value, but none were found...")
  132. return
  133. for n in xmlvalue.childNodes:
  134. if n.nodeType == n.ELEMENT_NODE:
  135. xmlvalue = n
  136. break
  137. if "ListOf" in xmlvalue.localName:
  138. self.value = []
  139. for el in xmlvalue.childNodes:
  140. if not el.nodeType == el.ELEMENT_NODE:
  141. continue
  142. val = self.__parseXMLSingleValue(el, parentDataTypeNode, parent)
  143. if val is None:
  144. self.value = []
  145. return
  146. self.value.append(val)
  147. else:
  148. self.value = [self.__parseXMLSingleValue(xmlvalue, parentDataTypeNode, parent)]
  149. def __parseXMLSingleValue(self, xmlvalue, parentDataTypeNode, parent, alias=None, encodingPart=None):
  150. # Parse an encoding list such as enc = [[Int32], ['Duration', ['DateTime']]],
  151. # returning a possibly aliased variable or list of variables.
  152. # Keep track of aliases, as ['Duration', ['Hawaii', ['UtcTime', ['DateTime']]]]
  153. # will be of type DateTime, but tagged as <Duration>2013-04-10 12:00 UTC</Duration>,
  154. # and not as <Duration><Hawaii><UtcTime><String>2013-04-10 12:00 UTC</String>...
  155. # Encoding may be partially handed down (iterative call). Only resort to
  156. # type definition if we are not given a specific encoding to match
  157. if encodingPart == None:
  158. enc = parentDataTypeNode.getEncoding()
  159. else:
  160. enc = encodingPart
  161. # Check the structure of the encoding list to determine if a type is to be
  162. # returned or we need to descend further checking aliases or multipart types
  163. # such as extension Objects.
  164. if len(enc) == 1:
  165. # 0: ['BuiltinType'] either builtin type
  166. # 1: [ [ 'Alias', [...], n] ] or single alias for possible multipart
  167. if isinstance(enc[0], six.string_types):
  168. # 0: 'BuiltinType'
  169. if alias != None:
  170. if not xmlvalue.localName == alias and not xmlvalue.localName == enc[0]:
  171. logger.error(str(parent.id) + ": Expected XML element with tag " + alias + " but found " + xmlvalue.localName + " instead")
  172. return None
  173. else:
  174. t = self.getTypeByString(enc[0], enc)
  175. t.alias = alias
  176. t.parseXML(xmlvalue)
  177. return t
  178. else:
  179. if not valueIsInternalType(xmlvalue.localName):
  180. logger.error(str(parent.id) + ": Expected XML describing builtin type " + enc[0] + " but found " + xmlvalue.localName + " instead")
  181. else:
  182. t = self.getTypeByString(enc[0], enc)
  183. t.parseXML(xmlvalue)
  184. t.isInternal = True
  185. return t
  186. else:
  187. # 1: ['Alias', [...], n]
  188. # Let the next elif handle this
  189. return self.__parseXMLSingleValue(xmlvalue, parentDataTypeNode, parent, alias=alias, encodingPart=enc[0])
  190. elif len(enc) == 3 and isinstance(enc[0], six.string_types):
  191. # [ 'Alias', [...], 0 ] aliased multipart
  192. if alias == None:
  193. alias = enc[0]
  194. # if we have an alias and the next field is multipart, keep the alias
  195. elif alias != None and len(enc[1]) > 1:
  196. alias = enc[0]
  197. # otherwise drop the alias
  198. return self.__parseXMLSingleValue(xmlvalue, parentDataTypeNode, parent, alias=alias, encodingPart=enc[1])
  199. else:
  200. # [ [...], [...], [...]] multifield of unknowns (analyse separately)
  201. # create an extension object to hold multipart type
  202. # FIXME: This implementation expects an extensionobject to be manditory for
  203. # multipart variables. Variants/Structures are not included in the
  204. # OPCUA Namespace 0 nodeset.
  205. # Consider moving this ExtensionObject specific parsing into the
  206. # builtin type and only determining the multipart type at this stage.
  207. if not xmlvalue.localName == "ExtensionObject":
  208. logger.error(str(parent.id) + ": Expected XML tag <ExtensionObject> for multipart type, but found " + xmlvalue.localName + " instead.")
  209. return None
  210. extobj = ExtensionObject()
  211. extobj.encodingRule = enc
  212. etype = xmlvalue.getElementsByTagName("TypeId")
  213. if len(etype) == 0:
  214. logger.error(str(parent.id) + ": Did not find <TypeId> for ExtensionObject")
  215. return None
  216. etype = etype[0].getElementsByTagName("Identifier")
  217. if len(etype) == 0:
  218. logger.error(str(parent.id) + ": Did not find <Identifier> for ExtensionObject")
  219. return None
  220. etype = NodeId(etype[0].firstChild.data.strip(' \t\n\r'))
  221. extobj.typeId = etype
  222. ebody = xmlvalue.getElementsByTagName("Body")
  223. if len(ebody) == 0:
  224. logger.error(str(parent.id) + ": Did not find <Body> for ExtensionObject")
  225. return None
  226. ebody = ebody[0]
  227. # Body must contain an Object of type 'DataType' as defined in Variable
  228. ebodypart = ebody.firstChild
  229. if not ebodypart.nodeType == ebodypart.ELEMENT_NODE:
  230. ebodypart = getNextElementNode(ebodypart)
  231. if ebodypart == None:
  232. logger.error(str(parent.id) + ": Expected ExtensionObject to hold a variable of type " + str(parentDataTypeNode.browseName) + " but found nothing.")
  233. return None
  234. if not ebodypart.localName == parentDataTypeNode.browseName.name:
  235. logger.error(str(parent.id) + ": Expected ExtensionObject to hold a variable of type " + str(parentDataTypeNode.browseName) + " but found " +
  236. str(ebodypart.localName) + " instead.")
  237. return None
  238. extobj.alias = ebodypart.localName
  239. ebodypart = ebodypart.firstChild
  240. if not ebodypart.nodeType == ebodypart.ELEMENT_NODE:
  241. ebodypart = getNextElementNode(ebodypart)
  242. if ebodypart == None:
  243. logger.error(str(parent.id) + ": Description of dataType " + str(parentDataTypeNode.browseName) + " in ExtensionObject is empty/invalid.")
  244. return None
  245. extobj.value = []
  246. for e in enc:
  247. if not ebodypart == None:
  248. extobj.value.append(extobj.__parseXMLSingleValue(ebodypart, parentDataTypeNode, parent, alias=None, encodingPart=e))
  249. else:
  250. logger.error(str(parent.id) + ": Expected encoding " + str(e) + " but found none in body.")
  251. ebodypart = getNextElementNode(ebodypart)
  252. return extobj
  253. def __str__(self):
  254. return self.__class__.__name__ + "(" + str(self.value) + ")"
  255. def __repr__(self):
  256. return self.__str__()
  257. #################
  258. # Builtin Types #
  259. #################
  260. class Boolean(Value):
  261. def __init__(self, xmlelement=None):
  262. Value.__init__(self)
  263. self.numericRepresentation = BUILTINTYPE_TYPEID_BOOLEAN
  264. if xmlelement:
  265. self.parseXML(xmlelement)
  266. def parseXML(self, xmlvalue):
  267. # Expect <Boolean>value</Boolean> or
  268. # <Aliasname>value</Aliasname>
  269. self.checkXML(xmlvalue)
  270. if xmlvalue.firstChild == None:
  271. self.value = "false" # Catch XML <Boolean /> by setting the value to a default
  272. else:
  273. if "false" in unicode(xmlvalue.firstChild.data).lower():
  274. self.value = "false"
  275. else:
  276. self.value = "true"
  277. class Number(Value):
  278. def __init__(self, xmlelement=None):
  279. Value.__init__(self)
  280. self.numericRepresentation = BUILTINTYPE_TYPEID_NUMBER
  281. if xmlelement:
  282. self.parseXML(xmlelement)
  283. def parseXML(self, xmlvalue):
  284. # Expect <Int16>value</Int16> or any other valid number type, or
  285. # <Aliasname>value</Aliasname>
  286. self.checkXML(xmlvalue)
  287. if xmlvalue.firstChild == None:
  288. self.value = 0 # Catch XML <Int16 /> by setting the value to a default
  289. else:
  290. self.value = int(unicode(xmlvalue.firstChild.data))
  291. class Integer(Number):
  292. def __init__(self, xmlelement=None):
  293. Value.__init__(self)
  294. self.numericRepresentation = BUILTINTYPE_TYPEID_INTEGER
  295. if xmlelement:
  296. self.parseXML(xmlelement)
  297. class UInteger(Number):
  298. def __init__(self, xmlelement=None):
  299. Value.__init__(self)
  300. self.numericRepresentation = BUILTINTYPE_TYPEID_UINTEGER
  301. if xmlelement:
  302. self.parseXML(xmlelement)
  303. class Byte(UInteger):
  304. def __init__(self, xmlelement=None):
  305. Value.__init__(self)
  306. self.numericRepresentation = BUILTINTYPE_TYPEID_BYTE
  307. if xmlelement:
  308. self.parseXML(xmlelement)
  309. class SByte(Integer):
  310. def __init__(self, xmlelement=None):
  311. Value.__init__(self)
  312. self.numericRepresentation = BUILTINTYPE_TYPEID_SBYTE
  313. if xmlelement:
  314. self.parseXML(xmlelement)
  315. class Int16(Integer):
  316. def __init__(self, xmlelement=None):
  317. Value.__init__(self)
  318. self.numericRepresentation = BUILTINTYPE_TYPEID_INT16
  319. if xmlelement:
  320. self.parseXML(xmlelement)
  321. class UInt16(UInteger):
  322. def __init__(self, xmlelement=None):
  323. Value.__init__(self)
  324. self.numericRepresentation = BUILTINTYPE_TYPEID_UINT16
  325. if xmlelement:
  326. self.parseXML(xmlelement)
  327. class Int32(Integer):
  328. def __init__(self, xmlelement=None):
  329. Value.__init__(self)
  330. self.numericRepresentation = BUILTINTYPE_TYPEID_INT32
  331. if xmlelement:
  332. self.parseXML(xmlelement)
  333. class UInt32(UInteger):
  334. def __init__(self, xmlelement=None):
  335. Value.__init__(self)
  336. self.numericRepresentation = BUILTINTYPE_TYPEID_UINT32
  337. if xmlelement:
  338. self.parseXML(xmlelement)
  339. class Int64(Integer):
  340. def __init__(self, xmlelement=None):
  341. Value.__init__(self)
  342. self.numericRepresentation = BUILTINTYPE_TYPEID_INT64
  343. if xmlelement:
  344. self.parseXML(xmlelement)
  345. class UInt64(UInteger):
  346. def __init__(self, xmlelement=None):
  347. Value.__init__(self)
  348. self.numericRepresentation = BUILTINTYPE_TYPEID_UINT64
  349. if xmlelement:
  350. self.parseXML(xmlelement)
  351. class Float(Number):
  352. def __init__(self, xmlelement=None):
  353. Value.__init__(self)
  354. self.numericRepresentation = BUILTINTYPE_TYPEID_FLOAT
  355. if xmlelement:
  356. self.parseXML(xmlelement)
  357. def parseXML(self, xmlvalue):
  358. # Expect <Float>value</Float> or
  359. # <Aliasname>value</Aliasname>
  360. self.checkXML(xmlvalue)
  361. if xmlvalue.firstChild == None:
  362. self.value = 0.0 # Catch XML <Float /> by setting the value to a default
  363. else:
  364. self.value = float(unicode(xmlvalue.firstChild.data))
  365. class Double(Float):
  366. def __init__(self, xmlelement=None):
  367. Value.__init__(self)
  368. self.numericRepresentation = BUILTINTYPE_TYPEID_DOUBLE
  369. if xmlelement:
  370. self.parseXML(xmlelement)
  371. class String(Value):
  372. def __init__(self, xmlelement=None):
  373. Value.__init__(self)
  374. self.numericRepresentation = BUILTINTYPE_TYPEID_STRING
  375. if xmlelement:
  376. self.parseXML(xmlelement)
  377. def pack(self):
  378. bin = structpack("I", len(unicode(self.value)))
  379. bin = bin + str(self.value)
  380. return bin
  381. def parseXML(self, xmlvalue):
  382. # Expect <String>value</String> or
  383. # <Aliasname>value</Aliasname>
  384. if not isinstance(xmlvalue, dom.Element):
  385. self.value = xmlvalue
  386. return
  387. self.checkXML(xmlvalue)
  388. if xmlvalue.firstChild == None:
  389. self.value = "" # Catch XML <String /> by setting the value to a default
  390. else:
  391. self.value = unicode(xmlvalue.firstChild.data)
  392. class XmlElement(String):
  393. def __init__(self, xmlelement=None):
  394. Value.__init__(self, xmlelement)
  395. self.numericRepresentation = BUILTINTYPE_TYPEID_XMLELEMENT
  396. class ByteString(Value):
  397. def __init__(self, xmlelement=None):
  398. Value.__init__(self, xmlelement)
  399. self.numericRepresentation = BUILTINTYPE_TYPEID_BYTESTRING
  400. def parseXML(self, xmlvalue):
  401. # Expect <ByteString>value</ByteString>
  402. if not isinstance(xmlvalue, dom.Element):
  403. self.value = xmlvalue
  404. return
  405. self.checkXML(xmlvalue)
  406. if xmlvalue.firstChild == None:
  407. self.value = [] # Catch XML <ByteString /> by setting the value to a default
  408. else:
  409. self.value = b64decode(xmlvalue.firstChild.data).decode("utf-8")
  410. class ExtensionObject(Value):
  411. def __init__(self, xmlelement=None):
  412. Value.__init__(self)
  413. self.numericRepresentation = BUILTINTYPE_TYPEID_EXTENSIONOBJECT
  414. if xmlelement:
  415. self.parseXML(xmlelement)
  416. def parseXML(self, xmlelement):
  417. pass
  418. def __str__(self):
  419. return "'" + self.alias() + "':" + self.stringRepresentation + "(" + str(self.value) + ")"
  420. class LocalizedText(Value):
  421. def __init__(self, xmlvalue=None):
  422. Value.__init__(self)
  423. self.numericRepresentation = BUILTINTYPE_TYPEID_LOCALIZEDTEXT
  424. self.locale = ''
  425. self.text = ''
  426. if xmlvalue:
  427. self.parseXML(xmlvalue)
  428. def parseXML(self, xmlvalue):
  429. # Expect <LocalizedText> or <AliasName>
  430. # <Locale>xx_XX</Locale>
  431. # <Text>TextText</Text>
  432. # <LocalizedText> or </AliasName>
  433. if not isinstance(xmlvalue, dom.Element):
  434. self.text = xmlvalue
  435. return
  436. self.checkXML(xmlvalue)
  437. tmp = xmlvalue.getElementsByTagName("Locale")
  438. if len(tmp) > 0 and tmp[0].firstChild != None:
  439. self.locale = tmp[0].firstChild.data.strip(' \t\n\r')
  440. tmp = xmlvalue.getElementsByTagName("Text")
  441. if len(tmp) > 0 and tmp[0].firstChild != None:
  442. self.text = tmp[0].firstChild.data.strip(' \t\n\r')
  443. def __str__(self):
  444. if self.locale is not None and len(self.locale) > 0:
  445. return "(" + self.locale + ":" + self.text + ")"
  446. else:
  447. return self.text
  448. class NodeId(Value):
  449. def __init__(self, idstring=None):
  450. Value.__init__(self)
  451. self.numericRepresentation = BUILTINTYPE_TYPEID_NODEID
  452. self.i = None
  453. self.b = None
  454. self.g = None
  455. self.s = None
  456. self.ns = 0
  457. self.setFromIdString(idstring)
  458. def setFromIdString(self, idstring):
  459. if not idstring:
  460. self.i = 0
  461. return
  462. # The ID will encoding itself appropriatly as string. If multiple ID's
  463. # (numeric, string, guid) are defined, the order of preference for the ID
  464. # string is always numeric, guid, bytestring, string. Binary encoding only
  465. # applies to numeric values (UInt16).
  466. idparts = idstring.strip().split(";")
  467. for p in idparts:
  468. if p[:2] == "ns":
  469. self.ns = int(p[3:])
  470. elif p[:2] == "i=":
  471. self.i = int(p[2:])
  472. elif p[:2] == "o=":
  473. self.b = p[2:]
  474. elif p[:2] == "g=":
  475. tmp = []
  476. self.g = p[2:].split("-")
  477. for i in self.g:
  478. i = "0x" + i
  479. tmp.append(int(i, 16))
  480. self.g = tmp
  481. elif p[:2] == "s=":
  482. self.s = p[2:]
  483. else:
  484. raise Exception("no valid nodeid: " + idstring)
  485. def parseXML(self, xmlvalue):
  486. # Expect <NodeId> or <Alias>
  487. # <Identifier> # It is unclear whether or not this is manditory. Identifier tags are used in Namespace 0.
  488. # ns=x;i=y or similar string representation of id()
  489. # </Identifier>
  490. # </NodeId> or </Alias>
  491. if not isinstance(xmlvalue, dom.Element):
  492. self.text = xmlvalue
  493. return
  494. self.checkXML(xmlvalue)
  495. if self.alias != None:
  496. if not self.alias == xmlvalue.localName:
  497. logger.warn(
  498. "Expected an aliased XML field called " + self.alias + " but got " + xmlvalue.localName + " instead. This is a parsing error of Value.__parseXMLSingleValue(), will try to continue anyway.")
  499. else:
  500. if not self.stringRepresentation == xmlvalue.localName:
  501. logger.warn(
  502. "Expected XML field " + self.stringRepresentation + " but got " + xmlvalue.localName + " instead. This is a parsing error of Value.__parseXMLSingleValue(), will try to continue anyway.")
  503. # Catch XML <NodeId />
  504. if xmlvalue.firstChild == None:
  505. logger.error("No value is given, which is illegal for Node Types...")
  506. self.value = None
  507. else:
  508. # Check if there is an <Identifier> tag
  509. if len(xmlvalue.getElementsByTagName("Identifier")) != 0:
  510. xmlvalue = xmlvalue.getElementsByTagName("Identifier")[0]
  511. self.setFromIdString(unicode(xmlvalue.firstChild.data))
  512. def __str__(self):
  513. s = "ns=" + str(self.ns) + ";"
  514. # Order of preference is numeric, guid, bytestring, string
  515. if self.i != None:
  516. return s + "i=" + str(self.i)
  517. elif self.g != None:
  518. s = s + "g="
  519. tmp = []
  520. for i in self.g:
  521. tmp.append(hex(i).replace("0x", ""))
  522. for i in tmp:
  523. s = s + "-" + i
  524. return s.replace("g=-", "g=")
  525. elif self.b != None:
  526. return s + "b=" + str(self.b)
  527. elif self.s != None:
  528. return s + "s=" + str(self.s)
  529. def __eq__(self, nodeId2):
  530. return (str(self) == str(nodeId2))
  531. def __repr__(self):
  532. return str(self)
  533. def __hash__(self):
  534. return hash(str(self))
  535. class ExpandedNodeId(Value):
  536. def __init__(self, xmlelement=None):
  537. Value.__init__(self)
  538. self.numericRepresentation = BUILTINTYPE_TYPEID_EXPANDEDNODEID
  539. if xmlelement:
  540. self.parseXML(xmlelement)
  541. def parseXML(self, xmlvalue):
  542. self.checkXML(xmlvalue)
  543. logger.debug("Not implemented", LOG_LEVEL_ERR)
  544. class DateTime(Value):
  545. def __init__(self, xmlelement=None):
  546. Value.__init__(self)
  547. self.numericRepresentation = BUILTINTYPE_TYPEID_DATETIME
  548. if xmlelement:
  549. self.parseXML(xmlelement)
  550. def parseXML(self, xmlvalue):
  551. # Expect <DateTime> or <AliasName>
  552. # 2013-08-13T21:00:05.0000L
  553. # </DateTime> or </AliasName>
  554. self.checkXML(xmlvalue)
  555. if xmlvalue.firstChild == None:
  556. # Catch XML <DateTime /> by setting the value to a default
  557. self.value = datetime(2001, 1, 1)
  558. else:
  559. timestr = unicode(xmlvalue.firstChild.data)
  560. # .NET tends to create this garbage %Y-%m-%dT%H:%M:%S.0000z
  561. # strip everything after the "." away for a posix time_struct
  562. if "." in timestr:
  563. timestr = timestr[:timestr.index(".")]
  564. # If the last character is not numeric, remove it
  565. while len(timestr) > 0 and not timestr[-1] in "0123456789":
  566. timestr = timestr[:-1]
  567. try:
  568. self.value = datetime.strptime(timestr, "%Y-%m-%dT%H:%M:%S")
  569. except:
  570. try:
  571. self.value = datetime.strptime(timestr, "%Y-%m-%d")
  572. except:
  573. logger.error("Timestring format is illegible. Expected 2001-01-30T21:22:23 or 2001-01-30, but got " + \
  574. timestr + " instead. Time will be defaultet to now()")
  575. self.value = datetime(2001, 1, 1)
  576. class QualifiedName(Value):
  577. def __init__(self, xmlelement=None):
  578. Value.__init__(self)
  579. self.numericRepresentation = BUILTINTYPE_TYPEID_QUALIFIEDNAME
  580. self.ns = 0
  581. self.name = ''
  582. if xmlelement:
  583. self.parseXML(xmlelement)
  584. def parseXML(self, xmlvalue):
  585. # Expect <QualifiedName> or <AliasName>
  586. # <NamespaceIndex>Int16<NamespaceIndex>
  587. # <Name>SomeString<Name>
  588. # </QualifiedName> or </AliasName>
  589. if not isinstance(xmlvalue, dom.Element):
  590. colonindex = xmlvalue.find(":")
  591. if colonindex == -1:
  592. self.name = xmlvalue
  593. else:
  594. self.name = xmlvalue[colonindex + 1:]
  595. self.ns = int(xmlvalue[:colonindex])
  596. return
  597. self.checkXML(xmlvalue)
  598. # Is a namespace index passed?
  599. if len(xmlvalue.getElementsByTagName("NamespaceIndex")) != 0:
  600. self.ns = int(xmlvalue.getElementsByTagName("NamespaceIndex")[0].firstChild.data)
  601. if len(xmlvalue.getElementsByTagName("Name")) != 0:
  602. self.name = xmlvalue.getElementsByTagName("Name")[0].firstChild.data
  603. def __str__(self):
  604. return "ns=" + str(self.ns) + ";" + str(self.name)
  605. class StatusCode(UInt32):
  606. def __init__(self, xmlelement=None):
  607. Value.__init__(self, xmlelement)
  608. self.numericRepresentation = BUILTINTYPE_TYPEID_STATUSCODE
  609. class DiagnosticInfo(Value):
  610. def __init__(self, xmlelement=None):
  611. Value.__init__(self)
  612. self.numericRepresentation = BUILTINTYPE_TYPEID_DIAGNOSTICINFO
  613. if xmlelement:
  614. self.parseXML(xmlelement)
  615. def parseXML(self, xmlvalue):
  616. self.checkXML(xmlvalue)
  617. logger.warn("Not implemented")
  618. class Guid(Value):
  619. def __init__(self, xmlelement=None):
  620. Value.__init__(self)
  621. self.numericRepresentation = BUILTINTYPE_TYPEID_GUID
  622. if xmlelement:
  623. self.parseXML(xmlelement)
  624. def parseXML(self, xmlvalue):
  625. self.checkXML(xmlvalue)
  626. if xmlvalue.firstChild == None:
  627. self.value = [0, 0, 0, 0] # Catch XML <Guid /> by setting the value to a default
  628. else:
  629. self.value = unicode(xmlvalue.firstChild.data)
  630. self.value = self.value.replace("{", "")
  631. self.value = self.value.replace("}", "")
  632. self.value = self.value.split("-")
  633. tmp = []
  634. for g in self.value:
  635. try:
  636. tmp.append(int("0x" + g, 16))
  637. except:
  638. logger.error("Invalid formatting of Guid. Expected {01234567-89AB-CDEF-ABCD-0123456789AB}, got " + \
  639. unicode(xmlvalue.firstChild.data))
  640. tmp = [0, 0, 0, 0, 0]
  641. if len(tmp) != 5:
  642. logger.error("Invalid formatting of Guid. Expected {01234567-89AB-CDEF-ABCD-0123456789AB}, got " + \
  643. unicode(xmlvalue.firstChild.data))
  644. tmp = [0, 0, 0, 0]
  645. self.value = tmp