datatypes.py 25 KB

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