datatypes.py 27 KB

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