datatypes.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704
  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):
  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)
  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)]
  150. def __parseXMLSingleValue(self, xmlvalue, parentDataTypeNode, parent, 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.parseXML(xmlvalue)
  178. t.valueRank = valueRank
  179. return t
  180. else:
  181. if not valueIsInternalType(xmlvalue.localName):
  182. logger.error(str(parent.id) + ": Expected XML describing builtin type " + enc[0] + " but found " + xmlvalue.localName + " instead")
  183. else:
  184. t = self.getTypeByString(enc[0], enc)
  185. t.parseXML(xmlvalue)
  186. t.isInternal = True
  187. return t
  188. else:
  189. # 1: ['Alias', [...], n]
  190. # Let the next elif handle this
  191. return self.__parseXMLSingleValue(xmlvalue, parentDataTypeNode, parent,
  192. alias=alias, encodingPart=enc[0], valueRank=enc[2] if len(enc)>2 else None)
  193. elif len(enc) == 3 and isinstance(enc[0], six.string_types):
  194. # [ 'Alias', [...], 0 ] aliased multipart
  195. if alias is None:
  196. alias = enc[0]
  197. # if we have an alias and the next field is multipart, keep the alias
  198. elif alias is not None and len(enc[1]) > 1:
  199. alias = enc[0]
  200. # otherwise drop the alias
  201. return self.__parseXMLSingleValue(xmlvalue, parentDataTypeNode, parent,
  202. alias=alias, encodingPart=enc[1], valueRank=enc[2] if len(enc)>2 else None)
  203. else:
  204. # [ [...], [...], [...]] multifield of unknowns (analyse separately)
  205. # create an extension object to hold multipart type
  206. # FIXME: This implementation expects an extensionobject to be manditory for
  207. # multipart variables. Variants/Structures are not included in the
  208. # OPCUA Namespace 0 nodeset.
  209. # Consider moving this ExtensionObject specific parsing into the
  210. # builtin type and only determining the multipart type at this stage.
  211. if not xmlvalue.localName == "ExtensionObject":
  212. logger.error(str(parent.id) + ": Expected XML tag <ExtensionObject> for multipart type, but found " + xmlvalue.localName + " instead.")
  213. return None
  214. extobj = ExtensionObject()
  215. extobj.encodingRule = enc
  216. etype = xmlvalue.getElementsByTagName("TypeId")
  217. if len(etype) == 0:
  218. logger.error(str(parent.id) + ": Did not find <TypeId> for ExtensionObject")
  219. return None
  220. etype = etype[0].getElementsByTagName("Identifier")
  221. if len(etype) == 0:
  222. logger.error(str(parent.id) + ": Did not find <Identifier> for ExtensionObject")
  223. return None
  224. etype = NodeId(etype[0].firstChild.data.strip(' \t\n\r'))
  225. extobj.typeId = etype
  226. ebody = xmlvalue.getElementsByTagName("Body")
  227. if len(ebody) == 0:
  228. logger.error(str(parent.id) + ": Did not find <Body> for ExtensionObject")
  229. return None
  230. ebody = ebody[0]
  231. # Body must contain an Object of type 'DataType' as defined in Variable
  232. ebodypart = ebody.firstChild
  233. if not ebodypart.nodeType == ebodypart.ELEMENT_NODE:
  234. ebodypart = getNextElementNode(ebodypart)
  235. if ebodypart is None:
  236. logger.error(str(parent.id) + ": Expected ExtensionObject to hold a variable of type " + str(parentDataTypeNode.browseName) + " but found nothing.")
  237. return None
  238. if not ebodypart.localName == parentDataTypeNode.browseName.name:
  239. logger.error(str(parent.id) + ": Expected ExtensionObject to hold a variable of type " + str(parentDataTypeNode.browseName) + " but found " +
  240. str(ebodypart.localName) + " instead.")
  241. return None
  242. extobj.alias = ebodypart.localName
  243. ebodypart = ebodypart.firstChild
  244. if not ebodypart.nodeType == ebodypart.ELEMENT_NODE:
  245. ebodypart = getNextElementNode(ebodypart)
  246. if ebodypart is None:
  247. logger.error(str(parent.id) + ": Description of dataType " + str(parentDataTypeNode.browseName) + " in ExtensionObject is empty/invalid.")
  248. return None
  249. extobj.value = []
  250. for e in enc:
  251. if not ebodypart is None:
  252. extobj.value.append(extobj.__parseXMLSingleValue(ebodypart, parentDataTypeNode, parent, alias=None, encodingPart=e))
  253. else:
  254. logger.error(str(parent.id) + ": Expected encoding " + str(e) + " but found none in body.")
  255. ebodypart = getNextElementNode(ebodypart)
  256. return extobj
  257. def __str__(self):
  258. return self.__class__.__name__ + "(" + str(self.value) + ")"
  259. def __repr__(self):
  260. return self.__str__()
  261. #################
  262. # Builtin Types #
  263. #################
  264. class Boolean(Value):
  265. def __init__(self, xmlelement=None):
  266. Value.__init__(self)
  267. if xmlelement:
  268. self.parseXML(xmlelement)
  269. def parseXML(self, xmlvalue):
  270. # Expect <Boolean>value</Boolean> or
  271. # <Aliasname>value</Aliasname>
  272. self.checkXML(xmlvalue)
  273. if xmlvalue.firstChild is None:
  274. self.value = "false" # Catch XML <Boolean /> by setting the value to a default
  275. else:
  276. if "false" in unicode(xmlvalue.firstChild.data).lower():
  277. self.value = "false"
  278. else:
  279. self.value = "true"
  280. class Number(Value):
  281. def __init__(self, xmlelement=None):
  282. Value.__init__(self)
  283. if xmlelement:
  284. self.parseXML(xmlelement)
  285. def parseXML(self, xmlvalue):
  286. # Expect <Int16>value</Int16> or any other valid number type, or
  287. # <Aliasname>value</Aliasname>
  288. self.checkXML(xmlvalue)
  289. if xmlvalue.firstChild is None:
  290. self.value = 0 # Catch XML <Int16 /> by setting the value to a default
  291. else:
  292. self.value = int(unicode(xmlvalue.firstChild.data))
  293. class Integer(Number):
  294. def __init__(self, xmlelement=None):
  295. Number.__init__(self)
  296. if xmlelement:
  297. self.parseXML(xmlelement)
  298. class UInteger(Number):
  299. def __init__(self, xmlelement=None):
  300. Number.__init__(self)
  301. if xmlelement:
  302. self.parseXML(xmlelement)
  303. class Byte(UInteger):
  304. def __init__(self, xmlelement=None):
  305. UInteger.__init__(self)
  306. if xmlelement:
  307. self.parseXML(xmlelement)
  308. class SByte(Integer):
  309. def __init__(self, xmlelement=None):
  310. Integer.__init__(self)
  311. if xmlelement:
  312. self.parseXML(xmlelement)
  313. class Int16(Integer):
  314. def __init__(self, xmlelement=None):
  315. Integer.__init__(self)
  316. if xmlelement:
  317. self.parseXML(xmlelement)
  318. class UInt16(UInteger):
  319. def __init__(self, xmlelement=None):
  320. UInteger.__init__(self)
  321. if xmlelement:
  322. self.parseXML(xmlelement)
  323. class Int32(Integer):
  324. def __init__(self, xmlelement=None):
  325. Integer.__init__(self)
  326. if xmlelement:
  327. self.parseXML(xmlelement)
  328. class UInt32(UInteger):
  329. def __init__(self, xmlelement=None):
  330. UInteger.__init__(self)
  331. if xmlelement:
  332. self.parseXML(xmlelement)
  333. class Int64(Integer):
  334. def __init__(self, xmlelement=None):
  335. Integer.__init__(self)
  336. if xmlelement:
  337. self.parseXML(xmlelement)
  338. class UInt64(UInteger):
  339. def __init__(self, xmlelement=None):
  340. UInteger.__init__(self)
  341. if xmlelement:
  342. self.parseXML(xmlelement)
  343. class Float(Number):
  344. def __init__(self, xmlelement=None):
  345. Number.__init__(self)
  346. if xmlelement:
  347. Float.parseXML(self, xmlelement)
  348. def parseXML(self, xmlvalue):
  349. # Expect <Float>value</Float> or
  350. # <Aliasname>value</Aliasname>
  351. self.checkXML(xmlvalue)
  352. if xmlvalue.firstChild is None:
  353. self.value = 0.0 # Catch XML <Float /> by setting the value to a default
  354. else:
  355. self.value = float(unicode(xmlvalue.firstChild.data))
  356. class Double(Float):
  357. def __init__(self, xmlelement=None):
  358. Float.__init__(self)
  359. if xmlelement:
  360. self.parseXML(xmlelement)
  361. class String(Value):
  362. def __init__(self, xmlelement=None):
  363. Value.__init__(self)
  364. if xmlelement:
  365. self.parseXML(xmlelement)
  366. def pack(self):
  367. bin = structpack("I", len(unicode(self.value)))
  368. bin = bin + str(self.value)
  369. return bin
  370. def parseXML(self, xmlvalue):
  371. # Expect <String>value</String> or
  372. # <Aliasname>value</Aliasname>
  373. if not isinstance(xmlvalue, dom.Element):
  374. self.value = xmlvalue
  375. return
  376. self.checkXML(xmlvalue)
  377. if xmlvalue.firstChild is None:
  378. self.value = "" # Catch XML <String /> by setting the value to a default
  379. else:
  380. self.value = unicode(xmlvalue.firstChild.data)
  381. class XmlElement(String):
  382. def __init__(self, xmlelement=None):
  383. String.__init__(self, xmlelement)
  384. class ByteString(Value):
  385. def __init__(self, xmlelement=None):
  386. Value.__init__(self)
  387. def parseXML(self, xmlvalue):
  388. # Expect <ByteString>value</ByteString>
  389. if not isinstance(xmlvalue, dom.Element):
  390. self.value = xmlvalue
  391. return
  392. self.checkXML(xmlvalue)
  393. if xmlvalue.firstChild is None:
  394. self.value = [] # Catch XML <ByteString /> by setting the value to a default
  395. else:
  396. self.value = b64decode(xmlvalue.firstChild.data).decode("utf-8")
  397. class ExtensionObject(Value):
  398. def __init__(self, xmlelement=None):
  399. Value.__init__(self)
  400. if xmlelement:
  401. self.parseXML(xmlelement)
  402. def parseXML(self, xmlelement):
  403. pass
  404. def __str__(self):
  405. return "'ExtensionObject'"
  406. class LocalizedText(Value):
  407. def __init__(self, xmlvalue=None):
  408. Value.__init__(self)
  409. self.locale = ''
  410. self.text = ''
  411. if xmlvalue:
  412. self.parseXML(xmlvalue)
  413. def parseXML(self, xmlvalue):
  414. # Expect <LocalizedText> or <AliasName>
  415. # <Locale>xx_XX</Locale>
  416. # <Text>TextText</Text>
  417. # <LocalizedText> or </AliasName>
  418. if not isinstance(xmlvalue, dom.Element):
  419. self.text = xmlvalue
  420. return
  421. self.checkXML(xmlvalue)
  422. tmp = xmlvalue.getElementsByTagName("Locale")
  423. if len(tmp) > 0 and tmp[0].firstChild != None:
  424. self.locale = tmp[0].firstChild.data.strip(' \t\n\r')
  425. tmp = xmlvalue.getElementsByTagName("Text")
  426. if len(tmp) > 0 and tmp[0].firstChild != None:
  427. self.text = tmp[0].firstChild.data.strip(' \t\n\r')
  428. def __str__(self):
  429. if self.locale is not None and len(self.locale) > 0:
  430. return "(" + self.locale + ":" + self.text + ")"
  431. else:
  432. return self.text
  433. class NodeId(Value):
  434. def __init__(self, idstring=None):
  435. Value.__init__(self)
  436. self.i = None
  437. self.b = None
  438. self.g = None
  439. self.s = None
  440. self.ns = 0
  441. self.setFromIdString(idstring)
  442. def setFromIdString(self, idstring):
  443. if not idstring:
  444. self.i = 0
  445. return
  446. # The ID will encoding itself appropriatly as string. If multiple ID's
  447. # (numeric, string, guid) are defined, the order of preference for the ID
  448. # string is always numeric, guid, bytestring, string. Binary encoding only
  449. # applies to numeric values (UInt16).
  450. idparts = idstring.strip().split(";")
  451. for p in idparts:
  452. if p[:2] == "ns":
  453. self.ns = int(p[3:])
  454. elif p[:2] == "i=":
  455. self.i = int(p[2:])
  456. elif p[:2] == "o=":
  457. self.b = p[2:]
  458. elif p[:2] == "g=":
  459. tmp = []
  460. self.g = p[2:].split("-")
  461. for i in self.g:
  462. i = "0x" + i
  463. tmp.append(int(i, 16))
  464. self.g = tmp
  465. elif p[:2] == "s=":
  466. self.s = p[2:]
  467. else:
  468. raise Exception("no valid nodeid: " + idstring)
  469. def parseXML(self, xmlvalue):
  470. # Expect <NodeId> or <Alias>
  471. # <Identifier> # It is unclear whether or not this is manditory. Identifier tags are used in Namespace 0.
  472. # ns=x;i=y or similar string representation of id()
  473. # </Identifier>
  474. # </NodeId> or </Alias>
  475. if not isinstance(xmlvalue, dom.Element):
  476. self.text = xmlvalue # Alias
  477. return
  478. self.checkXML(xmlvalue)
  479. # Catch XML <NodeId />
  480. if xmlvalue.firstChild is None:
  481. logger.error("No value is given, which is illegal for Node Types...")
  482. self.value = None
  483. else:
  484. # Check if there is an <Identifier> tag
  485. if len(xmlvalue.getElementsByTagName("Identifier")) != 0:
  486. xmlvalue = xmlvalue.getElementsByTagName("Identifier")[0]
  487. self.setFromIdString(unicode(xmlvalue.firstChild.data))
  488. def __str__(self):
  489. s = "ns=" + str(self.ns) + ";"
  490. # Order of preference is numeric, guid, bytestring, string
  491. if self.i != None:
  492. return s + "i=" + str(self.i)
  493. elif self.g != None:
  494. s = s + "g="
  495. tmp = []
  496. for i in self.g:
  497. tmp.append(hex(i).replace("0x", ""))
  498. for i in tmp:
  499. s = s + "-" + i
  500. return s.replace("g=-", "g=")
  501. elif self.b != None:
  502. return s + "b=" + str(self.b)
  503. elif self.s != None:
  504. return s + "s=" + str(self.s)
  505. def __eq__(self, nodeId2):
  506. return (str(self) == str(nodeId2))
  507. def __ne__(self, other):
  508. return not self.__eq__(other)
  509. def __repr__(self):
  510. return str(self)
  511. def __hash__(self):
  512. return hash(str(self))
  513. class ExpandedNodeId(Value):
  514. def __init__(self, xmlelement=None):
  515. Value.__init__(self)
  516. if xmlelement:
  517. self.parseXML(xmlelement)
  518. def parseXML(self, xmlvalue):
  519. self.checkXML(xmlvalue)
  520. logger.debug("Not implemented", LOG_LEVEL_ERR)
  521. class DateTime(Value):
  522. def __init__(self, xmlelement=None):
  523. Value.__init__(self)
  524. if xmlelement:
  525. self.parseXML(xmlelement)
  526. def parseXML(self, xmlvalue):
  527. # Expect <DateTime> or <AliasName>
  528. # 2013-08-13T21:00:05.0000L
  529. # </DateTime> or </AliasName>
  530. self.checkXML(xmlvalue)
  531. if xmlvalue.firstChild is None:
  532. # Catch XML <DateTime /> by setting the value to a default
  533. self.value = datetime(2001, 1, 1)
  534. else:
  535. timestr = unicode(xmlvalue.firstChild.data)
  536. # .NET tends to create this garbage %Y-%m-%dT%H:%M:%S.0000z
  537. # strip everything after the "." away for a posix time_struct
  538. if "." in timestr:
  539. timestr = timestr[:timestr.index(".")]
  540. # If the last character is not numeric, remove it
  541. while len(timestr) > 0 and not timestr[-1] in "0123456789":
  542. timestr = timestr[:-1]
  543. try:
  544. self.value = datetime.strptime(timestr, "%Y-%m-%dT%H:%M:%S")
  545. except Exception:
  546. try:
  547. self.value = datetime.strptime(timestr, "%Y-%m-%d")
  548. except Exception:
  549. logger.error("Timestring format is illegible. Expected 2001-01-30T21:22:23 or 2001-01-30, but got " + \
  550. timestr + " instead. Time will be defaultet to now()")
  551. self.value = datetime(2001, 1, 1)
  552. class QualifiedName(Value):
  553. def __init__(self, xmlelement=None):
  554. Value.__init__(self)
  555. self.ns = 0
  556. self.name = ''
  557. if xmlelement:
  558. self.parseXML(xmlelement)
  559. def parseXML(self, xmlvalue):
  560. # Expect <QualifiedName> or <AliasName>
  561. # <NamespaceIndex>Int16<NamespaceIndex>
  562. # <Name>SomeString<Name>
  563. # </QualifiedName> or </AliasName>
  564. if not isinstance(xmlvalue, dom.Element):
  565. colonindex = xmlvalue.find(":")
  566. if colonindex == -1:
  567. self.name = xmlvalue
  568. else:
  569. self.name = xmlvalue[colonindex + 1:]
  570. self.ns = int(xmlvalue[:colonindex])
  571. return
  572. self.checkXML(xmlvalue)
  573. # Is a namespace index passed?
  574. if len(xmlvalue.getElementsByTagName("NamespaceIndex")) != 0:
  575. self.ns = int(xmlvalue.getElementsByTagName("NamespaceIndex")[0].firstChild.data)
  576. if len(xmlvalue.getElementsByTagName("Name")) != 0:
  577. self.name = xmlvalue.getElementsByTagName("Name")[0].firstChild.data
  578. def __str__(self):
  579. return "ns=" + str(self.ns) + ";" + str(self.name)
  580. class StatusCode(UInt32):
  581. def __init__(self, xmlelement=None):
  582. UInt32.__init__(self, xmlelement)
  583. class DiagnosticInfo(Value):
  584. def __init__(self, xmlelement=None):
  585. Value.__init__(self)
  586. if xmlelement:
  587. self.parseXML(xmlelement)
  588. def parseXML(self, xmlvalue):
  589. self.checkXML(xmlvalue)
  590. logger.warn("Not implemented")
  591. class Guid(Value):
  592. def __init__(self, xmlelement=None):
  593. Value.__init__(self)
  594. if xmlelement:
  595. self.parseXML(xmlelement)
  596. def parseXML(self, xmlvalue):
  597. self.checkXML(xmlvalue)
  598. if xmlvalue.firstChild is None:
  599. self.value = [0, 0, 0, 0] # Catch XML <Guid /> by setting the value to a default
  600. else:
  601. self.value = unicode(xmlvalue.firstChild.data)
  602. self.value = self.value.replace("{", "")
  603. self.value = self.value.replace("}", "")
  604. self.value = self.value.split("-")
  605. tmp = []
  606. for g in self.value:
  607. try:
  608. tmp.append(int("0x" + g, 16))
  609. except Exception:
  610. logger.error("Invalid formatting of Guid. Expected {01234567-89AB-CDEF-ABCD-0123456789AB}, got " + \
  611. unicode(xmlvalue.firstChild.data))
  612. tmp = [0, 0, 0, 0, 0]
  613. if len(tmp) != 5:
  614. logger.error("Invalid formatting of Guid. Expected {01234567-89AB-CDEF-ABCD-0123456789AB}, got " + \
  615. unicode(xmlvalue.firstChild.data))
  616. tmp = [0, 0, 0, 0]
  617. self.value = tmp