datatypes.py 25 KB

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