Main Page | Packages | Class Hierarchy | Alphabetical List | Class List | Directories | File List | Namespace Members | Class Members | Related Pages

gSchemaConfig.py

00001 #!/usr/local/bin/python
00002 #
00003 #                               Copyright 2002
00004 #                                     by
00005 #                        The Board of Trustees of the
00006 #                     Leland Stanford Junior University.
00007 #                            All rights reserved.
00008 #
00009 
00010 __facility__ = "Online"
00011 __abstract__ = """Build the GLAST LAT database schema and configuration from
00012 an XML defintion.
00013 """
00014 __author__  = "Selim Tuvi <stuvi@slac.stanford.edu> SLAC - GLAST LAT I&T/Online"
00015 __date__    = ("$Date: 2006/07/17 18:42:26 $").split(' ')[1]
00016 __version__ = "$Revision: 2.81 $"
00017 __release__ = "$Name: R04-12-00 $"
00018 __credits__ = "SLAC"
00019 
00020 import LATTE.copyright_SLAC
00021 
00022 
00023 import os
00024 import sys
00025 import inspect
00026 import types
00027 import logging          as     log
00028 import gc
00029 
00030 from xml.dom             import Node
00031 #from xml.dom.ext.reader import Sax2
00032 #from xml.dom.NodeFilter import NodeFilter
00033 #from xml.dom.ext        import PrettyPrint
00034 #from xml.dom            import implementation
00035 
00036 #import xml.dom.minidom  as minidom
00037 
00038 from Ft.Xml.Domlette import NonvalidatingReader, PrettyPrint, implementation
00039 from Ft.Lib          import Uri
00040 from Ft.Xml          import EMPTY_NAMESPACE
00041 
00042 from ihooks             import BasicModuleLoader
00043 
00044 from gGroup             import *
00045 
00046 from LATTE.client import gLog
00047 from LATTE.client import gBits
00048 from LATTE.client import gException
00049 
00050 # Default namespace for all XML files used by LATTE.
00051 # This currently has to be None or '' since we do not
00052 # currently qualify tags and attributes with a namespace.
00053 LAT_NAMESPACE = EMPTY_NAMESPACE
00054 
00055 # (tray, which) to layer map
00056 MAP_DETECTOR_TO_LAYER = {
00057                          (18, 'bot'): 'Y17',
00058                          (17, 'top'): 'X17',
00059                          (17, 'bot'): 'X16',
00060                          (16, 'top'): 'Y16',
00061                          (16, 'bot'): 'Y15',
00062                          (15, 'top'): 'X15',
00063                          (15, 'bot'): 'X14',
00064                          (14, 'top'): 'Y14',
00065                          (14, 'bot'): 'Y13',
00066                          (13, 'top'): 'X13',
00067                          (13, 'bot'): 'X12',
00068                          (12, 'top'): 'Y12',
00069                          (12, 'bot'): 'Y11',
00070                          (11, 'top'): 'X11',
00071                          (11, 'bot'): 'X10',
00072                          (10, 'top'): 'Y10',
00073                          (10, 'bot'): 'Y9',
00074                          ( 9, 'top'): 'X9',
00075                          ( 9, 'bot'): 'X8',
00076                          ( 8, 'top'): 'Y8',
00077                          ( 8, 'bot'): 'Y7',
00078                          ( 7, 'top'): 'X7',
00079                          ( 7, 'bot'): 'X6',
00080                          ( 6, 'top'): 'Y6',
00081                          ( 6, 'bot'): 'Y5',
00082                          ( 5, 'top'): 'X5',
00083                          ( 5, 'bot'): 'X4',
00084                          ( 4, 'top'): 'Y4',
00085                          ( 4, 'bot'): 'Y3',
00086                          ( 3, 'top'): 'X3',
00087                          ( 3, 'bot'): 'X2',
00088                          ( 2, 'top'): 'Y2',
00089                          ( 2, 'bot'): 'Y1',
00090                          ( 1, 'top'): 'X1',
00091                          ( 1, 'bot'): 'X0',
00092                          ( 0, 'top'): 'Y0'
00093                         }
00094 
00095 
00096 # layer to (cc lo, cc hi, rc) map
00097 MAP_LAYER_TO_CABLE = {
00098                         'Y17': (5,4,8),
00099                         'X17': (6,7,8),
00100                         'X16': (3,2,8),
00101                         'Y16': (0,1,8),
00102                         'Y15': (5,4,7),
00103                         'X15': (6,7,7),
00104                         'X14': (3,2,7),
00105                         'Y14': (0,1,7),
00106                         'Y13': (5,4,6),
00107                         'X13': (6,7,6),
00108                         'X12': (3,2,6),
00109                         'Y12': (0,1,6),
00110                         'Y11': (5,4,5),
00111                         'X11': (6,7,5),
00112                         'X10': (3,2,5),
00113                         'Y10': (0,1,5),
00114                         'Y9' : (5,4,4),
00115                         'X9' : (6,7,4),
00116                         'X8' : (3,2,4),
00117                         'Y8' : (0,1,4),
00118                         'Y7' : (5,4,3),
00119                         'X7' : (6,7,3),
00120                         'X6' : (3,2,3),
00121                         'Y6' : (0,1,3),
00122                         'Y5' : (5,4,2),
00123                         'X5' : (6,7,2),
00124                         'X4' : (3,2,2),
00125                         'Y4' : (0,1,2),
00126                         'Y3' : (5,4,1),
00127                         'X3' : (6,7,1),
00128                         'X2' : (3,2,1),
00129                         'Y2' : (0,1,1),
00130                         'Y1' : (5,4,0),
00131                         'X1' : (6,7,0),
00132                         'X0' : (3,2,0),
00133                         'Y0' : (0,1,0)
00134                      }
00135 
00136 # Minitower configuration
00137 #MINITOWER_MAP_LAYER_TO_CABLE = {
00138 #                                  'Y3' : (6,7,1),
00139 #                                  'X3' : (4,5,1),
00140 #                                  'X2' : (0,1,1),
00141 #                                  'Y2' : (2,3,1),
00142 #                                  'Y1' : (6,7,0),
00143 #                                  'X1' : (4,5,0),
00144 #                                  'X0' : (0,1,0),
00145 #                                  'Y0' : (2,3,0)
00146 #                              }
00147 
00148 MAP_TEM_TO_TOWER = {
00149                               #TEM_ID -> (col,row)
00150                               '0':(0,0),
00151                               '1':(1,0),
00152                               '2':(2,0),
00153                               '3':(3,0),
00154                               '4':(0,1),
00155                               '5':(1,1),
00156                               '6':(2,1),
00157                               '7':(3,1),
00158                               '8':(0,2),
00159                               '9':(1,2),
00160                               '10':(2,2),
00161                               '11':(3,2),
00162                               '12':(0,3),
00163                               '13':(1,3),
00164                               '14':(2,3),
00165                               '15':(3,3)
00166                    }
00167 
00168 VALID_NODES = ['GLAT','GTEM','GTIC','GCCC','GCRC','GCFE','GTCC','GTRC','GTFE',
00169                'GAEM','GAEQ','GARC','GAFE','GCRU','GEBM','GEBMC','GEBMST',
00170                'GGEM','GGEMC','GGEMMG','GGEMST','GGEMSC','GGEMVG','GGEMIE','GGEMW',
00171                'GXBRD','GTWR','GLCB','GPDU','GPEQ','GGLT','GSIU', 'GEPU']
00172 
00173 
00174 def readSchema(glat, fileName):
00175   """Reads a LAT schema/config document from an XML file
00176   and returns the object model
00177 
00178   Input ::
00179 
00180     (1) Filename of the XML
00181     (2) Optional active (connected) command client reference.
00182         Not needed if the document does not contain a 'configuration' section
00183 
00184   Output::
00185 
00186     GLAT root of the object model
00187 
00188   Usage::
00189 
00190     lat = readSchema('testSchema.xml')"""
00191   #reader = PyExpat.Reader()
00192   #doc = reader.fromStream(file(fileName,'r'))
00193 
00194   # Change the directory to the path of the schema file
00195   # in case the include files do not have absolute paths
00196   fn = "readSchema"
00197   curDir = os.getcwd()
00198   mainFilePath = os.path.dirname(fileName)
00199   mainFileName = os.path.basename(fileName)
00200   if mainFilePath != '': os.chdir(mainFilePath)
00201   try:
00202     #doc = Sax2.FromXmlFile(mainFileName)
00203     #doc = minidom.parse(mainFileName)
00204     file_uri = Uri.OsPathToUri(mainFileName, attemptAbsolute=1)
00205     doc = NonvalidatingReader.parseUri(file_uri)
00206   except Exception, e:
00207     if os.path.exists(curDir):
00208       os.chdir(curDir)
00209     log.exception("%s: Error parsing XML: %s" % (fn, mainFileName))
00210     raise e
00211 
00212   comments = []
00213   for n in doc.childNodes:
00214     if n.nodeType == Node.COMMENT_NODE:
00215       comments.append(n.data)
00216   tagName = doc.documentElement.tagName.lower()
00217   if tagName != "latdoc":
00218     log.error("%s: Invalid LAT document tag: %s" % (fn,tagName))
00219     if os.path.exists(curDir):
00220       os.chdir(curDir)
00221     return None
00222 
00223   includeFiles = []
00224   processIncludes(doc, doc.documentElement, includeFiles, mainFilePath)
00225 
00226   declarations =  { 'imports':{},
00227                     'groups':{},
00228                     'constraints':{('default','default'):{}},
00229                     'rules':{('default','default'):{}},
00230                     'egus':{('default','default'):{}},
00231                     'options':{'skipsystemoverrides':0,
00232                                'explicitbroadcastnodes':0,
00233                                'ignorehardwaretimeouts':0
00234                                },
00235                     'sysregs': {},
00236                   }
00237   deadChannels  = {'calib':{}, 'data':{}, 'trig':{}}
00238   noisyChannels = {'calib':{}, 'data':{}, 'trig':{}}
00239   name = str(getAttribute(doc.documentElement, 'name'))
00240   pNodeClass = glat.__class__.__name__
00241   isSchema = None
00242   for n in getChildNodes(doc.documentElement):
00243     if n.nodeType == Node.ELEMENT_NODE:
00244       tagname = str(n.tagName).lower()
00245       if  tagname == 'declarations':
00246         processDeclarations(1, n, declarations)
00247       elif tagname == 'constraints':
00248         processConstraints(n, declarations)
00249       elif tagname == 'rules':
00250         processRules(n, declarations)
00251       elif tagname == 'egus':
00252         processEGUs(n, declarations)
00253       elif tagname == 'schema':
00254         isSchema = 0
00255         xbrdExists = False
00256         for node in getChildNodes(n):
00257           if pNodeClass in gSCprocessRegistry.keys() and \
00258              pNodeClass.lower() == node.tagName.lower():
00259             isSchema = 1
00260             gSCprocessRegistry[pNodeClass](isSchema, glat, node, declarations)
00261           elif node.tagName.lower() == 'gxbrd':
00262             xbrdExists = True
00263 #           if pNodeClass == 'GLAT' and node.tagName.lower() == 'glat':
00264 #             processGLAT(isSchema=1, glat=glat,
00265 #                         node=node, declarations=declarations)
00266 #             break
00267 #           elif pNodeClass == 'GXBRD' and node.tagName.lower() == 'gxbrd':
00268 #             processGXBRD(isSchema=1, gxbrd=glat,
00269 #                         node=node, declarations=declarations)
00270 #             break
00271           # Silently skip other root tags for now.
00272           #else:
00273           #  log.error("%s: Unexpected tag: %s for root: %s" % (fn, node.tagName, glat.__class__.__name__))
00274       elif tagname == 'configuration':
00275         configName = ''
00276         configVersion = ''
00277         if hasAttribute(n, 'name'):
00278           configName = str(getAttribute(n, 'name'))
00279         if hasAttribute(n, 'version'):
00280           configVersion = str(getAttribute(n, 'version'))
00281         configs = glat.getConfigurations()
00282         configSeq = len(configs)
00283         configs[configSeq] = (n, configName, configVersion)
00284       elif tagname == 'badstrips' and pNodeClass == 'GLAT':
00285         typ = str(getAttribute(n, 'badType'))
00286         if typ == 'dead':
00287           processBadChannels(n, deadChannels)
00288         elif typ == 'hot':
00289           processBadChannels(n, noisyChannels)
00290         else:
00291           log.error("%s: Unrecognized bad strip type: %s" % (fn, typ))
00292         doc.documentElement.removeChild(n)
00293         gc.collect()
00294       elif tagname == 'opaque':
00295         addOpaque(glat, n)
00296       elif tagname == 'flags':
00297         for flag_glat in getChildNodes(n):
00298           if str(flag_glat.tagName).lower() == pNodeClass.lower():
00299             processFlags(glat, flag_glat)
00300       elif pNodeClass == 'GLAT':
00301         log.error("%s: Unexpected tag: %s" % (fn, n.tagName))
00302         if os.path.exists(curDir):
00303           os.chdir(curDir)
00304         return None
00305 
00306   # need to write some private attributes in the glat object, but there's no
00307   # guarantee of what the class's type actually is.  It doesn't matter if the
00308   # class doesn't have the attribute, this will create it.
00309   # Use the __dict__ and create the string on the fly.
00310   gname = glat.__class__.__name__
00311   gdict = glat.__dict__
00312   gdict["_" + gname + '__schemaName']        = name
00313   gdict["_" + gname + '__schemaComments']    = comments
00314   gdict["_" + gname + '__includeFiles']      = includeFiles
00315   gdict["_" + gname + '__declarations']      = declarations
00316   gdict["_" + gname + '__deadChannels']      = deadChannels
00317   gdict["_" + gname + '__noisyChannels']     = noisyChannels
00318 
00319   if gname == 'GXBRD':
00320     gxbrd = glat
00321   else:
00322     gdict["_" + gname + '__xbrdExists']     = xbrdExists
00323     gxbrd = None
00324   applyConfig(glat, seq=None, gxbrd=gxbrd, enableSystemOverrides=False, enableRegWrite=False)
00325 
00326   if os.path.exists(curDir):
00327     os.chdir(curDir)
00328   #PrettyPrint(doc, file("c:/projects/latte/tests/post.xml", "w"))
00329   if isSchema == 0:
00330     # A matching schema root tag (such as GLAT or GXBRD) was not found
00331     return None
00332   else:
00333     return glat
00334 
00335 def processFlags(gnode, xnode):
00336   fn = "processFlags"
00337 
00338   childNodes = []
00339   flags = {}
00340 
00341   for n in getChildNodes(xnode):
00342     tagname = str(n.tagName)
00343     if tagname in VALID_NODES:
00344       childNodes.append(n)
00345     else:
00346       flags[tagname] = str(n.firstChild.data.strip())
00347   if flags != {}:
00348     for (key, value) in flags.items():
00349       gnode.setFlag(key, value)
00350 
00351   for n in childNodes:
00352     tagname = str(n.tagName)
00353     if hasAttribute(n, 'ID'):
00354       seq = uncompressSequence(getAttribute(n, 'ID'))
00355       for nodeId in seq:
00356         downStr = "gnode."+ tagname[1:] + "[" + str(nodeId) + "]"
00357         try:
00358           cgnode = eval(downStr)
00359           processFlags(cgnode, n)
00360         except:
00361           log.error("%s: Error evaluating string %s" % (fn, downStr))
00362     else:
00363       downStr = "gnode."+ tagname[1:]
00364       try:
00365         cgnode = eval(downStr)
00366         processFlags(cgnode, n)
00367       except:
00368         log.error("%s: Error evaluating string %s" % (fn, downStr))
00369 
00370 def addOpaque(gnode, xnode):
00371   name = str(getAttribute(xnode, 'name'))
00372   root = gnode.root()
00373   rname = root.__class__.__name__
00374   rdict = root.__dict__
00375   opaque = rdict["_" + rname + '__opaque']
00376   if gnode in opaque:
00377     opaqueDict = opaque[gnode]
00378   else:
00379     opaqueDict = opaque[gnode] = {}
00380   if name in opaqueDict:
00381     if not opaqueExists(opaqueDict[name], xnode):
00382       opaqueDict[name].append(ConfigElement(xnode))
00383   else:
00384     opaqueDict[name] = [ConfigElement(xnode)]
00385 
00386 def opaqueExists(opaqueList, xnode):
00387   for opaque in opaqueList:
00388     if opaque._ConfigElement__dElement == xnode:
00389       return True
00390   return False
00391 
00392 def addSerialNos(gnode, snode):
00393   root = gnode.root()
00394   rname = root.__class__.__name__
00395   rdict = root.__dict__
00396   serialnos = rdict["_" + rname + '__serialnos']
00397   if gnode in serialnos:
00398     serialDict = serialnos[gnode]
00399   else:
00400     serialDict = serialnos[gnode] = {}
00401   for i in range(len(snode.attributes)):
00402     name  = str(snode.attributes.values()[i].name).lower()
00403     value = str(snode.attributes.values()[i].value)
00404     serialDict[name] = value
00405 
00406 def addExcludes(gnode, enode):
00407   root = gnode.root()
00408   rname = root.__class__.__name__
00409   rdict = root.__dict__
00410   excludes = rdict["_" + rname + '__excludes']
00411   if gnode in excludes:
00412     excludeList = excludes[gnode]
00413   else:
00414     excludeList = excludes[gnode] = []
00415   for i in range(len(enode.attributes)):
00416     name  = str(enode.attributes.values()[i].name).lower()
00417     value = str(enode.attributes.values()[i].value).lower()
00418     if value != "true":
00419       log.error("<exclude> tag attribute %s has invalid value %s. Only allowed value is 'True'"
00420                 % (name, value))
00421     elif name not in excludeList:
00422       excludeList.append(name)
00423 
00424 def processIncludes(doc, node, includeFiles, mainFilePath):
00425   fn = "processIncludes"
00426   for n in getChildNodes(node):
00427     if n.nodeType == Node.ELEMENT_NODE and n.tagName.lower() == 'include':
00428       incFileName = os.path.expandvars(str(getAttribute(n, 'filename')))
00429       incFilePath = os.path.dirname(incFileName)
00430       if incFilePath == '' and mainFilePath != '':
00431         incFileName = os.path.join(mainFilePath, incFileName)
00432       #incDoc = Sax2.FromXmlFile(incFileName)
00433       incFileName = os.path.normpath(os.path.abspath(incFileName))
00434       try:
00435         #incDoc = minidom.parse(incFileName)
00436         file_uri = Uri.OsPathToUri(incFileName, attemptAbsolute=1)
00437         incDoc = NonvalidatingReader.parseUri(file_uri)
00438       except Exception, e:
00439         log.exception("%s: Error parsing XML include: %s" % (fn, incFileName))
00440         raise e
00441       if incFileName not in includeFiles:
00442         includeFiles.append(incFileName)
00443       processIncludes(incDoc, incDoc.documentElement, includeFiles, mainFilePath)
00444       incDom = doc.importNode(incDoc.documentElement,1)
00445       node.replaceChild(incDom, n)
00446     else:
00447       processIncludes(doc, n, includeFiles, mainFilePath)
00448 
00449 def processConfigProperties(node, declarations):
00450   fn = "processConfigProperties"
00451   if node.nodeType == Node.ELEMENT_NODE:
00452     cfgTagname = node.tagName.lower()
00453     if cfgTagname == 'declarations':
00454       processDeclarations(0, node, declarations)
00455     elif cfgTagname == 'constraints':
00456       processConstraints(node, declarations)
00457     elif cfgTagname == 'rules':
00458       processRules(node, declarations)
00459     elif cfgTagname == 'egus':
00460       processEGUs(node, declarations)
00461     elif cfgTagname in ('glat', 'gglt', 'gxbrd', 'ghsk'):
00462       pass
00463     else:
00464       log.error("%s: Unrecognized configuration tag: %s" % (fn, cfgTagname))
00465 
00466 
00467 def readConfig(glat, cfgFileName):
00468   """Read a configuration XML file and add its DOM
00469   to the dictionary of configurations.
00470 
00471   \param  glat        Populated schema
00472   \param  cfgFileName Name of the configuration file in XML format
00473   \return             The numeric key value of the dictionary entry.
00474                       -1 if it fails to read the configuration file.
00475 
00476   """
00477   fn = "readConfig"
00478   curDir = os.getcwd()
00479   mainFilePath = os.path.dirname(cfgFileName)
00480   mainFileName = os.path.basename(cfgFileName)
00481   if mainFilePath != '': os.chdir(mainFilePath)
00482 
00483   try:
00484     #cfgDoc = Sax2.FromXmlFile(mainFileName)
00485     #cfgDoc = minidom.parse(mainFileName)
00486     file_uri = Uri.OsPathToUri(mainFileName, attemptAbsolute=1)
00487     cfgDoc = NonvalidatingReader.parseUri(file_uri)
00488   except:
00489     log.exception("%s: Error reading configuration file: %s" % (fn, cfgFileName))
00490     if os.path.exists(curDir):
00491       os.chdir(curDir)
00492     return -1
00493 
00494   cfgNode = cfgDoc.documentElement
00495 
00496   includeFiles = []
00497   processIncludes(cfgDoc, cfgNode, includeFiles, mainFilePath)
00498   glat._GLAT__includeFiles += includeFiles
00499   #cfgDom = cfgDoc.importNode(cfgDoc,1)
00500   cfgDict = glat.getConfigurations()
00501   configSeq = len(cfgDict)
00502   configName = ''
00503   configVersion = ''
00504   if hasAttribute(cfgNode, 'name'):
00505     configName = str(getAttribute(cfgNode, 'name'))
00506   if hasAttribute(cfgNode, 'version'):
00507     configVersion = str(getAttribute(cfgNode, 'version'))
00508 
00509   cfgDict[configSeq] = (cfgNode, configName, configVersion)
00510   if os.path.exists(curDir):
00511     os.chdir(curDir)
00512   return configSeq
00513 
00514 def applyConfig(glat, seq=None, gxbrd=None, enableSystemOverrides=True, enableRegWrite=True):
00515   """Applies the configuration that may have existed when the schema is read.
00516      The configuration portion of the schema is stored as a DOM reference
00517      in the GLAT node. This function accesses that DOM and sets the registers
00518      accordingly
00519 
00520   Input ::
00521 
00522     (1) GLAT root of the object model
00523     (2) Optional sequence number of the configuration
00524 
00525   Output: None
00526 
00527   Usage::
00528 
00529     applyConfig(lat)"""
00530 
00531   fn = "applyConfig"
00532   options = glat.getDeclarations()['options']
00533   if enableSystemOverrides:
00534     options['__systemoverrides'] = True
00535   else:
00536     options['__systemoverrides'] = False
00537   if enableRegWrite:
00538     options['__regwrite'] = True
00539   else:
00540     options['__regwrite'] = False
00541   configs = []
00542   if seq is None:
00543     if len(glat.getConfigurations()) == 0:
00544       log.debug("%s: Nothing to do, no configuration exists" % fn)
00545     else:
00546       glat.getDeclarations()['sysregs'] = {}
00547       configSeqList = glat.getConfigurations().keys()
00548       configSeqList.sort()
00549       for seq in configSeqList:
00550         configs.append(glat.getConfigurations()[seq][0])
00551   elif type(seq) == types.IntType:
00552     if glat.getConfigurations().has_key(seq):
00553       configs.append(glat.getConfigurations()[seq][0])
00554     else:
00555       log.error("%s: Configuration with sequence %d could not be found" % (fn, seq))
00556       return
00557 
00558   for config in configs:
00559     for n in getChildNodes(config):
00560       processConfigProperties(n, glat.getDeclarations())
00561       if n.nodeType == Node.ELEMENT_NODE:
00562         tagname = n.tagName.lower()
00563         if tagname == 'glat' and glat.__class__.__name__ == 'GLAT':
00564           if hasAttribute(config, 'name'):
00565             configName = getAttribute(config, 'name')
00566           else:
00567             configName = '(no name)'
00568           log.debug("%s: Applying LAT configuration: %s" % (fn, configName))
00569           processGLAT(isSchema=0, glat=glat,
00570                       node=n, declarations=glat.getDeclarations())
00571         elif tagname == 'gxbrd':
00572           if hasAttribute(config, 'name'):
00573             configName = getAttribute(config, 'name')
00574           else:
00575             configName = '(no name)'
00576           if gxbrd is not None:
00577             log.debug("%s: Applying XBRD configuration: %s" % (fn, configName))
00578             processGXBRD(isSchema=0, gxbrd=gxbrd,
00579                       node=n, declarations=glat.getDeclarations())
00580           # XBRD configuration should be optional -ST
00581           #else:
00582           #  log.warn("skipping XBRD configuration, no gXBRD given")
00583   options = glat.getDeclarations()['options']
00584   skipSystemOverrides = options['skipsystemoverrides']
00585   skipSystemOverrides = skipSystemOverrides or (not options['__systemoverrides'])
00586   if not skipSystemOverrides:
00587     configureSystem(glat, glat.TEM.keys())
00588 
00589 def processGLAT(isSchema, glat, node, declarations):
00590   fn = "processGLAT"
00591   node = checkForDuplicateNode(node)
00592   for n in getChildNodes(node):
00593     tagName = n.tagName.lower()
00594     if tagName == 'gtem':
00595       processGTEM(isSchema, glat, n, declarations)
00596     elif tagName == 'gaem':
00597       processGAEM(isSchema, glat, n, declarations)
00598     elif tagName == 'gpdu':
00599       processGPDU(isSchema, glat, n, declarations)
00600     elif tagName == 'gebm':
00601       processGEBM(isSchema, glat, n, declarations)
00602     elif tagName == 'ggem':
00603       processGGEM(isSchema, glat, n, declarations)
00604     elif tagName == 'gcru':
00605       processGCRU(isSchema, glat, n, declarations)
00606     elif tagName == 'gsiu':
00607       processGSIU(isSchema, glat, n, declarations)
00608     elif tagName == 'gepu':
00609       processGEPU(isSchema, glat, n, declarations)
00610     elif tagName == 'opaque':
00611       addOpaque(glat, n)
00612     elif isSchema:
00613       log.error("%s: Unexpected tag: %s" % (fn, n.tagName))
00614     elif tagName == 'serialnos':
00615       addSerialNos(glat, n)
00616     elif tagName == 'exclude':
00617       addExcludes(glat, n)
00618     elif tagName in glat.regs:
00619       setRegister(glat.regs[tagName], n, declarations)
00620     else:
00621       log.error("%s: Configuration error processing GLAT...Invalid register %s" % (fn, n.tagName))
00622 
00623   return glat
00624 
00625 def setRegister(gattr, node, declarations):
00626   fn = "setRegister"
00627 
00628   if hasAttribute(node, 'constraint'):
00629     gNode = gattr.getNode()
00630     if gNode.getName() in ('GTIC', 'GAEQ', 'GPEQ'):
00631       gNode = gNode.up()
00632     serialNos = gNode.getSerialNos()
00633     consName = str(getAttribute(node, 'constraint'))
00634     if serialNos is not None:
00635       for (sId, sVal) in serialNos.items():
00636         if (sId, sVal) in declarations['constraints'] and \
00637            consName in declarations['constraints'][(sId, sVal)]:
00638           constraints = declarations['constraints'][(sId, sVal)]
00639           break
00640       else:
00641         constraints = declarations['constraints'][('default','default')]
00642     else:
00643       constraints = declarations['constraints'][('default','default')]
00644     cons = constraints[consName]
00645     if cons is not None:
00646       gattr.setConstraint(cons)
00647 
00648   if hasAttribute(node, 'egu'):
00649     gNode = gattr.getNode()
00650     if gNode.getName() in ('GTIC', 'GAEQ', 'GPEQ'):
00651       gNode = gNode.up()
00652     eguName = str(getAttribute(node, 'egu'))
00653     serialNos = gNode.getSerialNos()
00654     if serialNos is not None:
00655       for (sId, sVal) in serialNos.items():
00656         if (sId, sVal) in declarations['egus'] and \
00657            eguName in declarations['egus'][(sId, sVal)]:
00658           egus = declarations['egus'][(sId, sVal)]
00659           break
00660       else:
00661         egus = declarations['egus'][('default','default')]
00662     else:
00663       egus = declarations['egus'][('default','default')]
00664     egu = egus[eguName]
00665     if egu is not None:
00666       gattr.setEGU(egu)
00667 
00668   if hasAttribute(node, 'rule'):
00669     gNode = gattr.getNode()
00670     if gNode.getName() in ('GTIC', 'GAEQ', 'GPEQ'):
00671       gNode = gNode.up()
00672     ruleName = str(getAttribute(node, 'rule'))
00673     serialNos = gNode.getSerialNos()
00674     if serialNos is not None:
00675       for (sId, sVal) in serialNos.items():
00676         if (sId, sVal) in declarations['rules'] and \
00677            ruleName in declarations['rules'][(sId, sVal)]:
00678           rules = declarations['rules'][(sId, sVal)]
00679           break
00680       else:
00681         rules = declarations['rules'][('default','default')]
00682     else:
00683       rules = declarations['rules'][('default','default')]
00684     rule = rules[ruleName]
00685     if rule is not None:
00686       gattr.setRule(rule)
00687 
00688   regVal = None
00689   if node.firstChild is not None and not gattr.isReadOnly():
00690     regVal = extractRegisterValue(node)
00691     if declarations['options']['__regwrite'] and 'nowrite' not in gattr.getNode().getExcludeFlags():
00692       try:
00693         gattr.set(regVal, bypass=1)
00694       except:
00695         log.error("%s: Error setting register %s.%s" % (fn, gattr.getNode().getName(), gattr.getName()))
00696         log.exception("")
00697   return regVal
00698 
00699 def extractRegisterValue(node):
00700   regVal = node.firstChild.data.strip()
00701   if regVal.startswith('0x'):
00702     regVal = long(regVal,16)
00703   else:
00704     regVal = long(regVal)
00705   return regVal
00706 
00707 def processGXBRD(isSchema, gxbrd, node, declarations):
00708   fn = "processGXBRD"
00709   node = checkForDuplicateNode(node)
00710   for n in getChildNodes(node):
00711     tagName = n.tagName.lower()
00712     if tagName == 'gtwr':
00713       processGTWR(isSchema, gxbrd, n, declarations)
00714     elif tagName == 'gglt':
00715       processGGLT(isSchema, gxbrd, n, declarations)
00716     elif isSchema:
00717       log.error("%s: Unexpected tag: %s" % (fn, n.tagName))
00718     elif tagName in gxbrd.regs:
00719       setRegister(gxbrd.regs[tagName], n, declarations)
00720     else:
00721       log.error("%s: Configuration error processing GXBRD...Invalid register %s" % (fn, n.tagName))
00722   return gxbrd
00723 
00724 
00725 def processGTWR(isSchema, gxbrd, node, declarations):
00726   fn = "processGTWR"
00727   if hasAttribute(node, 'ID'):
00728     gtwrIdSeq = uncompressSequence(getAttribute(node, 'ID'))
00729   else:
00730     log.error("%s: Configuration error processing GTWR...Missing ID" % fn)
00731     return
00732   for gtwrId in gtwrIdSeq:
00733     if isSchema:
00734       gtwr = gxbrd._GXBRD__addTWR(gtwrId)
00735     elif gxbrd.existsTWR(gtwrId):
00736       gtwr = gxbrd.TWR[gtwrId]
00737     else:
00738       #log.debug("%s: Configuration error processing GTWR # %d ...Not populated" % (fn, gtwrId))
00739       continue
00740     node = checkForDuplicateNode(node)
00741     for n in getChildNodes(node):
00742       tagName = n.tagName.lower()
00743       if tagName == 'opaque':
00744         addOpaque(gtwr, n)
00745       elif isSchema:
00746         log.error("%s: Unexpected tag: %s" % (fn, n.tagName))
00747       elif tagName == 'serialnos':
00748         addSerialNos(gtwr, n)
00749       elif tagName == 'exclude':
00750         addExcludes(gtwr, n)
00751       elif tagName in gtwr.regs:
00752         setRegister(gtwr.regs[tagName], n, declarations)
00753       else:
00754         log.error("%s: Configuration error processing GTWR # %d ...Invalid register %s" % (fn, gtwrId, n.tagName))
00755 
00756 def processGGLT(isSchema, gxbrd, node, declarations):
00757   fn = "processGGLT"
00758   if isSchema:
00759     gglt = gxbrd._GXBRD__addGLT()
00760   elif gxbrd.downGLT() != None:
00761     gglt = gxbrd.downGLT()
00762   else:
00763     #log.debug("%s: Configuration error processing GGLT...Not populated" % fn)
00764     return
00765   node = checkForDuplicateNode(node)
00766   for n in getChildNodes(node):
00767     tagName = n.tagName.lower()
00768     if tagName == 'opaque':
00769       addOpaque(gglt, n)
00770     elif isSchema:
00771       log.error("%s: Unexpected tag: %s" % (fn, n.tagName))
00772     elif tagName == 'serialnos':
00773       addSerialNos(gglt, n)
00774     elif tagName == 'exclude':
00775       addExcludes(gglt, n)
00776     elif tagName in gglt.regs:
00777       setRegister(gglt.regs[tagName], n, declarations)
00778     else:
00779       log.error("%s: Configuration error processing GGLT...Invalid register %s" % (fn, n.tagName))
00780 
00781 def processGPDU(isSchema, glat, node, declarations):
00782   fn = "processGPDU"
00783   if hasAttribute(node, 'ID'):
00784     gpduIdSeq = uncompressSequence(getAttribute(node, 'ID'))
00785   else:
00786     log.error("%s: Configuration error processing GPDU...Missing ID" % fn)
00787     return
00788 
00789   for gpduId in gpduIdSeq:
00790     if isSchema:
00791       gpdu = glat._GLAT__addPDU(gpduId)
00792     elif glat.existsPDU(gpduId):
00793       gpdu = glat.downPDU(gpduId)
00794     else:
00795       #log.debug("%s: Configuration error processing GPDU...Not populated" % fn)
00796       return
00797 
00798     node = checkForDuplicateNode(node)
00799     for n in getChildNodes(node):
00800       tagName = n.tagName.lower()
00801       if tagName == 'gpeq':
00802         processGPEQ(isSchema, gpdu, n, declarations)
00803       elif tagName == 'opaque':
00804         addOpaque(gpdu, n)
00805       elif isSchema:
00806         log.error("%s: Unexpected tag: %s" % (fn, n.tagName))
00807       elif tagName == 'serialnos':
00808         addSerialNos(gpdu, n)
00809       elif tagName == 'exclude':
00810         addExcludes(gpdu, n)
00811       elif tagName in gpdu.regs:
00812         setRegister(gpdu.regs[tagName], n, declarations)
00813       else:
00814         log.error("%s: Configuration error processing GPDU...Invalid register %s" % (fn, n.tagName))
00815 
00816 
00817 def processGPEQ(isSchema, gpdu, node, declarations):
00818   fn = "processGPEQ"
00819   if isSchema:
00820     gpeq = gpdu._GPDU__addPEQ()
00821   elif gpdu.existsPEQ():
00822     gpeq = gpdu.downPEQ()
00823   else:
00824     #log.debug("%s: Configuration error processing GPEQ...Not populated" % fn)
00825     return
00826   node = checkForDuplicateNode(node)
00827   for n in getChildNodes(node):
00828     tagName = n.tagName.lower()
00829     if tagName == 'opaque':
00830       addOpaque(gpeq, n)
00831     elif isSchema:
00832       log.error("%s: Unexpected tag: %s" % (fn, n.tagName))
00833     elif tagName == 'serialnos':
00834       addSerialNos(gpeq, n)
00835     elif tagName == 'exclude':
00836       addExcludes(gpeq, n)
00837     elif tagName in gpeq.regs:
00838       setRegister(gpeq.regs[tagName], n, declarations)
00839     else:
00840       log.error("%s: Configuration error processing GPEQ...Invalid register %s" % (fn, n.tagName))
00841 
00842 def processGEBM(isSchema, glat, node, declarations):
00843   fn = "processGEBM"
00844   if isSchema:
00845     gebm = glat._GLAT__addEBM()
00846   elif glat.existsEBM():
00847     gebm = glat.downEBM()
00848   else:
00849     #log.debug("%s: Configuration error processing GEBM...Not populated" % fn)
00850     return
00851   node = checkForDuplicateNode(node)
00852   for n in getChildNodes(node):
00853     tagName = n.tagName.lower()
00854     if tagName == 'gebmc':
00855       processGEBMC(isSchema, gebm, n, declarations)
00856     elif tagName == 'gebmst':
00857       processGEBMST(isSchema, gebm, n, declarations)
00858     elif tagName == 'opaque':
00859       addOpaque(gebm, n)
00860     elif isSchema:
00861       log.error("%s: Unexpected tag: %s" % (fn, n.tagName))
00862     elif tagName == 'serialnos':
00863       addSerialNos(gebm, n)
00864     elif tagName == 'exclude':
00865       addExcludes(gebm, n)
00866     elif tagName in gebm.regs:
00867       setRegister(gebm.regs[tagName], n, declarations)
00868     else:
00869       log.error("%s: Configuration error processing GEBM...Invalid register %s" % (fn, n.tagName))
00870 
00871 def processGEBMC(isSchema, gebm, node, declarations):
00872   fn = "processGEBMC"
00873   if isSchema:
00874     gebmc = gebm._GEBM__addEBMC()
00875   elif gebm.existsEBMC():
00876     gebmc = gebm.downEBMC()
00877   else:
00878     #log.debug("%s: Configuration error processing GEBMC...Not populated" % fn)
00879     return
00880   node = checkForDuplicateNode(node)
00881   for n in getChildNodes(node):
00882     tagName = n.tagName.lower()
00883     if tagName == 'opaque':
00884       addOpaque(gebmc, n)
00885     elif isSchema:
00886       log.error("%s: Unexpected tag: %s" % (fn, n.tagName))
00887     elif tagName == 'serialnos':
00888       addSerialNos(gebmc, n)
00889     elif tagName == 'exclude':
00890       addExcludes(gebmc, n)
00891     elif tagName in gebmc.regs:
00892       regVal = setRegister(gebmc.regs[tagName], n, declarations)
00893       if tagName in  ('timeout'):
00894         setSysReg(declarations, gebmc, tagName, regVal)
00895     else:
00896       log.error("%s: Configuration error processing GEBMC...Invalid register %s" % (fn, n.tagName))
00897 
00898 def processGEBMST(isSchema, gebm, node, declarations):
00899   fn = "processGEBMST"
00900   if isSchema:
00901     gebmst = gebm._GEBM__addEBMST()
00902   elif gebm.existsEBMST():
00903     gebmst = gebm.downEBMST()
00904   else:
00905     #log.debug("%s: Configuration error processing GEBMST...Not populated" % fn)
00906     return
00907   node = checkForDuplicateNode(node)
00908   for n in getChildNodes(node):
00909     tagName = n.tagName.lower()
00910     if tagName == 'opaque':
00911       addOpaque(gebmst, n)
00912     elif isSchema:
00913       log.error("%s: Unexpected tag: %s" % (fn, n.tagName))
00914     elif tagName == 'serialnos':
00915       addSerialNos(gebmst, n)
00916     elif tagName == 'exclude':
00917       addExcludes(gebmst, n)
00918     elif tagName in gebmst.regs:
00919       setRegister(gebmst.regs[tagName], n, declarations)
00920     else:
00921       log.error("%s: Configuration error processing GEBMST...Invalid register %s" % (fn, n.tagName))
00922 
00923 def processGGEM(isSchema, glat, node, declarations):
00924   fn = "processGGEM"
00925   if isSchema:
00926     ggem = glat._GLAT__addGEM()
00927   elif glat.existsGEM():
00928     ggem = glat.GEM
00929   else:
00930     #log.debug("%s: Configuration error processing GGEM...Not populated" % fn)
00931     return
00932   node = checkForDuplicateNode(node)
00933   for n in getChildNodes(node):
00934     tagName = n.tagName.lower()
00935     if tagName == 'ggemc':
00936       processGGEMC(isSchema, ggem, n, declarations)
00937     elif tagName == 'ggemmg':
00938       processGGEMMG(isSchema, ggem, n, declarations)
00939     elif tagName == 'ggemst':
00940       processGGEMST(isSchema, ggem, n, declarations)
00941     elif tagName == 'ggemsc':
00942       processGGEMSC(isSchema, ggem, n, declarations)
00943     elif tagName == 'ggemvg':
00944       processGGEMVG(isSchema, ggem, n, declarations)
00945     elif tagName == 'ggemie':
00946       processGGEMIE(isSchema, ggem, n, declarations)
00947     elif tagName == 'ggemw':
00948       processGGEMW(isSchema, ggem, n, declarations)
00949     elif tagName == 'opaque':
00950       addOpaque(ggem, n)
00951     elif isSchema:
00952       log.error("%s: Unexpected tag: %s" % (fn, n.tagName))
00953     elif tagName == 'serialnos':
00954       addSerialNos(ggem, n)
00955     elif tagName == 'exclude':
00956       addExcludes(ggem, n)
00957     elif tagName in ggem.regs:
00958       setRegister(ggem.regs[tagName], n, declarations)
00959     else:
00960       log.error("%s: Configuration error processing GGEM...Invalid register %s" % (fn, n.tagName))
00961 
00962 def processGGEMC(isSchema, ggem, node, declarations):
00963   fn = "processGGEMC"
00964   if isSchema:
00965     ggemc = ggem._GGEM__addGEMC()
00966   elif ggem.existsGEMC():
00967     ggemc = ggem.downGEMC()
00968   else:
00969     #log.debug("%s: Configuration error processing GGEMC...Not populated" % fn)
00970     return
00971   node = checkForDuplicateNode(node)
00972   for n in getChildNodes(node):
00973     tagName = n.tagName.lower()
00974     if tagName == 'opaque':
00975       addOpaque(ggemc, n)
00976     elif isSchema:
00977       log.error("%s: Unexpected tag: %s" % (fn, n.tagName))
00978     elif tagName == 'serialnos':
00979       addSerialNos(ggemc, n)
00980     elif tagName == 'exclude':
00981       addExcludes(ggemc, n)
00982     elif tagName in ggemc.regs:
00983       setRegister(ggemc.regs[tagName], n, declarations)
00984     else:
00985       log.error("%s: Configuration error processing GGEMC...Invalid register %s" % (fn, n.tagName))
00986 
00987 def processGGEMMG(isSchema, ggem, node, declarations):
00988   fn = "processGGEMMG"
00989   if isSchema:
00990     ggemmg = ggem._GGEM__addGEMMG()
00991   elif ggem.existsGEMMG():
00992     ggemmg = ggem.downGEMMG()
00993   else:
00994     #log.debug("%s: Configuration error processing GGEMMG...Not populated" % fn)
00995     return
00996   node = checkForDuplicateNode(node)
00997   for n in getChildNodes(node):
00998     tagName = n.tagName.lower()
00999     if tagName == 'opaque':
01000       addOpaque(ggemmg, n)
01001     elif isSchema:
01002       log.error("%s: Unexpected tag: %s" % (fn, n.tagName))
01003     elif tagName == 'serialnos':
01004       addSerialNos(ggemmg, n)
01005     elif tagName == 'exclude':
01006       addExcludes(ggemmg, n)
01007     elif tagName in ggemmg.regs:
01008       setRegister(ggemmg.regs[tagName], n, declarations)
01009     else:
01010       log.error("%s: Configuration error processing GGEMMG...Invalid register %s" % (fn, n.tagName))
01011 
01012 def processGGEMST(isSchema, ggem, node, declarations):
01013   fn = "processGGEMST"
01014   if isSchema:
01015     ggemst = ggem._GGEM__addGEMST()
01016   elif ggem.existsGEMST():
01017     ggemst = ggem.downGEMST()
01018   else:
01019     #log.debug("%s: Configuration error processing GGEMST...Not populated" % fn)
01020     return
01021   node = checkForDuplicateNode(node)
01022   for n in getChildNodes(node):
01023     tagName = n.tagName.lower()
01024     if tagName == 'opaque':
01025       addOpaque(ggemst, n)
01026     elif isSchema:
01027       log.error("%s: Unexpected tag: %s" % (fn, n.tagName))
01028     elif tagName == 'serialnos':
01029       addSerialNos(ggemst, n)
01030     elif tagName == 'exclude':
01031       addExcludes(ggemst, n)
01032     elif tagName in ggemst.regs:
01033       setRegister(ggemst.regs[tagName], n, declarations)
01034     else:
01035       log.error("%s: Configuration error processing GGEMST...Invalid register %s" % (fn, n.tagName))
01036 
01037 def processGGEMSC(isSchema, ggem, node, declarations):
01038   fn = "processGGEMSC"
01039   if isSchema:
01040     ggemsc = ggem._GGEM__addGEMSC()
01041   elif ggem.existsGEMSC():
01042     ggemsc = ggem.downGEMSC()
01043   else:
01044     #log.debug("%s: Configuration error processing GGEMSC...Not populated" % fn)
01045     return
01046   node = checkForDuplicateNode(node)
01047   for n in getChildNodes(node):
01048     tagName = n.tagName.lower()
01049     if tagName == 'opaque':
01050       addOpaque(ggemsc, n)
01051     elif isSchema:
01052       log.error("%s: Unexpected tag: %s" % (fn, n.tagName))
01053     elif tagName == 'serialnos':
01054       addSerialNos(ggemsc, n)
01055     elif tagName == 'exclude':
01056       addExcludes(ggemsc, n)
01057     elif tagName in ggemsc.regs:
01058       setRegister(ggemsc.regs[tagName], n, declarations)
01059     else:
01060       log.error("%s: Configuration error processing GGEMSC...Invalid register %s" % (fn, n.tagName))
01061 
01062 def processGGEMVG(isSchema, ggem, node, declarations):
01063   fn = "processGGEMVG"
01064   if isSchema:
01065     ggemvg = ggem._GGEM__addGEMVG()
01066   elif ggem.existsGEMVG():
01067     ggemvg = ggem.downGEMVG()
01068   else:
01069     #log.debug("%s: Configuration error processing GGEMVG...Not populated" % fn)
01070     return
01071   node = checkForDuplicateNode(node)
01072   for n in getChildNodes(node):
01073     tagName = n.tagName.lower()
01074     if tagName == 'opaque':
01075       addOpaque(ggemvg, n)
01076     elif isSchema:
01077       log.error("%s: Unexpected tag: %s" % (fn, n.tagName))
01078     elif tagName == 'serialnos':
01079       addSerialNos(ggemvg, n)
01080     elif tagName == 'exclude':
01081       addExcludes(ggemvg, n)
01082     elif tagName in ggemvg.regs:
01083       setRegister(ggemvg.regs[tagName], n, declarations)
01084     else:
01085       log.error("%s: Configuration error processing GGEMVG...Invalid register %s" % (fn, n.tagName))
01086 
01087 def processGGEMIE(isSchema, ggem, node, declarations):
01088   fn = "processGGEMIE"
01089   if isSchema:
01090     ggemie = ggem._GGEM__addGEMIE()
01091   elif ggem.existsGEMIE():
01092     ggemie = ggem.downGEMIE()
01093   else:
01094     #log.debug("%s: Configuration error processing GGEMIE...Not populated" % fn)
01095     return
01096   node = checkForDuplicateNode(node)
01097   for n in getChildNodes(node):
01098     tagName = n.tagName.lower()
01099     if tagName == 'opaque':
01100       addOpaque(ggemie, n)
01101     elif isSchema:
01102       log.error("%s: Unexpected tag: %s" % (fn, n.tagName))
01103     elif tagName == 'serialnos':
01104       addSerialNos(ggemie, n)
01105     elif tagName == 'exclude':
01106       addExcludes(ggemie, n)
01107     elif tagName in ggemie.regs:
01108       setRegister(ggemie.regs[tagName], n, declarations)
01109     else:
01110       log.error("%s: Configuration error processing GGEMIE...Invalid register %s" % (fn, n.tagName))
01111 
01112 def processGGEMW(isSchema, ggem, node, declarations):
01113   fn = "processGGEMW"
01114   if isSchema:
01115     ggemw = ggem._GGEM__addGEMW()
01116   elif ggem.existsGEMW():
01117     ggemw = ggem.downGEMW()
01118   else:
01119     #log.debug("%s: Configuration error processing GGEMW...Not populated" % fn)
01120     return
01121   node = checkForDuplicateNode(node)
01122   for n in getChildNodes(node):
01123     tagName = n.tagName.lower()
01124     if tagName == 'opaque':
01125       addOpaque(ggemw, n)
01126     elif isSchema:
01127       log.error("%s: Unexpected tag: %s" % (fn, n.tagName))
01128     elif tagName == 'serialnos':
01129       addSerialNos(ggemw, n)
01130     elif tagName == 'exclude':
01131       addExcludes(ggemw, n)
01132     elif tagName in ggemw.regs:
01133       setRegister(ggemw.regs[tagName], n, declarations)
01134     else:
01135       log.error("%s: Configuration error processing GGEMW...Invalid register %s" % (fn, n.tagName))
01136 
01137 
01138 def processGCRU(isSchema, glat, node, declarations):
01139   fn = "processGCRU"
01140   if isSchema:
01141     gcru = glat._GLAT__addCRU()
01142   elif glat.existsCRU():
01143     gcru = glat.downCRU()
01144   else:
01145     #log.debug("%s: Configuration error processing GCRU...Not populated" % fn)
01146     return
01147   node = checkForDuplicateNode(node)
01148   for n in getChildNodes(node):
01149     tagName = n.tagName.lower()
01150     if tagName == 'opaque':
01151       addOpaque(gcru, n)
01152     elif isSchema:
01153       log.error("%s: Unexpected tag: %s" % (fn, n.tagName))
01154     elif tagName == 'serialnos':
01155       addSerialNos(gcru, n)
01156     elif tagName == 'exclude':
01157       addExcludes(gcru, n)
01158     elif tagName in gcru.regs:
01159       setRegister(gcru.regs[tagName], n, declarations)
01160     else:
01161       log.error("%s: Configuration error processing GCRU...Invalid register %s" % (fn, n.tagName))
01162 
01163 
01164 def processGTEM(isSchema, glat, node, declarations):
01165   fn = "processGTEM"
01166   explicitBroadcastNodes = declarations['options']['explicitbroadcastnodes']
01167   skipSystemOverrides = declarations['options']['skipsystemoverrides']
01168   # LHM for multiple tem ancillary files, allow configurations embedded in TEM nodes.
01169   # this method will simply remove the configuration level similar to duplicate node.
01170   if not isSchema:
01171     node = checkForConfigurationNode(node)
01172   node = checkForDuplicateNode(node)
01173   if hasAttribute(node, 'ID'):
01174     gtemIdSeq = uncompressSequence(getAttribute(node, 'ID'))
01175     if isSchema and not explicitBroadcastNodes:
01176       gtemIdSeq += [255]
01177   else:
01178     if not explicitBroadcastNodes:
01179       gtemIdSeq = [255]
01180     else:
01181       log.error("%s: Missing ID attribute for GTEM tag" % fn)
01182       return
01183 
01184   #if not isSchema and not skipSystemOverrides:
01185   #  configureSystem(glat, gtemIdSeq, node)
01186 
01187   for gtemId in gtemIdSeq:
01188     if isSchema:
01189       if gtemId == 255 and glat.existsTEM(255):
01190         gtem = glat.allTEM()
01191       else:
01192         gtem = glat._GLAT__addTEM(gtemId)
01193     elif glat.existsTEM(gtemId):
01194       gtem = glat.downTEM(gtemId)
01195     else:
01196       #log.debug("%s: Configuration error processing GTEM # %d ...Not populated" % (fn, gtemId))
01197       continue
01198     for n in getChildNodes(node):
01199       tagName = str(n.tagName.lower())
01200       if tagName == 'gccc':
01201         processGCCC(isSchema, gtem, n, declarations)
01202       elif tagName == 'gtcc':
01203         processGTCC(isSchema, gtem, n, declarations)
01204       elif tagName == 'gtic':
01205         processGTIC(isSchema, gtem, n, declarations)
01206       elif tagName == 'opaque':
01207         addOpaque(gtem, n)
01208       elif isSchema:
01209         log.error("%s: Unexpected tag: %s" % (fn, n.tagName))
01210       elif tagName == 'serialnos':
01211         addSerialNos(gtem, n)
01212       elif tagName == 'exclude':
01213         addExcludes(gtem, n)
01214       elif tagName == 'badstrips':
01215         gname = glat.__class__.__name__
01216         gdict = glat.__dict__
01217         deadChannels  = gdict["_" + gname + '__deadChannels']
01218         noisyChannels = gdict["_" + gname + '__noisyChannels']
01219         typ = str(getAttribute(n, 'badType'))
01220         if typ == 'dead':
01221           processBadChannels(n, deadChannels, temId=gtemId)
01222         elif typ == 'hot':
01223           processBadChannels(n, noisyChannels, temId=gtemId)
01224         else:
01225           log.error("%s: Unrecognized bad strip type: %s" % (fn, typ))
01226         node.removeChild(n)
01227         gc.collect()
01228       elif tagName in gtem.regs:
01229         if tagName == "cmd_reset":
01230           if not skipSystemOverrides:
01231             #Ignore any attempts to reset the TEM through the schema
01232             log.debug("%s: Ignoring TEM[%d].CMD_RESET coming from the schema" % (fn, gtemId))
01233             continue
01234           else:
01235             log.warn("%s: Doing TEM[%d].CMD_RESET as per the schema" % (fn, gtemId))
01236         elif tagName == "address":
01237           if not skipSystemOverrides:
01238             #Ignore any attempts to change the TEM address through the schema
01239             log.debug("%s: Ignoring TEM[%d].ADDRESS coming from the schema" % (fn, gtemId))
01240             continue
01241           else:
01242             log.warn("%s: Setting TEM[%d].ADDRESS as per the schema" % (fn, gtemId))
01243         regVal = setRegister(gtem.regs[tagName], n, declarations)
01244         if tagName in  ('configuration', 'status', 'command_response', 'data_masks'):
01245           setSysReg(declarations, gtem, tagName, regVal)
01246       else:
01247         log.error("%s: Configuration error processing GTEM # %d ...Invalid register %s" % (fn, gtemId, n.tagName))
01248 
01249 def setSysReg(declarations, node, regName, value):
01250   """\brief Record the system register if specified in the schema.
01251 
01252   \param declarations Declarations dictionary.
01253   \param node         Node where the system register is specified.
01254   \param regName      System register name.
01255   \param value        System register value as specified in the configuration(s).
01256 
01257   """
01258   sysRegDict = declarations['sysregs']
01259   nodeName = node.getName()
01260   idTuple = node.getIdTuple()
01261   if nodeName not in sysRegDict:
01262     sysRegDict[nodeName] = {}
01263   if idTuple not in sysRegDict[nodeName]:
01264     sysRegDict[nodeName][idTuple] = {}
01265   sysRegDict[nodeName][idTuple][regName] = value
01266 
01267 def getSysReg(declarations, node, regName):
01268   """\brief Check if the system register \a regName
01269   is specified in a configuration.
01270 
01271   \param declarations Declarations dictionary.
01272   \param node         Node where we check for the system register.
01273   \param regName      System register name.
01274 
01275   \return None if it is not specified in the configuration(s)
01276           Register value from the configurations(s) if it is specified.
01277   """
01278   sysRegDict = declarations['sysregs']
01279   nodeName = node.getName()
01280   if nodeName in sysRegDict:
01281     idTuple = node.getIdTuple()
01282     if idTuple in sysRegDict[nodeName]:
01283       if regName in sysRegDict[nodeName][idTuple]:
01284         return sysRegDict[nodeName][idTuple][regName]
01285     else:
01286       # search for broadcast nodes
01287       for t in sysRegDict[nodeName].keys():
01288         if tuplesMatch(idTuple, t):
01289           if regName in sysRegDict[nodeName][t]:
01290             return sysRegDict[nodeName][t][regName]
01291           else:
01292             return None
01293   return None
01294 
01295 def tuplesMatch(t1, t2):
01296   # check if two tuples match in terms of broadcast nodes
01297   if len(t1) != len(t2):
01298     return False
01299   for i in range(len(t1)):
01300     if t1[i] != t2[i] and t2[i] != 255:
01301       return False
01302   return True
01303 
01304 def configureSystem(glat, gtemIdSeq):
01305   # Revised based on LTE-198
01306   # More changes based on LTE-240
01307   fn = "cfgSys"
01308   cccsToEnable = range(4)
01309   tccsToEnable = range(8)
01310   maskCCbits = 0x0
01311   for cc in cccsToEnable:
01312     maskCCbits += (1 << (cc+8))
01313   for cc in tccsToEnable:
01314     maskCCbits += (1 << cc)
01315 
01316   GEMtowerBusyMap = 0
01317 
01318   # cc : (ccN0, rcN0), (ccP0, rcP0), (ccN1, rcN1), (ccP1, rcP1)
01319   layerMaskMap = { 0: ((2, 0), (0, 0), (2, 1), (0, 1)),
01320                    1: ((3, 2), (1, 2), (3, 3), (1, 3)),
01321                    2: ((2, 2), (0, 2), (2, 3), (0, 3)),
01322                    3: ((3, 0), (1, 0), (3, 1), (1, 1))
01323                  }
01324 
01325   declarations = glat.getDeclarations()
01326 
01327   for gtemId in gtemIdSeq:
01328     if gtemId == 255: continue
01329     gtem = glat.TEM[gtemId]
01330     try:
01331       dataMasksValue = gtem.DATA_MASKS
01332       oldDataMasksValue = dataMasksValue
01333     except gException.LATInterfaceException:
01334       if sys.exc_info()[1].errstr()[0] in ('LCB_RTOERR', 'LCBD_RTOERR') \
01335           and glat.getDeclarations()['options']['ignorehardwaretimeouts']:
01336         continue
01337       else:
01338         raise gException.LATInterfaceException(sys.exc_info()[1].status)
01339 
01340     if dataMasksValue & maskCCbits != 0:
01341       dataMasksValue &= ~maskCCbits
01342 
01343     for cc in cccsToEnable:
01344       cccConfiguration = gtem.CCC[cc].CONFIGURATION
01345       oldConfiguration = cccConfiguration
01346       cccConfiguration |= (1L << 31)
01347       if getSysReg(declarations, gtem.CCC[cc], 'configuration') is None:
01348         # set 'listen MSB' to zero
01349         cccConfiguration &= ~(0x0FL << 27)
01350         # set FIFO full (sum/diag)
01351         cccConfiguration &= ~(0x3FL << 16)
01352         cccConfiguration |=  (0x08L << 16)
01353         # set FIFO full (err)
01354         cccConfiguration &= ~(0x3FL <<  8)
01355         cccConfiguration |=  (0x08L <<  8)
01356         # set FIFO full (data)
01357         cccConfiguration &= ~(0x7FL <<  0)
01358         cccConfiguration |=  (0x20L <<  0)
01359       if cccConfiguration != oldConfiguration:
01360         log.debug("%s: [OVR] TEM[%d].CCC[%d].CONFIGURATION=0x%08x (0x%08x)" % (fn, gtemId, cc, cccConfiguration, oldConfiguration))
01361         gtem.CCC[cc].CONFIGURATION = cccConfiguration
01362 
01363       layerMask = gtem.CCC[cc].LAYER_MASK_0
01364       oldLayerMask = layerMask
01365       (ccN0, rcN0), (ccP0, rcP0), (ccN1, rcN1), (ccP1, rcP1) = layerMaskMap[cc]
01366       if not gtem.CCC[ccN0].existsCRC(rcN0):
01367         if layerMask & 0x3FFF0000L != 0x3FFF0000L:
01368           layerMask |= 0x3FFF0000L
01369       if not gtem.CCC[ccP0].existsCRC(rcP0):
01370         if layerMask & 0x3FFF != 0x3FFF:
01371           layerMask |= 0x3FFF
01372       if layerMask != oldLayerMask:
01373         log.debug("%s: [OVR] TEM[%d].CCC[%d].LAYER_MASK_0=0x%08x (0x%08x)" % (fn, gtemId, cc, layerMask, oldLayerMask))
01374         gtem.CCC[cc].LAYER_MASK_0 = layerMask
01375 
01376       layerMask = gtem.CCC[cc].LAYER_MASK_1
01377       oldLayerMask = layerMask
01378       if not gtem.CCC[ccN1].existsCRC(rcN1):
01379         if layerMask & 0x3FFF0000L != 0x3FFF0000L:
01380           layerMask |= 0x3FFF0000L
01381       if not gtem.CCC[ccP1].existsCRC(rcP1):
01382         if layerMask & 0x3FFF != 0x3FFF:
01383           layerMask |= 0x3FFF
01384       if layerMask != oldLayerMask:
01385         log.debug("%s: [OVR] TEM[%d].CCC[%d].LAYER_MASK_1=0x%08x (0x%08x)" % (fn, gtemId, cc, layerMask, oldLayerMask))
01386         gtem.CCC[cc].LAYER_MASK_1 = layerMask
01387 
01388       if getSysReg(declarations, gtem.CCC[cc], 'fifo_status') is None:
01389         log.debug("%s: [CLR] TEM[%d].CCC[%d].FIFO_STATUS" % (fn, gtemId, cc))
01390         gtem.CCC[cc].FIFO_STATUS = 0
01391 
01392       if getSysReg(declarations, gtem.CCC[cc], 'latched_status') is None:
01393         log.debug("%s: [CLR] TEM[%d].CCC[%d].LATCHED_STATUS" % (fn, gtemId, cc))
01394         gtem.CCC[cc].LATCHED_STATUS = 0
01395 
01396       if getSysReg(declarations, gtem.CCC[cc], 'event_timeouts') is None:
01397         cccEventTimeouts = gtem.CCC[cc].EVENT_TIMEOUTS
01398         oldEventTimeouts = cccEventTimeouts
01399         cccEventTimeouts &= ~(0x3FFL << 16)
01400         cccEventTimeouts |=  (0x010L << 16) # Default per Eric Siskind (LTE-295)
01401         cccEventTimeouts &= ~0x3FF
01402         if cccEventTimeouts != oldEventTimeouts:
01403           log.debug("%s: [OVR] TEM[%d].CCC[%d].EVENT_TIMEOUTS=0x%08x (0x%08x)" % (fn, gtemId, cc, cccEventTimeouts, oldEventTimeouts))
01404           gtem.CCC[cc].EVENT_TIMEOUTS = cccEventTimeouts
01405 
01406     for cc in tccsToEnable:
01407       ccDisable = False
01408       tccInputMask = gtem.TCC[cc].INPUT_MASK
01409       oldInputMask = tccInputMask
01410       for rc in range(9):
01411         if not gtem.TCC[cc].existsTRC(rc):
01412           if tccInputMask & (1L << rc) == 0:
01413             tccInputMask |= (1L << rc)
01414       # Check if we need to disable this cable controller completely
01415       if tccInputMask & 0x1FF == 0x1FF: # None of the GTRC are present in the schema so mask it
01416         tccInputMask |= (1L << 16)
01417         ccDisable = True
01418 
01419       if tccInputMask != oldInputMask:
01420         log.debug("%s: [OVR] TEM[%d].TCC[%d].INPUT_MASK=0x%08x (0x%08x)" % (fn, gtemId, cc, tccInputMask, oldInputMask))
01421         gtem.TCC[cc].INPUT_MASK = tccInputMask
01422 
01423       tccConfiguration = gtem.TCC[cc].CONFIGURATION
01424       oldConfiguration = tccConfiguration
01425       if ccDisable:
01426         tccConfiguration &= ~(1L << 31)
01427         dataMasksValue |= (1L << cc)
01428       else:
01429         tccConfiguration |= (1L << 31)
01430       if getSysReg(declarations, gtem.TCC[cc], 'configuration') is None:
01431         # set cable length
01432         tccConfiguration &= ~(0x0FL << 27)
01433         tccConfiguration |=  ((9L-len(gtem.TCC[cc].TRC)) << 27)
01434         # set FIFO full (sum/diag)
01435         tccConfiguration &= ~(0x3FL << 16)
01436         tccConfiguration |=  (0x05L << 16)
01437         # set FIFO full (err)
01438         tccConfiguration &= ~(0x7FL <<  8)
01439         tccConfiguration |=  (0x48L <<  8)
01440         # set FIFO full (data)
01441         tccConfiguration &= ~(0x7FL <<  0)
01442         tccConfiguration |=  (0x20L <<  0)
01443 
01444       if tccConfiguration != oldConfiguration:
01445         log.debug("%s: [OVR] TEM[%d].TCC[%d].CONFIGURATION=0x%08x (0x%08x)" % (fn, gtemId, cc, tccConfiguration, oldConfiguration))
01446         gtem.TCC[cc].CONFIGURATION = tccConfiguration
01447 
01448       if getSysReg(declarations, gtem.TCC[cc], 'fifo_status') is None:
01449         log.debug("%s: [CLR] TEM[%d].TCC[%d].FIFO_STATUS" % (fn, gtemId, cc))
01450         gtem.TCC[cc].FIFO_STATUS = 0
01451 
01452       if getSysReg(declarations, gtem.TCC[cc], 'latched_status') is None:
01453         log.debug("%s: [CLR] TEM[%d].TCC[%d].LATCHED_STATUS" % (fn, gtemId, cc))
01454         gtem.TCC[cc].LATCHED_STATUS = 0
01455 
01456       if getSysReg(declarations, gtem.TCC[cc], 'event_timeouts') is None:
01457         tccEventTimeouts = gtem.TCC[cc].EVENT_TIMEOUTS
01458         oldEventTimeouts = tccEventTimeouts
01459         tccEventTimeouts = 0x3FFF
01460         if tccEventTimeouts != oldEventTimeouts:
01461           log.debug("%s: [OVR] TEM[%d].TCC[%d].EVENT_TIMEOUTS=0x%08x (0x%08x)" % (fn, gtemId, cc, tccEventTimeouts, oldEventTimeouts))
01462           gtem.TCC[cc].EVENT_TIMEOUTS = tccEventTimeouts
01463 
01464     if dataMasksValue != oldDataMasksValue:
01465       log.debug("%s: [OVR] TEM[%d].DATA_MASKS=0x%08x (0x%08x)" % (fn, gtemId, dataMasksValue, oldDataMasksValue))
01466       gtem.DATA_MASKS = dataMasksValue
01467 
01468     # Set EBM and GEM redundant bits if necessary
01469     temConfiguration = gtem.CONFIGURATION
01470     oldConfiguration = temConfiguration
01471     if glat.LCB.getFlag('UseRedundant', integer=1) == 1:
01472       temConfiguration |= (3L << 24)
01473     else:
01474       temConfiguration &= ~(3L << 24)
01475     if getSysReg(declarations, gtem, 'configuration') is None:
01476       temConfiguration &= ~(0x7FFFFF)
01477     if temConfiguration != oldConfiguration:
01478       log.debug("%s: [OVR] TEM[%d].CONFIGURATION=0x%08x (0x%08x)" % (fn, gtemId, temConfiguration, oldConfiguration))
01479       gtem.CONFIGURATION = temConfiguration
01480 
01481     if getSysReg(declarations, gtem, 'status') is None:
01482       log.debug("%s: [CLR] TEM[%d].STATUS" % (fn, gtemId))
01483       gtem.STATUS = 0
01484 
01485     if getSysReg(declarations, gtem, 'command_response') is None:
01486       log.debug("%s: [CLR] TEM[%d].COMMAND_RESPONSE" % (fn, gtemId))
01487       gtem.COMMAND_RESPONSE = 0
01488 
01489     if gtem.TIC is not None and getSysReg(declarations, gtem.TIC, 'status') is None:
01490       log.debug("%s: [CLR] TEM[%d].TIC.STATUS" % (fn, gtemId))
01491       gtem.TIC.status = 0
01492 
01493     GEMtowerBusyMap |= ( 1L << gtemId )
01494 
01495   if glat.existsGEM():   # override tower busy map with tem map.
01496     glat.GEM.GEMIE.tower_busy = GEMtowerBusyMap
01497 
01498   if glat.existsAEM() and getSysReg(declarations, glat.AEM, 'timeout') is None:
01499     aemTimeout = glat.AEM.TIMEOUT
01500     oldTimeout = aemTimeout
01501     aemTimeout = 0xEFFF
01502     if aemTimeout != oldTimeout:
01503       log.debug("%s: [OVR] AEM.TIMEOUT=0x%08x (0x%08x)" % (fn, aemTimeout, oldTimeout))
01504       glat.AEM.TIMEOUT = aemTimeout
01505 
01506   if glat.existsEBM() and glat.EBM.existsEBMC() and getSysReg(declarations, glat.EBM.EBMC, 'timeout') is None:
01507     ebmcTimeout = glat.EBM.EBMC.TIMEOUT
01508     oldTimeout = ebmcTimeout
01509     ebmcTimeout = 0xFFFF
01510     if ebmcTimeout != oldTimeout:
01511       log.debug("%s: [OVR] EBMC.TIMEOUT=0x%08x (0x%08x)" % (fn, ebmcTimeout, oldTimeout))
01512       glat.EBM.EBMC.TIMEOUT = ebmcTimeout
01513 
01514 
01515 def processGSIU(isSchema, glat, node, declarations):
01516   fn = "processGSIU"
01517   if hasAttribute(node, 'ID'):
01518     gsiuIdSeq = uncompressSequence(getAttribute(node, 'ID'))
01519   else:
01520     log.error("%s: Configuration error processing GSIU...Missing ID" % fn)
01521     return
01522 
01523   for gsiuId in gsiuIdSeq:
01524     if isSchema:
01525       gsiu = glat._GLAT__addSIU(gsiuId)
01526     elif glat.existsSIU(gsiuId):
01527       gsiu = glat.downSIU(gsiuId)
01528     else:
01529       #log.debug("%s: Configuration error processing GSIU...Not populated" % fn)
01530       return
01531 
01532 def processGEPU(isSchema, glat, node, declarations):
01533   fn = "processGEPU"
01534   if hasAttribute(node, 'ID'):
01535     gepuIdSeq = uncompressSequence(getAttribute(node, 'ID'))
01536   else:
01537     log.error("%s: Configuration error processing GEPU...Missing ID" % fn)
01538     return
01539 
01540   for gepuId in gepuIdSeq:
01541     if isSchema:
01542       gepu = glat._GLAT__addEPU(gepuId)
01543     elif glat.existsEPU(gepuId):
01544       gepu = glat.downEPU(gepuId)
01545     else:
01546       #log.debug("%s: Configuration error processing GEPU...Not populated" % fn)
01547       return
01548 
01549 def configureGCCC(node):
01550   layerMask0 = None
01551   layerMask1 = None
01552   configuration = None
01553   for n in getChildNodes(node):
01554     tagName = str(n.tagName.lower())
01555     if tagName == 'layer_mask_0':
01556       if layerMask0 is None:
01557         layerMask0 = extractRegisterValue(n)
01558     elif tagName == 'layer_mask_1':
01559       if layerMask1 is None:
01560         layerMask1 = extractRegisterValue(n)
01561     elif tagName == 'configuration':
01562       if configuration is None:
01563         configuration = extractRegisterValue(n)
01564 
01565   return (configuration, layerMask0, layerMask1)
01566 
01567 def checkForDuplicateNode(node):
01568   #printNode("***", node)
01569 
01570   for child in getChildNodes(node):
01571     #printNode("child:", child)
01572     checkForDuplicateNode(child)
01573 
01574     if child.nodeType != Node.TEXT_NODE and str(node.tagName) == str(child.tagName):
01575       sibling = child.nextSibling
01576       for n in getChildNodes(child):
01577         if sibling is None:
01578           node.appendChild(n)
01579         else:
01580           node.insertBefore(n, sibling)
01581 
01582       #if getAttribute(node, "ID") == '' and getAttribute(child, "ID") != '':
01583       #  setAttribute(node, "ID", getAttribute(child, "ID"))
01584 
01585       # The following generalizes the above two lines
01586       for i in range(len(child.attributes)):
01587         name = str(child.attributes.values()[i].name)
01588         if not hasAttribute(node, name):
01589           value = str(child.attributes.values()[i].value)
01590           setAttribute(node, name, value)
01591 
01592       node.removeChild(child)
01593 
01594   return node
01595 
01596 def checkForConfigurationNode(node):
01597   # routine to allow including configuration node underneath
01598   # a gtem or other node. If a configuration child is found,
01599   # it finds a glat and appends glat's children
01600   for n in getChildNodes(node):
01601     if str(n.tagName.lower()) == 'configuration' and hasAttribute(n, 'name'):
01602       for cn in getChildNodes(n):
01603         if str(cn.tagName.lower()) == 'glat':
01604           for cnlat in getChildNodes(cn):
01605             node.appendChild(cnlat)
01606       node.removeChild(n)
01607   return node
01608 
01609 def processGCCC(isSchema, gtem, node, declarations):
01610   fn = "processGCCC"
01611   explicitBroadcastNodes = declarations['options']['explicitbroadcastnodes']
01612   node = checkForDuplicateNode(node)
01613   if hasAttribute(node, 'ID'):
01614     gcccIdSeq = uncompressSequence(getAttribute(node, 'ID'))
01615     if isSchema and not explicitBroadcastNodes:
01616       gcccIdSeq += [255]
01617   else:
01618     if not explicitBroadcastNodes: gcccIdSeq = [255]
01619   for gcccId in gcccIdSeq:
01620     if isSchema:
01621       if gcccId == 255 and gtem.existsCCC(255):
01622         gccc = gtem.allCCC()
01623       elif gtem.id() == 255 and gtem.existsCCC(gcccId):
01624         continue
01625       else:
01626         gccc = gtem._GTEM__addCCC(gcccId)
01627     elif gtem.existsCCC(gcccId):
01628       gccc = gtem.downCCC(gcccId)
01629     else:
01630       #log.debug("%s: Configuration error processing GCCC # %d ...Not populated" % (fn, gcccId))
01631       continue
01632     for n in getChildNodes(node):
01633       tagName = str(n.tagName.lower())
01634       if tagName == 'gcrc':
01635         processGCRC(isSchema, gccc, n, declarations)
01636       elif tagName == 'opaque':
01637         addOpaque(gccc, n)
01638       elif isSchema:
01639         log.error("%s: Unexpected tag: %s" % (fn, n.tagName))
01640       elif tagName == 'serialnos':
01641         addSerialNos(gccc, n)
01642       elif tagName == 'exclude':
01643         addExcludes(gccc, n)
01644       elif tagName in gccc.regs:
01645         regVal = setRegister(gccc.regs[tagName], n, declarations)
01646         if tagName in  ('configuration', 'fifo_status', 'latched_status', 'event_timeouts'):
01647           setSysReg(declarations, gccc, tagName, regVal)
01648       else:
01649         log.error("%s: Configuration error processing GCCC # %d ...Invalid register %s" % (fn, gcccId, n.tagName))
01650 
01651 def processGTCC(isSchema, gtem, node, declarations):
01652   fn = "processGTCC"
01653   explicitBroadcastNodes = declarations['options']['explicitbroadcastnodes']
01654   node = checkForDuplicateNode(node)
01655   if hasAttribute(node, 'ID'):
01656     gtccIdSeq = uncompressSequence(getAttribute(node, 'ID'))
01657     if isSchema and not explicitBroadcastNodes:
01658       gtccIdSeq += [255]
01659   else:
01660     if not explicitBroadcastNodes: gtccIdSeq = [255]
01661   for gtccId in gtccIdSeq:
01662     if isSchema:
01663       if gtccId == 255 and gtem.existsTCC(255):
01664         gtcc = gtem.allTCC()
01665       elif gtem.id() == 255 and gtem.existsTCC(gtccId):
01666         continue
01667       else:
01668         gtcc = gtem._GTEM__addTCC(gtccId)
01669     elif gtem.existsTCC(gtccId):
01670       gtcc = gtem.downTCC(gtccId)
01671     else:
01672       #log.debug("%s: Configuration error processing GTCC # %d ...Not populated" % (fn, gtccId))
01673       continue
01674     for n in getChildNodes(node):
01675       tagName = str(n.tagName.lower())
01676       if tagName == 'gtrc':
01677         processGTRC(isSchema, gtcc, n, declarations)
01678       elif tagName == 'opaque':
01679         addOpaque(gtcc, n)
01680       elif isSchema:
01681         log.error("%s: Unexpected tag: %s" % (fn, n.tagName))
01682       elif tagName == 'serialnos':
01683         addSerialNos(gtcc, n)
01684       elif tagName == 'exclude':
01685         addExcludes(gtcc, n)
01686       elif tagName in gtcc.regs:
01687         regVal = setRegister(gtcc.regs[tagName], n, declarations)
01688         if tagName in  ('configuration', 'fifo_status', 'latched_status', 'event_timeouts'):
01689           setSysReg(declarations, gtcc, tagName, regVal)
01690       else:
01691         log.error("%s: Configuration error processing GTCC # %d ...Invalid register %s" % (fn, gtccId, n.tagName))
01692 
01693 def processGTIC(isSchema, gtem, node, declarations):
01694   fn = "processGTIC"
01695   if isSchema:
01696     gtic = gtem._GTEM__addTIC()
01697   elif gtem.downTIC() != None:
01698     gtic = gtem.downTIC()
01699   else:
01700     #log.debug("%s: Configuration error processing GTIC...Not populated" % fn)
01701     return
01702   node = checkForDuplicateNode(node)
01703   for n in getChildNodes(node):
01704     tagName = str(n.tagName.lower())
01705     if tagName == 'opaque':
01706       addOpaque(gtic, n)
01707     elif isSchema:
01708       log.error("%s: Unexpected tag: %s" % (fn, n.tagName))
01709     elif tagName == 'serialnos':
01710       addSerialNos(gtic, n)
01711     elif tagName == 'exclude':
01712       addExcludes(gtic, n)
01713     elif tagName in gtic.regs:
01714       regVal = setRegister(gtic.regs[tagName], n, declarations)
01715       if tagName in  ('status', 'busy_lrs_mask'):
01716         setSysReg(declarations, gtic, tagName, regVal)
01717     else:
01718       log.error("%s: Configuration error processing GTIC...Invalid register %s" % (fn, n.tagName))
01719 
01720 
01721 def processGCRC(isSchema, gccc, node, declarations):
01722   fn = "processGCRC"
01723   explicitBroadcastNodes = declarations['options']['explicitbroadcastnodes']
01724   node = checkForDuplicateNode(node)
01725   if hasAttribute(node, 'ID'):
01726     gcrcIdSeq = uncompressSequence(getAttribute(node, 'ID'))
01727     if isSchema and not explicitBroadcastNodes:
01728       gcrcIdSeq += [255]
01729   else:
01730     if not explicitBroadcastNodes: gcrcIdSeq = [255]
01731   for gcrcId in gcrcIdSeq:
01732     if isSchema:
01733       if gcrcId == 255 and gccc.existsCRC(255):
01734         gcrc = gccc.allCRC()
01735       elif gccc.id() == 255 and gccc.existsCRC(gcrcId):
01736         continue
01737       else:
01738         gcrc = gccc._GCCC__addCRC(gcrcId)
01739     elif gccc.existsCRC(gcrcId):
01740       gcrc = gccc.downCRC(gcrcId)
01741     else:
01742       #log.debug("%s: Configuration error processing GCRC # %d ...Not populated" % (fn, gcrcId))
01743       continue
01744     for n in getChildNodes(node):
01745       tagName = str(n.tagName.lower())
01746       if tagName == 'gcfe':
01747         processGCFE(isSchema, gcrc, n, declarations)
01748       elif tagName == 'opaque':
01749         addOpaque(gcrc, n)
01750       elif isSchema:
01751         log.error("%s: Unexpected tag: %s" % (fn, n.tagName))
01752       elif tagName == 'serialnos':
01753         addSerialNos(gcrc, n)
01754       elif tagName == 'exclude':
01755         addExcludes(gcrc, n)
01756       elif tagName in gcrc.regs:
01757         setRegister(gcrc.regs[tagName], n, declarations)
01758       else:
01759         log.error("%s: Configuration error processing GCRC # %d ...Invalid register %s" % (fn, gcrcId, n.tagName))
01760 
01761 def processGTRC(isSchema, gtcc, node, declarations):
01762   fn = "processGTRC"
01763   explicitBroadcastNodes = declarations['options']['explicitbroadcastnodes']
01764   node = checkForDuplicateNode(node)
01765   if hasAttribute(node, 'ID'):
01766     gtrcIdSeq = uncompressSequence(getAttribute(node, 'ID'))
01767     if isSchema and not explicitBroadcastNodes:
01768       gtrcIdSeq += [255]
01769   else:
01770     if not explicitBroadcastNodes: gtrcIdSeq = [255]
01771   for gtrcId in gtrcIdSeq:
01772     if isSchema:
01773       if gtrcId == 255 and gtcc.existsTRC(255):
01774         gtrc = gtcc.allTRC()
01775       elif gtcc.id() == 255 and gtcc.existsTRC(gtrcId):
01776         continue
01777       else:
01778         gtrc = gtcc._GTCC__addTRC(gtrcId)
01779     elif gtcc.existsTRC(gtrcId):
01780       gtrc = gtcc.downTRC(gtrcId)
01781     else:
01782       #log.debug("%s: Configuration error processing GTRC # %d ...Not populated" % (fn, gtrcId))
01783       continue
01784     for n in getChildNodes(node):
01785       tagName = str(n.tagName.lower())
01786       if tagName == 'gtfe':
01787         processGTFE(isSchema, gtrc, n, declarations)
01788       elif tagName == 'opaque':
01789         addOpaque(gtrc, n)
01790       elif isSchema:
01791         log.error("%s: Unexpected tag: %s" % (fn, n.tagName))
01792       elif tagName == 'serialnos':
01793         addSerialNos(gtrc, n)
01794       elif tagName == 'exclude':
01795         addExcludes(gtrc, n)
01796       elif tagName in gtrc.regs:
01797         setRegister(gtrc.regs[tagName], n, declarations)
01798       else:
01799         log.error("%s: Configuration error processing GTRC # %d ...Invalid register %s" % (fn, gtrcId, n.tagName))
01800 
01801 
01802 def processGCFE(isSchema, gcrc, node, declarations):
01803   fn = "processGCFE"
01804   explicitBroadcastNodes = declarations['options']['explicitbroadcastnodes']
01805   node = checkForDuplicateNode(node)
01806   if hasAttribute(node, 'ID'):
01807     gcfeIdSeq = uncompressSequence(getAttribute(node, 'ID'))
01808     if isSchema and not explicitBroadcastNodes:
01809       gcfeIdSeq += [255]
01810   else:
01811     if not explicitBroadcastNodes: gcfeIdSeq = [255]
01812   for gcfeId in gcfeIdSeq:
01813     if isSchema:
01814       if gcfeId == 255 and gcrc.existsCFE(255):
01815         gcfe = gcrc.allCFE()
01816       elif gcrc.id() == 255 and gcrc.existsCFE(gcfeId):
01817         continue
01818       else:
01819         gcfe = gcrc._GCRC__addCFE(gcfeId)
01820     elif gcrc.existsCFE(gcfeId):
01821       gcfe = gcrc.downCFE(gcfeId)
01822     else:
01823       #log.debug("%s: Configuration error processing GCFE # %d ...Not populated" % (fn, gcfeId))
01824       continue
01825     for n in getChildNodes(node):
01826       tagName = str(n.tagName.lower())
01827       if tagName == 'opaque':
01828         addOpaque(gcfe, n)
01829       elif isSchema:
01830         log.error("%s: Unexpected tag: %s" % (fn, n.tagName))
01831       elif tagName == 'serialnos':
01832         addSerialNos(gcfe, n)
01833       elif tagName == 'exclude':
01834         addExcludes(gcfe, n)
01835       elif tagName in gcfe.regs:
01836         setRegister(gcfe.regs[tagName], n, declarations)
01837       else:
01838         log.error("%s: Configuration error processing GCFE # %d ...Invalid register %s" % (fn, gcfeId, n.tagName))
01839 
01840 
01841 def processGTFE(isSchema, gtrc, node, declarations):
01842   fn = "processGTFE"
01843   explicitBroadcastNodes = declarations['options']['explicitbroadcastnodes']
01844   node = checkForDuplicateNode(node)
01845   if hasAttribute(node, 'ID'):
01846     gtfeIdSeq = uncompressSequence(getAttribute(node, 'ID'))
01847     if isSchema and not explicitBroadcastNodes:
01848       gtfeIdSeq += [255]
01849   else:
01850     if not explicitBroadcastNodes: gtfeIdSeq = [255]
01851   for gtfeId in gtfeIdSeq:
01852     if isSchema:
01853       if gtfeId == 255 and gtrc.existsTFE(255):
01854         gtfe = gtrc.allTFE()
01855       elif gtrc.id() == 255 and gtrc.existsTFE(gtfeId):
01856         continue
01857       else:
01858         gtfe = gtrc._GTRC__addTFE(gtfeId)
01859     elif gtrc.existsTFE(gtfeId):
01860       gtfe = gtrc.downTFE(gtfeId)
01861     else:
01862       #log.debug("%s: Configuration error processing GTFE # %d ...Not populated" % (fn, gtfeId))
01863       continue
01864     for n in getChildNodes(node):
01865       tagName = str(n.tagName.lower())
01866       if tagName == 'opaque':
01867         addOpaque(gtfe, n)
01868       elif isSchema:
01869         log.error("%s: Unexpected tag: %s" % (fn, n.tagName))
01870       elif tagName == 'serialnos':
01871         addSerialNos(gtfe, n)
01872       elif tagName == 'exclude':
01873         addExcludes(gtfe, n)
01874       elif tagName in gtfe.regs:
01875         setRegister(gtfe.regs[tagName], n, declarations)
01876       else:
01877         log.error("%s: Configuration error processing GTFE # %d ...Invalid register %s" % (fn, gtfeId, n.tagName))
01878 
01879 
01880 def processGAEM(isSchema, glat, node, declarations):
01881   fn = "processGAEM"
01882   if isSchema:
01883     gaem = glat._GLAT__addAEM()
01884   elif glat.existsAEM():
01885     gaem = glat.downAEM()
01886   else:
01887     #log.debug("%s: Configuration error processing GAEM ...Not populated" %(fn))
01888     return
01889 
01890   node = checkForDuplicateNode(node)
01891   for n in getChildNodes(node):
01892     tagName = str(n.tagName.lower())
01893     if tagName == 'garc':
01894       processGARC(isSchema, gaem, n, declarations)
01895     elif tagName == 'gaeq':
01896       processGAEQ(isSchema, gaem, n, declarations)
01897     elif tagName == 'opaque':
01898       addOpaque(gaem, n)
01899     elif isSchema:
01900       log.error("%s: Unexpected tag: %s" % (fn, n.tagName))
01901     elif tagName == 'serialnos':
01902       addSerialNos(gaem, n)
01903     elif tagName == 'exclude':
01904       addExcludes(gaem, n)
01905     elif tagName in gaem.regs:
01906       regVal = setRegister(gaem.regs[tagName], n, declarations)
01907       if tagName in  ('timeout'):
01908         setSysReg(declarations, gaem, tagName, regVal)
01909     else:
01910       log.error("%s: Configuration error processing GAEM ...Invalid register %s" %(fn, n.tagName))
01911 
01912 
01913 def processGAEQ(isSchema, gaem, node, declarations):
01914   fn = "processGAEQ"
01915   if isSchema:
01916     gaeq = gaem._GAEM__addAEQ()
01917   elif gaem.downAEQ() != None:
01918     gaeq = gaem.downAEQ()
01919   else:
01920     #log.debug("%s: Configuration error processing GAEQ...Not populated" % fn)
01921     return
01922   node = checkForDuplicateNode(node)
01923   for n in getChildNodes(node):
01924     tagName = str(n.tagName.lower())
01925     if tagName == 'opaque':
01926       addOpaque(gaeq, n)
01927     elif isSchema:
01928       log.error("%s: Unexpected tag: %s" % (fn, n.tagName))
01929     elif tagName == 'serialnos':
01930       addSerialNos(gaeq, n)
01931     elif tagName == 'exclude':
01932       addExcludes(gaeq, n)
01933     elif tagName in gaeq.regs:
01934       setRegister(gaeq.regs[tagName], n, declarations)
01935     else:
01936       log.error("%s: Configuration error processing GAEQ...Invalid register %s" % (fn, n.tagName))
01937 
01938 
01939 def processGARC(isSchema, gaem, node, declarations):
01940   fn = "processGARC"
01941   explicitBroadcastNodes = declarations['options']['explicitbroadcastnodes']
01942   node = checkForDuplicateNode(node)
01943   if hasAttribute(node, 'ID'):
01944     garcIdSeq = uncompressSequence(getAttribute(node, 'ID'))
01945     if isSchema and not explicitBroadcastNodes:
01946       garcIdSeq += [255]
01947   else:
01948     if not explicitBroadcastNodes: garcIdSeq = [255]
01949   for garcId in garcIdSeq:
01950     if isSchema:
01951       if garcId == 255 and gaem.existsARC(255):
01952         garc = gaem.allARC()
01953       else:
01954         garc = gaem._GAEM__addARC(garcId)
01955     elif gaem.existsARC(garcId):
01956       garc = gaem.downARC(garcId)
01957     else:
01958       #log.debug("%s: Configuration error processing GARC # %d ...Not populated" % (fn, garcId))
01959       continue
01960     for n in getChildNodes(node):
01961       tagName = str(n.tagName.lower())
01962       if tagName == 'gafe':
01963         processGAFE(isSchema, garc, n, declarations)
01964       elif tagName == 'opaque':
01965         addOpaque(garc, n)
01966       elif isSchema:
01967         log.error("%s: Unexpected tag: %s" % (fn, n.tagName))
01968       elif tagName == 'serialnos':
01969         addSerialNos(garc, n)
01970       elif tagName == 'exclude':
01971         addExcludes(garc, n)
01972       elif tagName in garc.regs:
01973         setRegister(garc.regs[tagName], n, declarations)
01974       else:
01975         log.error("%s: Configuration error processing GARC # %d ...Invalid register %s" % (fn, garcId, n.tagName))
01976 
01977 
01978 def processGAFE(isSchema, garc, node, declarations):
01979   fn = "processGAFE"
01980   explicitBroadcastNodes = declarations['options']['explicitbroadcastnodes']
01981   node = checkForDuplicateNode(node)
01982   if hasAttribute(node, 'ID'):
01983     gafeIdSeq = uncompressSequence(getAttribute(node, 'ID'))
01984     if isSchema and not explicitBroadcastNodes:
01985       gafeIdSeq += [255]
01986   else:
01987     if not explicitBroadcastNodes: gafeIdSeq = [255]
01988   for gafeId in gafeIdSeq:
01989     if isSchema:
01990       if gafeId == 255 and garc.existsAFE(255):
01991         gafe = garc.allAFE()
01992       elif garc.id() == 255 and garc.existsAFE(gafeId):
01993         continue
01994       else:
01995         gafe = garc._GARC__addAFE(gafeId)
01996     elif garc.existsAFE(gafeId):
01997       gafe = garc.downAFE(gafeId)
01998     else:
01999       #log.debug("%s: Configuration error processing GAFE # %d ...Not populated" % (fn, gafeId))
02000       continue
02001     if hasAttribute(node, 'TUBE'):
02002       gafe.setTube(getAttribute(node, 'TUBE'))
02003       aem = garc.up()
02004       garcId = garc.id()
02005       aem.tileMap[garcId, gafeId] = getAttribute(node, 'TUBE')
02006     for n in getChildNodes(node):
02007       tagName = str(n.tagName.lower())
02008       if tagName == 'opaque':
02009         addOpaque(gafe, n)
02010       elif isSchema:
02011         log.error("%s: Unexpected tag: %s" % (fn, n.tagName))
02012       elif tagName == 'serialnos':
02013         addSerialNos(gafe, n)
02014       elif tagName == 'exclude':
02015         addExcludes(gafe, n)
02016       elif tagName in gafe.regs:
02017         setRegister(gafe.regs[tagName], n, declarations)
02018       else:
02019         log.error("%s: Configuration error processing GAFE # %d ...Invalid register %s" % (fn, gafeId, n.tagName))
02020 
02021 
02022 def printTree(node):
02023   if node.nodeType == Node.TEXT_NODE and node.data[0] == '\n':
02024     pass
02025   else:
02026     print node
02027     if node.nodeType == Node.ELEMENT_NODE:
02028       tagName = node.tagName.lower()
02029       #print "Element:",tagName
02030       if tagName in ('schema', 'configuration', 'glat', 'gtem', 'gccc', 'gcrc', 'gcfe', 'gtic', \
02031                      'gtcc', 'gtrc', 'gtfe', 'gaem', 'gaeq', 'garc', 'gafe', \
02032                      'gpdu', 'gpduc', 'gpeq', 'gtwr','gebm','gebmc','gebmst', \
02033                      'ggem','ggemc','ggemmg', 'ggemst','ggemsc','ggemvg','ggemie','ggemw','gcru'):
02034         for n in node.childNodes:
02035           printTree(n)
02036 
02037 def getChildNodes(node):
02038   childNodes = []
02039   for n in node.childNodes:
02040     if (n.nodeType == Node.TEXT_NODE and \
02041          (n.data[0] == '\n' or n.data[0].strip() == '')) \
02042         or n.nodeType == Node.COMMENT_NODE:
02043       pass
02044     else:
02045       childNodes.append(n)
02046   return childNodes
02047 
02048 def getAttribute(node, attr):
02049   return node.getAttributeNS(LAT_NAMESPACE, attr)
02050 
02051 def hasAttribute(node, attr):
02052   return node.hasAttributeNS(LAT_NAMESPACE, attr)
02053 
02054 def setAttribute(node, attr, value):
02055   return node.setAttributeNS(LAT_NAMESPACE, attr, value)
02056 
02057 def createElement(node, elem):
02058   return node.createElementNS(LAT_NAMESPACE, elem)
02059 
02060 def isNumber(s):
02061   try:
02062     float(s)
02063     return 1
02064   except ValueError:
02065     return 0
02066 
02067 def getParameterValue(parValue):
02068   if parValue.lower() in ('true', 'yes'):
02069     return 1
02070   elif parValue.lower() in ('false', 'no'):
02071     return 0
02072   elif parValue.lower() == 'none':
02073     return None
02074   elif parValue.startswith('0x'):
02075     return long(parValue,16)
02076   elif isNumber(parValue):
02077     return float(parValue)
02078   else:
02079     return parValue
02080 
02081 def processConstraints(node, declarations):
02082   fn = "processConstraints"
02083   node = checkForDuplicateNode(node)
02084   groups = declarations['groups']
02085   constraints = declarations['constraints']
02086   if hasAttribute(node, 'serialKey'):
02087     serialKey = str(getAttribute(node, 'serialKey'))
02088   else:
02089     serialKey = 'default'
02090   if hasAttribute(node, 'serialNo'):
02091     serialNo = str(getAttribute(node, 'serialNo'))
02092   else:
02093     serialNo = 'default'
02094 
02095   if (serialKey, serialNo) not in constraints:
02096     constraints[(serialKey, serialNo)] = {}
02097 
02098   for n in getChildNodes(node):
02099     tagName = n.tagName.lower()
02100     if tagName == 'constraint':
02101       if hasAttribute(n, 'name'):
02102         consName = str(getAttribute(n, 'name'))
02103         consParList = {}
02104         #if constraints.has_key(consName):
02105         #  consClassModStr = constraints[consName][0]
02106         #  consClassNameStr = constraints[consName][1]
02107         #  consParList = constraints[consName][2]
02108         for consPropNode in getChildNodes(n):
02109           tagName = consPropNode.tagName.lower()
02110           if tagName == 'class':
02111             classStr = str(consPropNode.firstChild.data).strip()
02112             lastDot = classStr.rfind('.')
02113             if lastDot == -1:
02114               consClassNameStr = classStr
02115               consClassModStr = ''
02116             else:
02117               consClassNameStr = classStr[lastDot+1:]
02118               consClassModStr = classStr[:lastDot]
02119           elif tagName == 'parameters':
02120             consParList['name'] = consName
02121             for consParNode in getChildNodes(consPropNode):
02122               parName = str(consParNode.tagName.lower())
02123               parValue = str(consParNode.firstChild.data).strip()
02124               if parName == 'subsystem':
02125                 if groups.has_key(parValue):
02126                   parValue = groups[parValue]
02127                 else:
02128                   log.error("%s: Constraint subsystem group %s not defined" % (fn, parValue))
02129                   parValue = None
02130               elif parName == 'category':
02131                 if groups.has_key(parValue):
02132                   parValue = groups[parValue]
02133                 else:
02134                   log.error("%s: Constraint category group %s not defined" % (fn, parValue))
02135                   parValue = None
02136               else:
02137                 parValue = getParameterValue(parValue)
02138               consParList[str(consParNode.tagName)] = parValue
02139         constraints[(serialKey, serialNo)][consName] = instantiateClass(consClassModStr,
02140                                                          consClassNameStr,
02141                                                          consParList)
02142       else:
02143         log.error("%s: Missing constraint name" % fn)
02144         return None
02145     else:
02146       log.error("%s: Invalid tag: %s ...skipping" % (fn, n.tagName))
02147 
02148 def processRules(node, declarations):
02149   fn = "processRules"
02150   node = checkForDuplicateNode(node)
02151   groups = declarations['groups']
02152   rules  = declarations['rules']
02153   if hasAttribute(node, 'serialKey'):
02154     serialKey = str(getAttribute(node, 'serialKey'))
02155   else:
02156     serialKey = 'default'
02157   if hasAttribute(node, 'serialNo'):
02158     serialNo = str(getAttribute(node, 'serialNo'))
02159   else:
02160     serialNo = 'default'
02161 
02162   if (serialKey, serialNo) not in rules:
02163     rules[(serialKey, serialNo)] = {}
02164 
02165   for n in getChildNodes(node):
02166     tagName = n.tagName.lower()
02167     if tagName == 'rule':
02168       if hasAttribute(n, 'name'):
02169         ruleName = str(getAttribute(n, 'name'))
02170         ruleParList = {}
02171         ruleActionList = []
02172         #if rules.has_key(ruleName):
02173         #  log.error("%s: Rule %s already defined." % (fn, ruleName))
02174         #  continue
02175         for rulePropNode in getChildNodes(n):
02176           tagName = rulePropNode.tagName.lower()
02177           if tagName == 'class':
02178             classStr = str(rulePropNode.firstChild.data).strip()
02179             lastDot = classStr.rfind('.')
02180             if lastDot == -1:
02181               ruleClassNameStr = classStr
02182               ruleClassModStr = ''
02183             else:
02184               ruleClassNameStr = classStr[lastDot+1:]
02185               ruleClassModStr = classStr[:lastDot]
02186           elif tagName == 'parameters':
02187             ruleParList['name'] = ruleName
02188             for ruleParNode in getChildNodes(rulePropNode):
02189               parName = str(ruleParNode.tagName.lower())
02190               parValue = str(ruleParNode.firstChild.data).strip()
02191               if parName == 'subsystem':
02192                 if groups.has_key(parValue):
02193                   parValue = groups[parValue]
02194                 else:
02195                   log.error("%s: Rule subsystem group %s not defined" % (fn, parValue))
02196                   parValue = None
02197               elif parName == 'category':
02198                 if groups.has_key(parValue):
02199                   parValue = groups[parValue]
02200                 else:
02201                   log.error("%s: Rule category group %s not defined" % (fn, parValue))
02202                   parValue = None
02203               elif parName == 'actions':
02204                 for ruleActionNode in getChildNodes(ruleParNode):
02205                   actName = str(ruleActionNode.tagName)
02206                   if actName not in ruleActionList:
02207                     ruleActionList.append(actName)
02208                   else:
02209                     log.error("%s: Rule action %s already defined." % (fn, actName))
02210                 parValue = ruleActionList
02211               else:
02212                 parValue = getParameterValue(parValue)
02213               ruleParList[str(ruleParNode.tagName)] = parValue
02214         rules[(serialKey, serialNo)][ruleName] = instantiateClass(ruleClassModStr,
02215                                                    ruleClassNameStr,
02216                                                    ruleParList)
02217       else:
02218         log.error("%s: Missing rule name" % fn)
02219         return None
02220     else:
02221       log.error("%s: Invalid tag: %s ...skipping" % (fn, n.tagName))
02222 
02223 def processEGUs(node, declarations):
02224   fn = "processEGUs"
02225   node = checkForDuplicateNode(node)
02226   egus = declarations['egus']
02227   if hasAttribute(node, 'serialKey'):
02228     serialKey = str(getAttribute(node, 'serialKey'))
02229   else:
02230     serialKey = 'default'
02231   if hasAttribute(node, 'serialNo'):
02232     serialNo = str(getAttribute(node, 'serialNo'))
02233   else:
02234     serialNo = 'default'
02235 
02236   if (serialKey, serialNo) not in egus:
02237     egus[(serialKey, serialNo)] = {}
02238 
02239   for n in getChildNodes(node):
02240     tagName = n.tagName.lower()
02241     if tagName == 'egu':
02242       if hasAttribute(n, 'name'):
02243         eguName = str(getAttribute(n, 'name'))
02244         #if egus.has_key(eguName):
02245         #  eguClassModStr = egus[eguName][0]
02246         #  eguClassNameStr = egus[eguName][1]
02247         #  eguParList = egus[eguName][2]
02248         for eguPropNode in getChildNodes(n):
02249           tagName = eguPropNode.tagName.lower()
02250           if tagName == 'class':
02251             classStr = str(eguPropNode.firstChild.data).strip()
02252             lastDot = classStr.rfind('.')
02253             if lastDot == -1:
02254               eguClassNameStr = classStr
02255               eguClassModStr = ''
02256             else:
02257               eguClassNameStr = classStr[lastDot+1:]
02258               eguClassModStr = classStr[:lastDot]
02259           elif tagName == 'parameters':
02260             eguParList = {}
02261             for eguParNode in getChildNodes(eguPropNode):
02262               parValue = str(eguParNode.firstChild.data).strip()
02263               parValue = getParameterValue(parValue)
02264               eguParList[str(eguParNode.tagName)] = parValue
02265         egus[(serialKey, serialNo)][eguName] = instantiateClass(eguClassModStr,
02266                                                  eguClassNameStr,
02267                                                  eguParList)
02268       else:
02269         log.error("%s: Missing EGU name" % fn)
02270         return None
02271     else:
02272       log.error("%s: Invalid tag: %s ...skipping" % (fn, n.tagName))
02273 
02274 
02275 def processDeclarations(isSchema, node, declarations):
02276   fn = "processDeclarations"
02277   groups = declarations['groups']
02278   imports = declarations['imports']
02279   ml = BasicModuleLoader()
02280   for n in getChildNodes(node):
02281     tagName = n.tagName.lower()
02282     if tagName == 'import':
02283       if hasAttribute(n, 'name'):
02284         modName = str(getAttribute(n, 'name'))
02285         modPathSpec = str(n.firstChild.data.strip())
02286         imports[modName] = modPathSpec
02287         if modPathSpec.endswith('.py'):
02288           (modPath, modFile) = os.path.split(os.path.expandvars(modPathSpec))
02289           modstuff = ml.find_module(os.path.splitext(modFile)[0], (modPath,))
02290         elif modPathSpec.find('.') != -1:
02291           exec('import ' + modPathSpec + ' as ' + modName)
02292           modstuff = ''
02293           sys.modules[modName] = sys.modules[modPathSpec]
02294         else:
02295           modstuff = ml.find_module(modPathSpec, tuple(sys.path) + (os.getcwd(),))
02296         if modstuff is None:
02297           raise ImportError, "%s: Module not found: %s" % (fn, modPathSpec)
02298         if isinstance(modstuff, tuple):
02299           ml.load_module(modName, modstuff)
02300       else:
02301         log.error("%s: Missing module name" % fn)
02302         return None
02303     elif tagName == 'group':
02304       if hasAttribute(n, 'name'):
02305         groupName = str(getAttribute(n, 'name'))
02306       else:
02307         log.error("%s: Missing group name" % fn)
02308         return None
02309       if hasAttribute(n, 'enabled'):
02310         isGroupEnabled = str(getAttribute(n, 'enabled'))
02311         if isGroupEnabled.lower() in ('true', 'yes'):
02312           isGroupEnabled = 1
02313         elif isGroupEnabled.lower() in ('false', 'no'):
02314           isGroupEnabled = 0
02315         else:
02316           log.error("%s: Invalid enable flag value %d" % (fn, isGroupEnabled))
02317       else:
02318         log.error("%s: Missing enable flag for group %s" % (fn, groupName))
02319       groups[groupName] = Ggroup(groupName, isGroupEnabled)
02320     elif tagName == 'options':
02321       for on in getChildNodes(n):
02322         tagName = str(on.tagName).lower()
02323         if tagName == 'explicitbroadcastnodes':
02324           if not isSchema:
02325             log.error("%s: '%s' declaration option can not be used in a configuration block" % (fn, on.tagName))
02326           else:
02327             processBooleanDeclarationOption(on, declarations)
02328         elif tagName in ('skiptemoverrides', 'skipsystemoverrides'):
02329           processBooleanDeclarationOption(on, declarations, 'skipsystemoverrides')
02330         elif tagName == 'ignorehardwaretimeouts':
02331           if not isSchema:
02332             log.error("%s: '%s' declaration option can not be used in a configuration block" % (fn, on.tagName))
02333           else:
02334             processBooleanDeclarationOption(on, declarations)
02335         else:
02336           log.error("%s: Invalid declaration options tag: %s ...skipping" % (fn, on.tagName))
02337     else:
02338       log.error("%s: Invalid declaration tag: %s ...skipping" % (fn, n.tagName))
02339   return
02340 
02341 def processBooleanDeclarationOption(on, declarations, tagName=None):
02342   if tagName is None:
02343     tagName = str(on.tagName).lower()
02344   val = str(on.firstChild.data).strip().lower()
02345   if val == '1' or val == 'true':
02346     declarations['options'][tagName] = 1
02347   else:
02348     declarations['options'][tagName] = 0
02349 
02350 def processBadChannels(node, badChannels, mapLayerToCable=None, mapDetectorToLayer=None, temId=None):
02351   BAD_CHANNEL_MASKS = ['nOnbdCalib', 'nOnbdData', 'nOnbdTrig']
02352   fn = "processBadChannels"
02353   for badStripNode in getChildNodes(node):
02354     if badStripNode.tagName == 'tower':
02355       badStripTower = badStripNode
02356       if temId is None:
02357         row = int(getAttribute(badStripTower, 'row'))
02358         col = int(getAttribute(badStripTower, 'col'))
02359         temId = row*4 + col
02360       for uniplane in getChildNodes(badStripTower):
02361         if uniplane.tagName == 'uniplane':
02362           tray = int(getAttribute(uniplane, 'tray'))
02363           which = str(getAttribute(uniplane, 'which'))
02364           howBad = int(getAttribute(uniplane, 'howBad'))
02365           if mapLayerToCable is not None and mapDetectorToLayer is not None:
02366             ccpair_rc = mapLayerToCable[mapDetectorToLayer[(tray, which)]]
02367           else:
02368             ccpair_rc = MAP_LAYER_TO_CABLE[MAP_DETECTOR_TO_LAYER[(tray, which)]]
02369           maskAttrVal = {}
02370           atLeastOneIsTrue = False
02371           for maskAttr in BAD_CHANNEL_MASKS:
02372             maskAttrVal[maskAttr] = str(getAttribute(uniplane, maskAttr)).lower()
02373             if maskAttrVal[maskAttr] == 'true':
02374               atLeastOneIsTrue = True
02375           # For backward compatibility: If masks are not specified or
02376           # if all masks are set to 'false' then assume all are 'true'
02377           if not atLeastOneIsTrue:
02378             for maskAttr in BAD_CHANNEL_MASKS:
02379               maskAttrVal[maskAttr] = 'true'
02380           for maskAttr in BAD_CHANNEL_MASKS:
02381             if maskAttrVal[maskAttr] == 'true':
02382               mask = maskAttr.lower()[5:]
02383               if (temId, ccpair_rc) in badChannels[mask]:
02384                 stripBitField = badChannels[mask][(temId, ccpair_rc)]
02385               else:
02386                 stripBitField = gBits.bf(0)
02387               for stripListNode in getChildNodes(uniplane):
02388                 if stripListNode.tagName == 'stripList':
02389                   stripSeq = str(getAttribute(stripListNode, 'strips')).strip()
02390                   stripList = uncompressSequence(stripSeq, sepChar=' ')
02391                   for strip in stripList:
02392                     stripBitField[strip] = 1
02393               badChannels[mask][(temId, ccpair_rc)] = stripBitField
02394 
02395 def readBadChannels(fileName, mapLayerToCable=None, mapDetectorToLayer=None, temId=None):
02396   fn = "readBadChannels"
02397   #doc = Sax2.FromXmlFile(fileName)
02398   try:
02399     #doc = minidom.parse(fileName)
02400     file_uri = Uri.OsPathToUri(fileName, attemptAbsolute=1)
02401     doc = NonvalidatingReader.parseUri(file_uri)
02402   except Exception, e:
02403     log.exception("%s: Error parsing bad channels file: %s" % (fn, fileName))
02404     raise e
02405   root = doc.documentElement
02406   tagName = root.tagName.lower()
02407   if tagName != "badstrips":
02408     log.error("%s: Invalid bad strips document tag: %s" % (fn, tagName))
02409     return None
02410   badChannels = {'calib':{}, 'data':{}, 'trig':{}}
02411   processBadChannels(root, badChannels, mapLayerToCable, mapDetectorToLayer, temId)
02412   return badChannels
02413 
02414 def instantiateClass(classModStr, classNameStr, parList):
02415   fn = "instantiateClass"
02416   if sys.modules.has_key(classModStr):
02417     m = sys.modules[classModStr]
02418     try:
02419       return apply(getattr(m, classNameStr), (), parList)
02420     except:
02421       log.error("%s: Error: %s %s %s" % (fn, classModStr, classNameStr, sys.exc_value))
02422       log.error("%s: Class parameter list: %s" % (fn, parList))
02423       return None
02424   else:
02425     log.error("%s: Module %s for class %s not loaded" % (fn, classModStr, classNameStr))
02426     return None
02427 
02428 def takeSnapshot(glat, stream=sys.stdout, fileName=None,
02429                  captureGTIC=1, captureGAEQ=1,
02430                  trigger=None,
02431                  configName='', configVersion=''):
02432   fn = "takeSnapshot"
02433   closeFlag=0
02434   if stream is None:
02435     try:
02436       stream = open(fileName,'w')
02437       closeFlag = 1
02438     except:
02439       log.error("%s: can't open snapshot file: %s" % (fn, fileName))
02440       return
02441   log.debug("%s: Generating snapshot: %s, configName= %s, configVersion= %s..." %
02442            (fn, fileName, configName, configVersion))
02443   result = writeSchema(glat, stream, snapshotMode=1,
02444               captureGTIC=captureGTIC, captureGAEQ=captureGAEQ,
02445               trigger=trigger,
02446               configName=configName, configVersion=configVersion)
02447   if closeFlag:
02448     stream.close()
02449   if result:
02450     log.debug("%s: Snapshot generation completed successfully" % fn)
02451   else:
02452     log.warning("%s: Snapshot generation completed with errors" % fn)
02453   return result
02454 
02455 def writeConfig(glat, stream=sys.stdout, seq=None):
02456   fn = "writeConfig"
02457   configs = glat.getConfigurations()
02458   configSeqList = configs.keys()
02459   configSeqList.sort()
02460   for configSeq in configSeqList:
02461     if seq is None:
02462       PrettyPrint(configs[configSeq][0], stream)
02463       #toPrettyXML(configs[configSeq][0], stream, indent="  ", encoding="UTF-8")
02464     elif seq == configSeq:
02465       PrettyPrint(configs[seq][0], stream)
02466       #toPrettyXML(configs[seq][0], stream, indent="  ", encoding="UTF-8")
02467       return
02468   if seq is None:
02469     return
02470   else:
02471     log.error("%s: Configuration %d not found." % (fn, seq))
02472 
02473 def writeRegisters(node, doc, xnode):
02474   fn = "writeRegisters"
02475   result = True
02476   for (reg, regObj) in node.regs.items():
02477     # Already writing the bit fields for the mask so skip it
02478     if node.__class__.__name__ == 'GGLT' and reg == 'mask':
02479       continue
02480     retryCount = 3
02481     if not regObj.isDeprecated() and \
02482        not regObj.isCommand() and \
02483        not regObj.isWriteOnly() and \
02484        not regObj.isNoDirectAccess() and \
02485        'noread' not in node.getExcludeFlags():
02486       while True:
02487         try:
02488           regVal = regObj.get(bypass=1)
02489           #print regObj.getName(), node.__class__.__name__, regVal.__class__.__name__
02490           #log.error("Added register to the snapshot: %s %s %s %s" \
02491           #            % (node.getName(), node.getIdTuple(), regObj.getName(), regVal))
02492           break
02493         except gException.LATInterfaceException:
02494           if sys.exc_info()[1].errstr()[0] in ('LCB_RTOERR', 'LCBD_RTOERR'):
02495             if not node.root().getDeclarations()['options']['ignorehardwaretimeouts']:
02496               log.error("%s: Error adding register to the snapshot: %s %s %s %s" \
02497                         % (fn, sys.exc_info()[1].errstr(), node.getName(),
02498                           node.getIdTuple(), regObj.getName()))
02499             return False
02500           elif sys.exc_info()[1].errstr()[0] == 'OCS_BDADC' and retryCount > 1:
02501             retryCount -= 1
02502             continue
02503           else:
02504             log.error("%s: Error adding register to the snapshot: %s %s %s %s" \
02505                       % (fn, sys.exc_info()[1].errstr(), node.getName(),
02506                         node.getIdTuple(), regObj.getName()))
02507             regVal = 0
02508             result = False
02509             break
02510 
02511       xreg = createElement(doc, reg)
02512       xreg.appendChild(doc.createTextNode('0x%x' % regVal))
02513       xnode.appendChild(xreg)
02514   return result
02515 
02516 
02517 def writeSchema(glat, stream=sys.stdout, snapshotMode=0,
02518                 captureGTIC=1, captureGAEQ=1,
02519                 trigger=None,
02520                 configName='', configVersion=''):
02521   """Writes a LAT object model to an XML schema
02522 
02523   Inputs::
02524 
02525     GLAT root of the object model
02526     Output stream (defaults to sys.stdout if omitted)
02527 
02528   Output: None
02529 
02530   Usage::
02531 
02532     f = open('mySchema.xml', 'w')
02533     writeSchema(lat, f)
02534     f.close()
02535       or
02536     writeSchema(lat) to output to sys.stdout.
02537   """
02538   fn = "writeSchema"
02539   result = True # Return False if there are any errors during snapshot
02540   if configName == '': configName = glat._GLAT__configName
02541   if configVersion == '': configVersion = glat._GLAT__configVersion
02542   #doc = minidom.getDOMImplementation().createDocument(None,None,None)
02543   doc = implementation.createDocument(None,None,None)
02544   if not snapshotMode:
02545     for c in glat._GLAT__schemaComments:
02546       doc.appendChild(doc.createComment(c))
02547     root = createElement(doc, "LATdoc")
02548     setAttribute(root, 'name', glat._GLAT__schemaName)
02549     doc.appendChild(root)
02550   else:
02551     root = createElement(doc, 'configuration')
02552     setAttribute(root, 'name', configName)
02553     setAttribute(root, 'version', configVersion)
02554     doc.appendChild(root)
02555 
02556   xdecl = createElement(doc, "declarations")
02557   root.appendChild(xdecl)
02558   options = glat._GLAT__declarations['options']
02559   if len(options) > 0:
02560     xoptblk = createElement(doc, 'options')
02561     for (optName, optVal) in options.items():
02562       if optName.startswith("__"):
02563         continue
02564       xopt = createElement(doc, optName)
02565       xopt.appendChild(doc.createTextNode(str(optVal)))
02566       xoptblk.appendChild(xopt)
02567     xdecl.appendChild(xoptblk)
02568   imports = glat._GLAT__declarations['imports']
02569   if len(imports) > 0:
02570     for (impName, impPath) in imports.items():
02571       ximp = createElement(doc, 'import')
02572       setAttribute(ximp, 'name', impName)
02573       ximp.appendChild(doc.createTextNode(impPath))
02574       xdecl.appendChild(ximp)
02575   groups = glat._GLAT__declarations['groups']
02576   if len(groups) > 0:
02577     for (groupName, group) in groups.items():
02578       xgrp = createElement(doc, 'group')
02579       if group.enabled():
02580         setAttribute(xgrp, 'enabled', 'true')
02581       else:
02582         setAttribute(xgrp, 'enabled', 'false')
02583       setAttribute(xgrp, 'name', groupName)
02584       xdecl.appendChild(xgrp)
02585 
02586   consDict = glat._GLAT__declarations['constraints']
02587   for ((serialKey, serialNo), constraints) in consDict.items():
02588     if len(constraints) > 0:
02589       xconsblk = createElement(doc, 'constraints')
02590       if serialKey != 'default':
02591         setAttribute(xconsblk, 'serialKey', serialKey)
02592       if serialNo != 'default':
02593         setAttribute(xconsblk, 'serialNo', serialNo)
02594       for (consName, cons) in constraints.items():
02595         if cons is None: continue
02596         xcons = createElement(doc, 'constraint')
02597         setAttribute(xcons, 'name', consName)
02598         xclass = createElement(doc, 'class')
02599         xclass.appendChild(doc.createTextNode(cons.__class__.__module__ +
02600                                               '.' + cons.__class__.__name__)
02601                                             )
02602         xcons.appendChild(xclass)
02603         xparblk = createElement(doc, 'parameters')
02604         (args, varargs, varkw) = inspect.getargs(cons.__init__.func_code)
02605         for arg in args:
02606           if arg == 'self': continue
02607           val = None
02608           for (dictVar, dictVal) in cons.__dict__.items():
02609             if dictVar.endswith('__' + arg):
02610               val = dictVal
02611               break
02612           if val is None:
02613           #if cons.__dict__.has_key('_Gconstraint__' + arg):
02614           #  val = cons.__dict__['_Gconstraint__' + arg]
02615           #elif cons.__dict__.has_key('_' + cons.__class__.__name__ + '__' + arg):
02616           #  val = cons.__dict__['_' + cons.__class__.__name__ + '__' + arg]
02617           #else:
02618             log.error("%s: Can not locate instance variable for "
02619                       "constraint parameter: %s ...skipping" % (fn, arg))
02620             continue
02621           if hasattr(val, 'name'):
02622             val = val.name()
02623           xpar = createElement(doc, arg)
02624           xval = doc.createTextNode(str(val))
02625           xpar.appendChild(xval)
02626           xparblk.appendChild(xpar)
02627         xcons.appendChild(xparblk)
02628         xconsblk.appendChild(xcons)
02629       root.appendChild(xconsblk)
02630 
02631   rulesDict = glat._GLAT__declarations['rules']
02632   for ((serialKey, serialNo), rules) in rulesDict.items():
02633     if len(rules) > 0:
02634       xruleblk = createElement(doc, 'rules')
02635       if serialKey != 'default':
02636         setAttribute(xruleblk, 'serialKey', serialKey)
02637       if serialNo != 'default':
02638         setAttribute(xruleblk, 'serialNo', serialNo)
02639       for (ruleName, rule) in rules.items():
02640         if rule is None: continue
02641         xrule = createElement(doc, 'rule')
02642         setAttribute(xrule, 'name', ruleName)
02643         xclass = createElement(doc, 'class')
02644         xclass.appendChild(doc.createTextNode(rule.__class__.__module__ +
02645                                               '.' + rule.__class__.__name__)
02646                                             )
02647         xrule.appendChild(xclass)
02648         xparblk = createElement(doc, 'parameters')
02649         (args, varargs, varkw) = inspect.getargs(rule.__init__.func_code)
02650         for arg in args:
02651           if arg == 'self': continue
02652           val = None
02653           for (dictVar, dictVal) in rule.__dict__.items():
02654             if dictVar.endswith('__' + arg):
02655               val = dictVal
02656               break
02657           if val is None:
02658           #if rule.__dict__.has_key('_Grule__' + arg):
02659           #  val = rule.__dict__['_Grule__' + arg]
02660           #elif rule.__dict__.has_key('_' + rule.__class__.__name__ + '__' + arg):
02661           #  val = rule.__dict__['_' + rule.__class__.__name__ + '__' + arg]
02662           #else:
02663             log.error("%s: Can not locate instance variable for "
02664                       "rule parameter: %s ...skipping" % (fn, arg))
02665             continue
02666           if hasattr(val, 'name'):
02667             val = val.name()
02668           xpar = createElement(doc, arg)
02669           xval = doc.createTextNode(str(val))
02670           xpar.appendChild(xval)
02671           xparblk.appendChild(xpar)
02672         xrule.appendChild(xparblk)
02673         xruleblk.appendChild(xrule)
02674       root.appendChild(xruleblk)
02675 
02676   egusDict = glat._GLAT__declarations['egus']
02677   for ((serialKey, serialNo), egus) in egusDict.items():
02678     if len(egus) > 0:
02679       xegublk = createElement(doc, 'egus')
02680       if serialKey != 'default':
02681         setAttribute(xegublk, 'serialKey', serialKey)
02682       if serialNo != 'default':
02683         setAttribute(xegublk, 'serialNo', serialNo)
02684       for (eguName, egu) in egus.items():
02685         if egu is None: continue
02686         xegu = createElement(doc, 'egu')
02687         setAttribute(xegu, 'name', eguName)
02688         xclass = createElement(doc, 'class')
02689         xclass.appendChild(doc.createTextNode(egu.__class__.__module__ +
02690                                               '.' + egu.__class__.__name__)
02691                                             )
02692         xegu.appendChild(xclass)
02693         xparblk = createElement(doc, 'parameters')
02694         (args, varargs, varkw) = inspect.getargs(egu.__init__.func_code)
02695         for arg in args:
02696           if arg == 'self': continue
02697           val = None
02698           for (dictVar, dictVal) in egu.__dict__.items():
02699             if dictVar.endswith('__' + arg):
02700               val = dictVal
02701               break
02702           if val is None:
02703           #if egu.__dict__.has_key('_GEGU__' + arg):
02704           #  val = egu.__dict__['_GEGU__' + arg]
02705           #elif egu.__dict__.has_key('_' + egu.__class__.__name__ + '__' + arg):
02706           #  val = egu.__dict__['_' + egu.__class__.__name__ + '__' + arg]
02707           #else:
02708             log.error("%s: Can not locate instance variable for "
02709                       "EGU parameter: %s ...skipping" % (fn, arg))
02710             continue
02711           if hasattr(val, 'name'):
02712             val = val.name()
02713           xpar = createElement(doc, arg)
02714           xval = doc.createTextNode(str(val))
02715           xpar.appendChild(xval)
02716           xparblk.appendChild(xpar)
02717         xegu.appendChild(xparblk)
02718         xegublk.appendChild(xegu)
02719       root.appendChild(xegublk)
02720 
02721   options = glat._GLAT__declarations['options']
02722   if not snapshotMode:
02723     explicitBroadcastNodes = options['explicitbroadcastnodes']
02724   else:
02725     explicitBroadcastNodes = 0
02726 
02727   lat = getPath(glat, explicitBroadcastNodes)
02728   if not snapshotMode:
02729     xsch = createElement(doc, 'schema')
02730     root.appendChild(xsch)
02731     xlat = createElement(doc, 'GLAT')
02732     xsch.appendChild(xlat)
02733   else:
02734     gem = lat[2]                                  # Check for a GEM
02735     if gem is None and trigger is not None:       # No gem, use GLT
02736       glt = trigger.GLT()                         # get GLT from trigger obj
02737       gltMask = ~( trigger.conditions().value() ) # GLT uses ~ logic
02738       gMask = gBits.bf(gltMask)
02739       xglt = createElement(doc, 'GGLT')
02740       for (bitField, fromBit, toBit) in glt._GGLT__mask_BF:
02741         xreg = createElement(doc, bitField)
02742         xreg.appendChild(doc.createTextNode('0x%x' % gMask[fromBit:toBit]))
02743         xglt.appendChild(xreg)
02744       # Add the rest of the GLT
02745       for reg in ('mask','parity','tag','event_number',
02746                   'destination','marker','tack',
02747                   'zero_suppress','four_range_readout','cal_strobe'):
02748         xreg = createElement(doc, reg)
02749         xreg.appendChild(doc.createTextNode('0x%x' % glt.regs[reg].get()))
02750         xglt.appendChild(xreg)
02751       root.appendChild(xglt)
02752     xlat = createElement(doc, 'GLAT')
02753     root.appendChild(xlat)
02754 
02755   pdus = lat[0]
02756   for pdu in pdus:
02757     pduIds = pdu[0]
02758     if snapshotMode:
02759       for pduId in pduIds:
02760         xpdu = createElement(doc, 'GPDU')
02761         setAttribute(xpdu, 'ID', "%d"%pduId)
02762         gpdu = glat.PDU[pduId]
02763         if not writeRegisters(gpdu, doc, xpdu):
02764           result = False
02765           continue
02766         xlat.appendChild(xpdu)
02767         peq = pdu[1]
02768         if peq:
02769           xpeq = createElement(doc, 'GPEQ')
02770           xpdu.appendChild(xpeq)
02771           result &= writeRegisters(gpdu.PEQ, doc, xpeq)
02772     else:
02773       xpdu = createElement(doc, 'GPDU')
02774       setAttribute(xpdu, 'ID', compressSequence(pduIds))
02775       xlat.appendChild(xpdu)
02776       peq = pdu[1]
02777       if peq:
02778         xpeq = createElement(doc, 'GPEQ')
02779         xpdu.appendChild(xpeq)
02780   ebm = lat[1]
02781   if ebm is not None:
02782     xebm = createElement(doc, 'GEBM')
02783     xlat.appendChild(xebm)
02784     if snapshotMode:
02785       gebm = glat.EBM
02786       result &= writeRegisters(gebm, doc, xebm)
02787     (ebmc, ebmst) = ebm
02788     if ebmc:
02789       xebmc = createElement(doc, 'GEBMC')
02790       xebm.appendChild(xebmc)
02791       if snapshotMode:
02792         result &= writeRegisters(gebm.EBMC, doc, xebmc)
02793     if ebmst:
02794       xebmst = createElement(doc, 'GEBMST')
02795       xebm.appendChild(xebmst)
02796       if snapshotMode:
02797         result &= writeRegisters(gebm.EBMST, doc, xebmst)
02798   gem = lat[2]
02799   if gem is not None:
02800     xgem = createElement(doc, 'GGEM')
02801     xlat.appendChild(xgem)
02802     if snapshotMode:
02803       ggem = glat.GEM
02804       result &= writeRegisters(ggem, doc, xgem)
02805     (gemc, gemmg, gemst, gemsc, gemvg, gemie, gemw) = gem
02806     if gemc:
02807       xgemc = createElement(doc, 'GGEMC')
02808       xgem.appendChild(xgemc)
02809       if snapshotMode:
02810         result &= writeRegisters(ggem.GEMC, doc, xgemc)
02811     if gemmg:
02812       xgemmg = createElement(doc, 'GGEMMG')
02813       xgem.appendChild(xgemmg)
02814       if snapshotMode:
02815         result &= writeRegisters(ggem.GEMMG, doc, xgemmg)
02816     if gemst:
02817       xgemst = createElement(doc, 'GGEMST')
02818       xgem.appendChild(xgemst)
02819       if snapshotMode:
02820         result &= writeRegisters(ggem.GEMST, doc, xgemst)
02821     if gemsc:
02822       xgemsc = createElement(doc, 'GGEMSC')
02823       xgem.appendChild(xgemsc)
02824       if snapshotMode:
02825         result &= writeRegisters(ggem.GEMSC, doc, xgemsc)
02826     if gemvg:
02827       xgemvg = createElement(doc, 'GGEMVG')
02828       xgem.appendChild(xgemvg)
02829       if snapshotMode:
02830         result &= writeRegisters(ggem.GEMVG, doc, xgemvg)
02831     if gemie:
02832       xgemie = createElement(doc, 'GGEMIE')
02833       xgem.appendChild(xgemie)
02834       if snapshotMode:
02835         result &= writeRegisters(ggem.GEMIE, doc, xgemie)
02836     if gemw:
02837        xgemw = createElement(doc, 'GGEMW')
02838        xgem.appendChild(xgemw)
02839        if snapshotMode:
02840          result &= writeRegisters(ggem.GEMW, doc, xgemw)
02841          if trigger is not None:
02842            for n in getChildNodes(xgemw):
02843              if str(n.tagName.lower()) == 'window_open_mask':
02844                old_wom = getChildNodes(n)[0]
02845                new_wom = doc.createTextNode('0x%x' % trigger.conditions().value())
02846                n.replaceChild(new_wom, old_wom)
02847                break
02848   cru = lat[3]
02849   if cru:
02850     xcru = createElement(doc, 'GCRU')
02851     xlat.appendChild(xcru)
02852     if snapshotMode:
02853       result &= writeRegisters(glat.CRU, doc, xcru)
02854   tems = lat[4]
02855   for tem in tems:
02856     temIds = tem[0]
02857     if snapshotMode:
02858       for temId in temIds:
02859         xtem = createElement(doc, 'GTEM')
02860         setAttribute(xtem, 'ID', "%d"%temId)
02861         gtem = glat.TEM[temId]
02862         if not writeRegisters(gtem, doc, xtem):
02863           result = False
02864           continue
02865         xlat.appendChild(xtem)
02866         ccs = tem[1]
02867         cccs = ccs[0]
02868         for ccc in cccs:
02869           cccIds = ccc[0]
02870           for cccId in cccIds:
02871             xccc = createElement(doc, 'GCCC')
02872             setAttribute(xccc, 'ID', "%d"%cccId)
02873             gccc = gtem.CCC[cccId]
02874             if not writeRegisters(gccc, doc, xccc):
02875               result = False
02876               continue
02877             xtem.appendChild(xccc)
02878             crcs = ccc[1]
02879             for crc in crcs:
02880               crcIds = crc[0]
02881               for crcId in crcIds:
02882                 xcrc = createElement(doc, 'GCRC')
02883                 setAttribute(xcrc, 'ID', "%d"%crcId)
02884                 gcrc = gccc.CRC[crcId]
02885                 if not writeRegisters(gcrc, doc, xcrc):
02886                   result = False
02887                   continue
02888                 xccc.appendChild(xcrc)
02889                 cfeIds = crc[1]
02890                 if cfeIds != ():
02891                   for cfeId in cfeIds:
02892                     xcfe = createElement(doc, 'GCFE')
02893                     setAttribute(xcfe, 'ID', "%d"%cfeId)
02894                     gcfe = gcrc.CFE[cfeId]
02895                     if not writeRegisters(gcfe, doc, xcfe):
02896                       result = False
02897                       continue
02898                     xcrc.appendChild(xcfe)
02899         tccs = ccs[1]
02900         for tcc in tccs:
02901           tccIds = tcc[0]
02902           for tccId in tccIds:
02903             xtcc = createElement(doc, 'GTCC')
02904             setAttribute(xtcc, 'ID', "%d"%tccId)
02905             gtcc = gtem.TCC[tccId]
02906             if not writeRegisters(gtcc, doc, xtcc):
02907               result = False
02908               continue
02909             xtem.appendChild(xtcc)
02910             trcs = tcc[1]
02911             for trc in trcs:
02912               trcIds = trc[0]
02913               for trcId in trcIds:
02914                 xtrc = createElement(doc, 'GTRC')
02915                 setAttribute(xtrc, 'ID', "%d"%trcId)
02916                 gtrc = gtcc.TRC[trcId]
02917                 if not writeRegisters(gtrc, doc, xtrc):
02918                   result = False
02919                   continue
02920                 xtcc.appendChild(xtrc)
02921                 tfeIds = trc[1]
02922                 if tfeIds != ():
02923                   for tfeId in tfeIds:
02924                     xtfe = createElement(doc, 'GTFE')
02925                     setAttribute(xtfe, 'ID', "%d"%tfeId)
02926                     gtfe = gtrc.TFE[tfeId]
02927                     if not writeRegisters(gtfe, doc, xtfe):
02928                       result = False
02929                       continue
02930                     xtrc.appendChild(xtfe)
02931         if captureGTIC:
02932           tic = ccs[2]
02933           if tic:
02934             xtic = createElement(doc, 'GTIC')
02935             gtic = gtem.TIC
02936             result &= writeRegisters(gtic, doc, xtic)
02937             xtem.appendChild(xtic)
02938     else:
02939       xtem = createElement(doc, 'GTEM')
02940       setAttribute(xtem, 'ID', compressSequence(temIds))
02941       xlat.appendChild(xtem)
02942       ccs = tem[1]
02943       cccs = ccs[0]
02944       for ccc in cccs:
02945         cccIds = ccc[0]
02946         xccc = createElement(doc, 'GCCC')
02947         setAttribute(xccc, 'ID', compressSequence(cccIds))
02948         xtem.appendChild(xccc)
02949         crcs = ccc[1]
02950         for crc in crcs:
02951           crcIds = crc[0]
02952           xcrc = createElement(doc, 'GCRC')
02953           setAttribute(xcrc, 'ID', compressSequence(crcIds))
02954           xccc.appendChild(xcrc)
02955           cfeIds = crc[1]
02956           if cfeIds != ():
02957             xcfe = createElement(doc, 'GCFE')
02958             setAttribute(xcfe, 'ID', compressSequence(cfeIds))
02959             xcrc.appendChild(xcfe)
02960       tccs = ccs[1]
02961       for tcc in tccs:
02962         tccIds = tcc[0]
02963         xtcc = createElement(doc, 'GTCC')
02964         setAttribute(xtcc, 'ID', compressSequence(tccIds))
02965         xtem.appendChild(xtcc)
02966         trcs = tcc[1]
02967         for trc in trcs:
02968           trcIds = trc[0]
02969           xtrc = createElement(doc, 'GTRC')
02970           setAttribute(xtrc, 'ID', compressSequence(trcIds))
02971           xtcc.appendChild(xtrc)
02972           tfeIds = trc[1]
02973           if tfeIds != ():
02974             xtfe = createElement(doc, 'GTFE')
02975             setAttribute(xtfe, 'ID', compressSequence(tfeIds))
02976             xtrc.appendChild(xtfe)
02977       tic = ccs[2]
02978       if tic:
02979         xtic = createElement(doc, 'GTIC')
02980         xtem.appendChild(xtic)
02981   aem = lat[5]
02982   if aem != None:
02983     xaem = createElement(doc, 'GAEM')
02984     if aem[0]:
02985       aemIds = (0,255)
02986       setAttribute(xaem, 'ID', compressSequence(aemIds))
02987     if snapshotMode:
02988       gaem = glat.AEM
02989       result &= writeRegisters(gaem, doc, xaem)
02990     xlat.appendChild(xaem)
02991     if snapshotMode:
02992       if captureGAEQ:
02993         aeq = aem[1]
02994         if aeq:
02995           xaeq = createElement(doc, 'GAEQ')
02996           gaeq = gaem.AEQ
02997           result &= writeRegisters(gaeq, doc, xaeq)
02998           xaem.appendChild(xaeq)
02999     else:
03000       aeq = aem[1]
03001       if aeq:
03002         xaeq = createElement(doc, 'GAEQ')
03003         xaem.appendChild(xaeq)
03004     for arc in aem[2]:
03005       arcIds = arc[0]
03006       if snapshotMode:
03007         for arcId in arcIds:
03008           xarc = createElement(doc, 'GARC')
03009           setAttribute(xarc, 'ID', "%d"%arcId)
03010           garc = gaem.ARC[arcId]
03011           result &= writeRegisters(garc, doc, xarc)
03012           xaem.appendChild(xarc)
03013           afeIds = arc[1]
03014           if afeIds != ():
03015             for afeId in afeIds:
03016               xafe = createElement(doc, 'GAFE')
03017               setAttribute(xafe, 'ID', "%d"%afeId)
03018               gafe = garc.AFE[afeId]
03019               result &= writeRegisters(gafe, doc, xafe)
03020               xarc.appendChild(xafe)
03021       else:
03022         xarc = createElement(doc, 'GARC')
03023         setAttribute(xarc, 'ID', compressSequence(arcIds))
03024         xaem.appendChild(xarc)
03025         afeIds = arc[1]
03026         if afeIds != ():
03027           xafe = createElement(doc, 'GAFE')
03028           setAttribute(xafe, 'ID', compressSequence(afeIds))
03029           xarc.appendChild(xafe)
03030 
03031   if not snapshotMode:
03032     configSeqList = glat.getConfigurations().keys()
03033     configSeqList.sort()
03034     for seq in configSeqList:
03035       xcnf = doc.importNode(glat.getConfigurations()[seq][0],1)
03036       root.appendChild(xcnf)
03037   PrettyPrint(doc, stream)
03038   #toPrettyXML(doc, stream, indent="  ", encoding="UTF-8")
03039   del doc
03040   gc.collect()
03041   return result
03042 
03043 
03044 def getPath(gnode, explicitBroadcastNodes):
03045   fn = 'getPath'
03046   if gnode.__class__.__name__ == 'GCRC':
03047     gcrcChildren = gnode.CFE.keys()
03048     gcrcChildren = tuple(gcrcChildren)
03049     return gcrcChildren
03050   elif gnode.__class__.__name__ == 'GCCC':
03051     gcrcSeqMap = {}
03052     for (gcrcId, gcrc) in gnode.CRC.items():
03053       if not explicitBroadcastNodes and gcrcId == 255: continue
03054       gcfeIdTuple = getPath(gcrc, explicitBroadcastNodes)
03055       if gcrcSeqMap.has_key(gcfeIdTuple):
03056         gcrcSeqMap[gcfeIdTuple] += (gcrcId,)
03057       else:
03058         gcrcSeqMap[gcfeIdTuple] = (gcrcId,)
03059     gcrcSeqTuple = ()
03060     for (gcfeIds, gcrcIds) in gcrcSeqMap.items():
03061       gcrcSeqTuple = ((gcrcIds, gcfeIds,),) + gcrcSeqTuple
03062     return gcrcSeqTuple
03063   if gnode.__class__.__name__ == 'GTRC':
03064     gtrcChildren = gnode.TFE.keys()
03065     gtrcChildren = tuple(gtrcChildren)
03066     return gtrcChildren
03067   elif gnode.__class__.__name__ == 'GTCC':
03068     gtrcSeqMap = {}
03069     for (gtrcId, gtrc) in gnode.TRC.items():
03070       if not explicitBroadcastNodes and gtrcId == 255: continue
03071       gtfeIdTuple = getPath(gtrc, explicitBroadcastNodes)
03072       if gtrcSeqMap.has_key(gtfeIdTuple):
03073         gtrcSeqMap[gtfeIdTuple] += (gtrcId,)
03074       else:
03075         gtrcSeqMap[gtfeIdTuple] = (gtrcId,)
03076     gtrcSeqTuple = ()
03077     for (gtfeIds, gtrcIds) in gtrcSeqMap.items():
03078       gtrcSeqTuple = ((gtrcIds, gtfeIds,),) + gtrcSeqTuple
03079     return gtrcSeqTuple
03080   elif gnode.__class__.__name__ == 'GTEM':
03081     gcccSeqMap = {}
03082     cccItems = gnode.CCC.items()
03083     if explicitBroadcastNodes and gnode.allCCC() is not None:
03084       cccItems.append((255,gnode.allCCC()))
03085     for (gcccId, gccc) in cccItems:
03086       gcrcIdTuple = getPath(gccc, explicitBroadcastNodes)
03087       if gcccSeqMap.has_key(gcrcIdTuple):
03088         gcccSeqMap[gcrcIdTuple] += (gcccId,)
03089       else:
03090         gcccSeqMap[gcrcIdTuple] = (gcccId,)
03091     gcccSeqTuple = ()
03092     for (gcrcIds, gcccIds) in gcccSeqMap.items():
03093       gcccSeqTuple = ((gcccIds, gcrcIds,),) + gcccSeqTuple
03094 
03095     gtccSeqMap = {}
03096     tccItems = gnode.TCC.items()
03097     if explicitBroadcastNodes and gnode.allTCC() is not None:
03098       tccItems.append((255,gnode.allTCC()))
03099     for (gtccId, gtcc) in tccItems:
03100       gtrcIdTuple = getPath(gtcc, explicitBroadcastNodes)
03101       if gtccSeqMap.has_key(gtrcIdTuple):
03102         gtccSeqMap[gtrcIdTuple] += (gtccId,)
03103       else:
03104         gtccSeqMap[gtrcIdTuple] = (gtccId,)
03105     gtccSeqTuple = ()
03106     for (gtrcIds, gtccIds) in gtccSeqMap.items():
03107       gtccSeqTuple = ((gtccIds, gtrcIds,),) + gtccSeqTuple
03108     if gnode.downTIC() != None:
03109       return (gcccSeqTuple , gtccSeqTuple, 1)
03110     else:
03111       return (gcccSeqTuple , gtccSeqTuple, 0)
03112   elif gnode.__class__.__name__ == 'GLAT':
03113     gtemSeqMap = {}
03114     temItems = gnode.TEM.items()
03115     if explicitBroadcastNodes and gnode.allTEM() is not None:
03116       temItems.append((255,gnode.allTEM()))
03117     for (gtemId, gtem) in temItems:
03118       gcccIdTuple = getPath(gtem, explicitBroadcastNodes)
03119       if gtemSeqMap.has_key(gcccIdTuple):
03120         gtemSeqMap[gcccIdTuple] += (gtemId,)
03121       else:
03122         gtemSeqMap[gcccIdTuple] = (gtemId,)
03123     gtemSeqTuple = ()
03124     for (gcccIds, gtemIds) in gtemSeqMap.items():
03125       gtemSeqTuple = ((gtemIds, gcccIds,),) + gtemSeqTuple
03126     gpduSeqMap = {}
03127     for (gpduId, gpdu) in gnode.PDU.items():
03128 
03129       gpduTuple = getPath(gpdu, explicitBroadcastNodes)
03130       if gpduTuple in gpduSeqMap:
03131         gpduSeqMap[gpduTuple] += (gpduId,)
03132       else:
03133         gpduSeqMap[gpduTuple] = (gpduId,)
03134     gpduSeqTuple = ()
03135     for (gpduTuple, gpduIds) in gpduSeqMap.items():
03136       gpduSeqTuple = ((gpduIds, gpduTuple,),) + gpduSeqTuple
03137 
03138     if gnode.downAEM() == None:
03139       gaemTuple = None
03140     else:
03141       gaemTuple = getPath(gnode.downAEM(), explicitBroadcastNodes)
03142       gaemTuple = (0,) + gaemTuple
03143     ebm = gnode.downEBM()
03144     if ebm is not None:
03145       gebmTuple = ()
03146       ebmc = ebm.downEBMC()
03147       if ebmc is not None:
03148         gebmTuple += (1,)
03149       else:
03150         gebmTuple += (0,)
03151       ebmst = ebm.downEBMST()
03152       if ebmst is not None:
03153         gebmTuple += (1,)
03154       else:
03155         gebmTuple += (0,)
03156     else:
03157       gebmTuple = None
03158     gem = gnode.downGEM()
03159     if gem is not None:
03160       ggemTuple = ()
03161       gemc = gem.downGEMC()
03162       if gemc is not None:
03163         ggemTuple += (1,)
03164       else:
03165         ggemTuple += (0,)
03166       gemmg = gem.downGEMMG()
03167       if gemmg is not None:
03168         ggemTuple += (1,)
03169       else:
03170         ggemTuple += (0,)
03171       gemst = gem.downGEMST()
03172       if gemst is not None:
03173         ggemTuple += (1,)
03174       else:
03175         ggemTuple += (0,)
03176       gemsc = gem.downGEMSC()
03177       if gemsc is not None:
03178         ggemTuple += (1,)
03179       else:
03180         ggemTuple += (0,)
03181       gemvg = gem.downGEMVG()
03182       if gemvg is not None:
03183         ggemTuple += (1,)
03184       else:
03185         ggemTuple += (0,)
03186       gemie = gem.downGEMIE()
03187       if gemie is not None:
03188         ggemTuple += (1,)
03189       else:
03190         ggemTuple += (0,)
03191       gemw = gem.downGEMW()
03192       if gemw is not None:
03193         ggemTuple += (1,)
03194       else:
03195         ggemTuple += (0,)
03196     else:
03197       ggemTuple = None
03198     if gnode.existsCRU():
03199       gcru = 1
03200     else:
03201       gcru = 0
03202     return (gpduSeqTuple, gebmTuple, ggemTuple, gcru, gtemSeqTuple , gaemTuple)
03203   elif gnode.__class__.__name__ == 'GPDU':
03204     gpduChildren = ()
03205     peq = gnode.downPEQ()
03206     if peq is not None:
03207       gpduChildren += (1,)
03208     else:
03209       gpduChildren += (0,)
03210     return gpduChildren
03211   elif gnode.__class__.__name__ == 'GAEM':
03212     garcSeqMap = {}
03213     arcItems = gnode.ARC.items()
03214     if explicitBroadcastNodes and gnode.allARC() is not None:
03215       arcItems.append((255,gnode.allARC()))
03216     for (garcId, garc) in arcItems:
03217       gafeIdTuple = getPath(garc, explicitBroadcastNodes)
03218       if garcSeqMap.has_key(gafeIdTuple):
03219         garcSeqMap[gafeIdTuple] += (garcId,)
03220       else:
03221         garcSeqMap[gafeIdTuple] = (garcId,)
03222     garcSeqTuple = ()
03223     for (gafeIds, garcIds) in garcSeqMap.items():
03224       garcSeqTuple = ((garcIds, gafeIds,),) + garcSeqTuple
03225     if gnode.downAEQ() != None:
03226       return (1, garcSeqTuple)
03227     else:
03228       return (0, garcSeqTuple)
03229 
03230   elif gnode.__class__.__name__ == 'GARC':
03231     garcChildren = gnode.AFE.keys()
03232     garcChildren = tuple(garcChildren)
03233     return garcChildren
03234   else:
03235     log.warn("%s: Unhandled node: %s" % (fn, gnode.__class__.__name__ ))
03236     return None
03237 
03238 def uncompressSequence(seqStr, sepChar=','):
03239   l = []
03240   s = seqStr.split(sepChar)
03241   for x in s:
03242     x = x.strip()
03243     p = x.find('-')
03244     if p == -1:
03245       if x == '*':
03246         l.append(255)
03247       elif x != '':
03248         l.append(int(x))
03249     else:
03250       fNum = int(x[0:p])
03251       tNum = int(x[p+1:])
03252       l += range(fNum, tNum+1)
03253   return l
03254 
03255 def compressSequence(idTuple, sepChar=','):
03256   fromId = -1
03257   toId = -1
03258   idStr = ''
03259   for idVal in idTuple:
03260     if fromId == -1:
03261       fromId = idVal
03262       toId = idVal
03263     elif (idVal - toId) == 1:
03264       toId = idVal
03265     else:
03266       if idStr != '':
03267         idStr += sepChar
03268       if fromId == toId:
03269         idStr += str(fromId)
03270       elif (toId - fromId) == 1:
03271         idStr += str(fromId) + sepChar + str(toId)
03272       else:
03273         idStr += str(fromId) + "-" + str(toId)
03274       fromId = idVal
03275       toId = idVal
03276   if idStr != '':
03277     idStr += sepChar
03278   if fromId == toId:
03279     if fromId == 255: fromId = '*'
03280     idStr += str(fromId)
03281   elif (toId - fromId) == 1:
03282     idStr += str(fromId) + sepChar + str(toId)
03283   else:
03284     idStr += str(fromId) + "-" + str(toId)
03285   return idStr
03286 
03287 # Currently does not work for Domlette, use Ft.Xml.Domlette.PrettyPrint instead.
03288 # copied and modified from Python/Lib/xml/dom/minidom.py
03289 # With the default routine the text nodes were being written
03290 # on a separate line. Now they are on the same line as their parent tags.
03291 def toPrettyXML(doc, writer, indent="\t", newl="\n", encoding = None):
03292   # indent = the indentation string to prepend, per level
03293   # newl = the newline string to append
03294   if encoding is not None:
03295     import codecs
03296     # Can't use codecs.getwriter to preserve 2.0 compatibility
03297     writer = codecs.lookup(encoding)[3](writer)
03298     writer.write('<?xml version="1.0" encoding="%s"?>\n' % encoding)
03299   else:
03300     writer.write('<?xml version="1.0" ?>\n')
03301   if doc.nodeType == Node.ELEMENT_NODE:
03302     writeXML(doc, writer, indent="",addindent="  ",newl="\n")
03303   else:
03304     for node in doc.childNodes:
03305       if (node.nodeType == Node.TEXT_NODE and \
03306         (node.data[0] == '\n' or node.data[0].strip() == '')):
03307         pass
03308       elif node.nodeType == Node.ELEMENT_NODE:
03309         writeXML(node, writer, indent="",addindent=indent,newl=newl)
03310       else:
03311         node.writexml(writer, indent="",addindent=indent,newl=newl)
03312 
03313 # copied and modified from Python/Lib/xml/dom/minidom.py
03314 def writeXML(n, writer, indent="", addindent="", newl=""):
03315   # indent = current indentation
03316   # addindent = indentation to add to higher levels
03317   # newl = newline string
03318   writer.write(indent+"<" + n.tagName)
03319 
03320   #attrs = n._get_attributes()
03321   a_names = [x.name for x in n.attributes.values()]
03322   a_names.sort()
03323 
03324   for a_name in a_names:
03325     writer.write(" %s=\"" % a_name)
03326     _write_data(writer, getAttribute(n, a_name))
03327     writer.write("\"")
03328   if n.childNodes:
03329     if len(n.childNodes) == 1 and n.childNodes[0].nodeType == Node.TEXT_NODE:
03330       node = n.childNodes[0]
03331       writer.write(">")
03332       node.writexml(writer,"",addindent,"")
03333       writer.write("</%s>%s" % (n.tagName,newl))
03334     else:
03335       writer.write(">%s"%(newl))
03336       for node in n.childNodes:
03337         if (node.nodeType == Node.TEXT_NODE and \
03338            (node.data[0] == '\n' or node.data[0].strip() == '')):
03339           pass
03340         elif node.nodeType == Node.ELEMENT_NODE:
03341           writeXML(node,writer,indent+addindent,addindent,newl)
03342         else:
03343           node.writexml(writer,indent+addindent,addindent,newl)
03344       writer.write("%s</%s>%s" % (indent,n.tagName,newl))
03345   else:
03346       writer.write("/>%s"%(newl))
03347 
03348 # copied from Python/Lib/xml/dom/minidom.py
03349 def _write_data(writer, data):
03350   "Writes datachars to writer."
03351   data = data.replace("&", "&amp;").replace("<", "&lt;")
03352   data = data.replace("\"", "&quot;").replace(">", "&gt;")
03353   writer.write(data)
03354 
03355 class ConfigElement(object):
03356   """\brief Wrapper class for providing a compatibility layer
03357   between the old minidom XML DOMs and the new 4Suite Domlette
03358   DOMs.
03359 
03360   """
03361   def __init__(self, domletteElement):
03362     self.__dElement = domletteElement
03363 
03364   def getAttribute(self, attr):
03365     return self.__dElement.getAttributeNS(LAT_NAMESPACE, attr)
03366 
03367   def getElementsByTagName(self, tagName):
03368     if self.__dElement.tagName == tagName:
03369       found = [ConfigElement(self.__dElement)]
03370     else:
03371       found = []
03372     return found + self.__getElementsByTagName(self.__dElement, tagName)
03373 
03374   def __getElementsByTagName(self, elem, tagName):
03375     found = []
03376     for n in getChildNodes(elem):
03377       if n.tagName == tagName:
03378         found.append(ConfigElement(n))
03379       found += self.__getElementsByTagName(n, tagName)
03380     return found
03381 
03382   def __getattr__(self, attr):
03383     if attr == 'childNodes':
03384       return map(ConfigElement, getChildNodes(self.__dElement))
03385     else:
03386       return getattr(self.__dElement, attr)
03387 
03388 
03389 # Registry dictionary to allow readSchema to read non locally defined
03390 # objects.  (Example GHSK)
03391 # Usage:  gSCprocessRegistry['GHSK']=processGHSK
03392 gSCprocessRegistry = {
03393   'GLAT'   :    processGLAT,
03394   'GXBRD'  :    processGXBRD,
03395 }
03396 
03397 

Generated on Fri Jul 21 13:26:29 2006 for LATTE R04-12-00 by doxygen 1.4.3