Changeset 13789


Ignore:
Timestamp:
05/18/12 23:16:43 (12 years ago)
Author:
neise
Message:
more comments and unimportant stuff
Location:
fact/tools/PyDimCtrl
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • fact/tools/PyDimCtrl/fpydim.py

    r13770 r13789  
    11#!/usr/bin/python -tti
     2
     3# for tab completion
    24import rlcompleter
    35import readline
    46readline.parse_and_bind('tab: complete')
    57
    6 import sys
    7 import pydim
    8 import types
    9 import time # for sleep
    10 from pprint import pprint
    11 from keyword import iskeyword
     8import sys      # for sys.exit() during bebugging mostly :-)
     9import types                    # for dynamic class construction
     10import time                     # for time.sleep
     11from pprint import pprint       # for nice printing
     12
     13from keyword import iskeyword   # in case dynamic methods are equal to keywords
     14
     15import pydim                    # for the C-API Dim Call Wrappers
     16
     17# using this line makes 'export DIM_DNS_NODE=daq' obsolete
    1218pydim.dic_set_dns_node('daq')
    1319
    14 # making server list
    15 rawlist = pydim.dic_sync_info_service('DIS_DNS/SERVER_LIST','C')
    16 # the output needs to be treated a bit .. it is a tuple with only one long string in it
    17 # the string contains | and the strange character \x00
    18 # I use both to cut the list apart
    19 rawlist = rawlist[0].split('\x00')
    20 servers_n_hosts = rawlist[0].split('|')
    21 server_ids = rawlist[1].split('|')
    22 
    23 servers = {}
    24 for i,snh in enumerate(servers_n_hosts):
    25         snh = snh.split('@')
    26         s = snh[0]
    27         h = snh[1]
    28         sid = server_ids[i]
    29         servers[s] = (sid, h)
    30 
    31 # delete unneeded vars
    32 del servers_n_hosts
    33 del rawlist
    34 del server_ids
    35 
    36 # print servers
    37 
    38 # make service list
    39 services = {}
    40 dd = {}
    41 for serv in servers.keys():
    42         # print serv+'/SERVICE_LIST'
    43         sl_raw = pydim.dic_sync_info_service(serv+'/SERVICE_LIST','C')[0]
    44         if serv+'/SERVICE_DESC' in sl_raw:
    45                 sd_raw = pydim.dic_sync_info_service(serv+'/SERVICE_DESC','C')[0]
    46         else:
    47                 # print "Warning:", serv+'/SERVICE_DESC' , "not in SERVICE_LIST of", serv
    48                 sd_raw = ''
    49         sl_raw = sl_raw.rstrip('\x00\n')
    50         sl_raw = sl_raw.replace('\x00','')
    51         sd_raw = sd_raw.rstrip('\x00\n')
    52         sl = sl_raw.split('\n')
    53         sd = sd_raw.split('\n')
    54        
    55         # create descripton dict dd from service_desc list sd
    56         for d_str in sd:
    57                 service,equalsign,desc = d_str.partition('=')
    58                 #if '=' != equalsign:
    59                         # print "Error: server:", serv, "desc:", d_str
    60                 dd[service] = desc
    61 
    62 
    63         services[serv] = {}
    64         for service in sl:
    65                 service = service.split('|')
    66                 if service[0] in dd:
    67                         services[serv][service[0]] = (
    68                                         service[1], service[2], dd[service[0]])
    69          #      else:
    70                         # print service[0], 'has no DESC in SERVICE_DESC'
    71 
    72 # pprint( services )
    73 
    7420class FactDimServer( object ):
    7521
    76         def __init__(self, name):
    77                 self.name = name
    78 
    79         def cmd(self, cmdstr, *args):
    80                 #args = cmdstr.split(' ')
    81                 #for i in range(len(args)):
    82         #               i = len(args)-1-i
    83         #               if not args[i]:
    84         #                       del args[i]
    85                 cmdstr=self.name+'/'+cmdstr.upper()
    86         #       args = tuple(args[1:])
    87                 desc = services[self.name][cmdstr.upper()][0]
    88                 # there is a bug in the pydim library ...
    89                 # even if a command need no argument
    90                 # one has to give one ... need to tell Niko about it.
    91                 if len(desc) == 0:
    92                         desc = 'I'
    93                         args=(1,)
    94                 # print 'cmd: cmdstr:', cmdstr,
    95                 # print '-args:', args,
    96                 # print '-desc:', desc
    97                 pydim.dic_sync_cmnd_service(cmdstr, args, desc, timeout=None)
    98         def get(self, service):
    99                 full_srv_name = self.name+'/'+service.upper()
    100                 desc = services[self.name][full_srv_name][0]
    101                 return pydim.dic_sync_info_service(full_srv_name, desc)
    102 
    103         def __call__(self):
    104                 """ get Server State as numeric code
    105                     for convenience
    106                 """
    107                 if hasattr(self, 'state'):
    108                         s = self.state()[0]
    109                         return int(s[ s.find('[')+1 : s.find(']') ])
    110                 else:
    111                         raise TypeError(self.name+' has no CMD called STATE')
    112        
    113         def wait(self, state_num, timeout=None):
    114                 """ waits for a certain state
    115                         BLOCKING
    116                         returns True if state was reached
    117                         returns False if timeout occured
    118                         raises TypeError if Server has no method state
    119                 """
    120 
    121                 if not hasattr(self, 'state'):
    122                         raise TypeError(self.name+' has no CMD called STATE')
    123                 if timeout == None:
    124                         timeout = float('inf')
    125                 else:
    126                         timeout = float(timeout)
    127                 start = time.time()
    128                 while not self() == state_num:
    129                         time.sleep(0.1)
    130                         if time.time() >= start+timeout:
    131                                 return False
    132                 return True
     22    def __init__(self, name):
     23        """ sets name of instance to name of server, all uppercase
     24        """
     25        self.name = name.upper()
     26
     27    def _cmd(self, cmdstr, *args):
     28        """ used by all dynamicly created methods, which call a Dim CMD
     29        """
     30        cmdstr=self.name+'/'+cmdstr.upper()
     31        desc = services[self.name][cmdstr.upper()][0]
     32       
     33        # there is a work around for a bug in pydim
     34        # even if a command needs no argument, and desc is also empty string
     35        # one has to give one ... need to tell Niko about it.
     36        if not desc:
     37            desc = 'I'
     38            args=(1,)
     39        pydim.dic_sync_cmnd_service(cmdstr, args, desc, timeout=None)
     40
     41
     42    def _get(self, service):
     43        """ used by all dynamicly created methods, which get a service
     44        """
     45        full_srv_name = self.name+'/'+service.upper()
     46        desc = services[self.name][full_srv_name][0]
     47        return pydim.dic_sync_info_service(full_srv_name, desc)
     48
     49
     50    def __call__(self):
     51        """ Wrapper / For Convenience
     52            self.state() returns a string (if it exists)
     53            *returns* numeric state code, parsed from return of self.state()
     54        """
     55        if hasattr(self, 'state'):
     56            s = self.state()[0]
     57            return int(s[ s.find('[')+1 : s.find(']') ])
     58        else:
     59            raise TypeError(self.name+' has no CMD called STATE')
     60   
     61    def wait(self, state_num, timeout=None):
     62        """ waits for a certain state
     63            BLOCKING
     64            returns True if state was reached
     65            returns False if timeout occured
     66            raises TypeError if Server has no method state
     67        """
     68
     69        if not hasattr(self, 'state'):
     70            raise TypeError(self.name+' has no CMD called STATE')
     71        if timeout == None:
     72            timeout = float('inf')
     73        else:
     74            timeout = float(timeout)
     75        start = time.time()
     76        while not self() == state_num:
     77            time.sleep(0.1)
     78            if time.time() >= start+timeout:
     79                return False
     80        return True
     81
     82
     83
     84# utility functions for dynamic addid of methods to classes
     85def add_command(cls, name):
     86    meth_name = name.split('/')[1].lower()
     87    if iskeyword(meth_name):
     88        meth_name += '_cmd'
     89       
     90    # this is the new command, it simple calls the _cmd() method
     91    def new_command(self, *args):
     92        self._cmd(meth_name, *args)
     93       
     94    new_command.__name__ = meth_name
     95   
     96    # from this line on, the docstring of the method is created
     97    if name in dd:
     98        if not dd[name]:
     99            new_command.__doc__ = "DESC in SERVICE_DESC is empty ?!"
     100        else:
     101            new_command.__doc__ = dd[name]
     102    else:
     103        new_command.__doc__ = "-- no DESC found in SERVICE_DESC --"
     104    new_command.__doc__ += '\n'
     105    new_command.__doc__ += services[name.split('/')[0]][name][0]
     106   
     107    # this line make the new_command() method, a method of the class cls
     108    # giving it the name new_command.__name__
     109    setattr( cls, new_command.__name__, new_command)
     110
     111# add_getter is very similar to add_command,
     112# the only difference is, that it calls _get() instead of _cmd()
     113# and since _get() has a return value, this return value is vorwarded to the user
     114def add_getter(cls, name):
     115    meth_name = name.split('/')[1].lower()
     116    if iskeyword(meth_name):
     117        meth_name += '_cmd'
     118    def new_command(self):
     119        return self._get(meth_name)
     120    new_command.__name__ = meth_name
     121    if name in dd:
     122        if not dd[name]:
     123            new_command.__doc__ = "DESC in SERVICE_DESC is empty ?!"
     124        else:
     125            new_command.__doc__ = dd[name]
     126    else:
     127        new_command.__doc__ = "-- no DESC found in SERVICE_DESC --"
     128    new_command.__doc__ += '\n'
     129    new_command.__doc__ += services[name.split('/')[0]][name][0]
     130    setattr( cls, new_command.__name__, new_command)
     131
     132
     133
     134
     135
     136# In order to create classes according to the Dim-Servers, currently connected
     137# to the DIS_DNS I have to parse DIS_DNS/SERVER_LIST
     138# This is done in two steps, first I get the list of Server Names from DIS_DNS
     139# and the I get the list of each servers services and cmds,
     140# from each servers SERVICE_LIST and the service/command description
     141# from each servers SERVICE_DESC
     142# I get quite a lot of information, which I store in python dicts, or
     143# even nested dicts, if necessary.
     144
     145def ParseDnsServerList():
     146    # making server list
     147    rawlist = pydim.dic_sync_info_service('DIS_DNS/SERVER_LIST','C')
     148    # the output needs to be treated a bit .. it is a tuple with only one long string in it
     149    # the string contains | and the strange character \x00
     150    # I use both to cut the list apart
     151    rawlist = rawlist[0].split('\x00')
     152    servers_n_hosts = rawlist[0].split('|')
     153    server_ids = rawlist[1].split('|')
     154
     155    servers = {}
     156    for i,snh in enumerate(servers_n_hosts):
     157        snh = snh.split('@')
     158        s = snh[0]
     159        h = snh[1]
     160        sid = server_ids[i]
     161        servers[s] = (sid, h)
     162
     163    return servers
     164
     165
     166
     167# servers should be a dict containing uppercase server names as keys,
     168# the values are not needed, so it might be any iteratable python listlike type
     169# to be precise
     170def ParseServersServiceList( servers )
     171   
     172    services = {}
     173    dd = {}
     174    for server in servers:
     175        # sl_raw is a tuple, with an really long string, which needs to be parsed
     176        sl_raw = pydim.dic_sync_info_service(server+'/SERVICE_LIST','C')[0]
     177       
     178        # even without parsing, I can find out, if this server also gives me a
     179        # service description list. In case it does not, this is fine as well
     180        # the doc string of the dynamicly created methods, will then contain
     181        # a note, that therer was no SERVICE_DESC ...
     182        if server+'/SERVICE_DESC' in sl_raw:
     183            sd_raw = pydim.dic_sync_info_service(server+'/SERVICE_DESC','C')[0]
     184        else:
     185            sd_raw = ''
     186       
     187        # now before parsing, I strip off all ASCII zeroes '\x00' and all
     188        # line breaks off the *end* of the long string of both
     189        # the service list sl
     190        # and service description sd
     191        #
     192        # I think in sl_raw were alse some '\x00' in the middle .. these
     193        # are replaced by nothing, in case they are there.
     194        sl_raw = sl_raw.rstrip('\x00\n')
     195        sl_raw = sl_raw.replace('\x00','')
     196        sd_raw = sd_raw.rstrip('\x00\n')
     197       
     198        # The lists are seperated by line breaks, so I split them using this
     199        sl = sl_raw.split('\n')
     200        sd = sd_raw.split('\n')
     201       
     202        # First I parse the service descriptons, so I have them available,
     203        # when I create the dict full of services.
     204        # All desciptions look like this
     205        # 'SERVER/SERVICE=some descriptive text' or
     206        # 'SERVER/SERVICE='
     207        # this I use to create the dictionary.
     208        # create descripton dict dd from service_desc list sd
     209        for d_str in sd:
     210            service,equalsign,desc = d_str.partition('=')
     211            #if '=' != equalsign:
     212                # print "Error: server:", server, "desc:", d_str
     213            dd[service] = desc
     214
     215        # Now I fill ther services dict. Each server gets a nested dict
     216        # inside services.
     217        # Each service is explained in a string with a '|' in between.
     218        # I use this for spliting.
     219        # The string look like this
     220        # SERVER/SERVICE|format-desc-str(e.g. I:2;C)|-empty- or CMD or RPC|
     221        services[server] = {}
     222        for service in sl:
     223            service = service.split('|')
     224            if service[0] in dd:
     225                services[server][service[0]] = (
     226                        service[1], service[2], dd[service[0]])
     227    return services
     228
     229
     230servers = ParseDnsServerList()
     231services = ParseServersServiceList( servers )
     232
    133233# create one class for each Fact Dim Server
    134234FactDimServerClasses = []
    135235for server_name in servers:
    136         FactDimServerClasses.append(
    137                         types.ClassType( server_name, (FactDimServer,), {}) )
     236    FactDimServerClasses.append(
     237            types.ClassType( server_name, (FactDimServer,), {}) )
    138238
    139239# create an instace of each of the classes
     
    143243all_dims = []
    144244for i,server_name in enumerate(servers):
    145         new_instance = FactDimServerClasses[i](server_name)
    146         all_dims.append( new_instance )
     245    new_instance = FactDimServerClasses[i](server_name)
     246    all_dims.append( new_instance )
    147247del new_instance
    148248
     
    150250#print "connecting to Dim Servers... "
    151251for dim in all_dims:
    152 #       print dim.name.lower()
    153         if dim.name == 'DIS_DNS':
    154                 continue
    155         globals()[dim.name.lower()] = dim
    156         dims.append(dim)
    157 
    158 # utility class for dynamic addid of methods to classes
    159 def add_command(cls, name):
    160         meth_name = name.split('/')[1].lower()
    161         if iskeyword(meth_name):
    162                 meth_name += '_cmd'
    163         def new_command(self, *args):
    164                 self.cmd(meth_name, *args)
    165         new_command.__name__ = meth_name
    166         if name in dd:
    167                 if not dd[name]:
    168                         new_command.__doc__ = "DESC in SERVICE_DESC is empty ?!"
    169                 else:
    170                         new_command.__doc__ = dd[name]
    171         else:
    172                 new_command.__doc__ = "-- no DESC found in SERVICE_DESC --"
    173         new_command.__doc__ += '\n'
    174         new_command.__doc__ += services[name.split('/')[0]][name][0]
    175         setattr( cls, new_command.__name__, new_command)
    176 
    177 def add_getter(cls, name):
    178         meth_name = name.split('/')[1].lower()
    179         if iskeyword(meth_name):
    180                 meth_name += '_cmd'
    181         def new_command(self):
    182                 return self.get(meth_name)
    183         new_command.__name__ = meth_name
    184         if name in dd:
    185                 if not dd[name]:
    186                         new_command.__doc__ = "DESC in SERVICE_DESC is empty ?!"
    187                 else:
    188                         new_command.__doc__ = dd[name]
    189         else:
    190                 new_command.__doc__ = "-- no DESC found in SERVICE_DESC --"
    191         new_command.__doc__ += '\n'
    192         new_command.__doc__ += services[name.split('/')[0]][name][0]
    193         setattr( cls, new_command.__name__, new_command)
     252#    print dim.name.lower()
     253    if dim.name == 'DIS_DNS':
     254        continue
     255    globals()[dim.name.lower()] = dim
     256    dims.append(dim)
    194257
    195258for i,dim in enumerate(all_dims):
    196         for cmd in services[dim.name]:
    197                 if 'CMD' in services[dim.name][cmd][1]:
    198                         cmdname = cmd.split('/')[1]
    199                         add_command(FactDimServerClasses[i], cmd)
    200                 elif not services[dim.name][cmd][1]:
    201                         cmdname = cmd.split('/')[1]
    202                         add_getter(FactDimServerClasses[i], cmd)
    203 
     259    for cmd in services[dim.name]:
     260        if 'CMD' in services[dim.name][cmd][1]:
     261            cmdname = cmd.split('/')[1]
     262            add_command(FactDimServerClasses[i], cmd)
     263        elif not services[dim.name][cmd][1]:
     264            cmdname = cmd.split('/')[1]
     265            add_getter(FactDimServerClasses[i], cmd)
     266
     267##############################################################################
     268# class for colored printing
    204269
    205270class bcolors:
    206             HEADER = '\033[95m'
    207             OKBLUE = '\033[94m'
    208             OKGREEN = '\033[92m'
    209             WARNING = '\033[93m'
    210             FAIL = '\033[91m'
    211             ENDC = '\033[0m'
    212 
    213             def disable(self):
    214                 self.HEADER = ''
    215                 self.OKBLUE = ''
    216                 self.OKGREEN = ''
    217                 self.WARNING = ''
    218                 self.FAIL = ''
    219                 self.ENDC = ''
     271        HEADER = '\033[95m'
     272        OKBLUE = '\033[94m'
     273        OKGREEN = '\033[92m'
     274        WARNING = '\033[93m'
     275        FAIL = '\033[91m'
     276        ENDC = '\033[0m'
     277
     278        def disable(self):
     279            self.HEADER = ''
     280            self.OKBLUE = ''
     281            self.OKGREEN = ''
     282            self.WARNING = ''
     283            self.FAIL = ''
     284            self.ENDC = ''
     285
     286##############################################################################
     287# class which implements colored printing
     288# method calls can be used instead of Python print calls
     289# for conveniently printing colored output.
     290
     291
    220292class MSG( bcolors):
    221         def __init__(self, verbose = True):
    222                 self.output = verbose
    223        
    224         def fail(self, text ):
    225                 text = str(text)
    226                 if self.output:
    227                         print bcolors.FAIL + "ERROR:" + bcolors.ENDC,
    228                         print bcolors.FAIL + text + bcolors.ENDC
    229 
    230         def warn(self, text ):
    231                 text = str(text)
    232                 if self.output:
    233                         print bcolors.WARNING + text + bcolors.ENDC
    234 
    235         def ok(self, text ):
    236                 text = str(text)
    237                 if self.output:
    238                         print bcolors.OKGREEN + text + bcolors.ENDC
    239 
    240         def __call__(self, *args):
    241                 if self.output:
    242                         for arg in args:
    243                                 print arg,
    244                         print
    245 
     293    def __init__(self, verbose = True):
     294        """ create MSG instance,
     295            default is verbose,
     296            sets self.output
     297           
     298            if:
     299            self.*output* = True, object behaves as expeted
     300            if False, no call return anything
     301        """
     302        self.output = verbose
     303   
     304    def fail(self, text ):
     305        """ print in RED
     306        """
     307        text = str(text)
     308        if self.output:
     309            print bcolors.FAIL + "ERROR:" + bcolors.ENDC,
     310            print bcolors.FAIL + text + bcolors.ENDC
     311
     312    def warn(self, text ):
     313        """ print in YELLOW
     314        """
     315        text = str(text)
     316        if self.output:
     317            print bcolors.WARNING + text + bcolors.ENDC
     318
     319    def ok(self, text ):
     320        """ print in GREEN
     321        """
     322        text = str(text)
     323        if self.output:
     324            print bcolors.OKGREEN + text + bcolors.ENDC
     325
     326    def __call__(self, *args):
     327        """ print as Python print would do
     328        """
     329        if self.output:
     330            for arg in args:
     331                print arg,
     332            print
     333
  • fact/tools/PyDimCtrl/service.py

    r13770 r13789  
    1 #!/usr/bin/python -tt
    2         from fpydim import *
     1#!/usr/bin/python -tti
     2#from fpydim import *
     3
     4
    35
    46def IsReadyForDataTaking( verbose = True ):
    5         drive = drive_control
    6         bias = bias_control
    7         fad = fad_control
    8        
    9         msg = MSG()
    10         msg.output = verbose
    11         msg("Checking if System isready for data taking... ")
    12 
    13         ok = True
    14         if not drive() == 7:
    15                 msg.warn( drive.state()[0] + "  NOT ok")
    16                 ok = False
    17         if not feedback() == 12:
    18                 msg.warn( feedback.state()[0] + "  NOT ok")
    19                 ok = False
    20         if not bias() == 9:
    21                 msg.warn( bias.state()[0] + "  NOT ok")
    22                 ok = False
    23         if not fad() == 4:
    24                 msg.warn( fad.state()[0] + "  NOT ok")
    25                 ok = False
    26        
    27         if ok:
    28                 msg.ok( " all ok " )
    29 
    30         return ok
     7    drive = drive_control
     8    bias = bias_control
     9    fad = fad_control
     10   
     11    msg = MSG()
     12    msg.output = verbose
     13    msg("Checking if System isready for data taking... ")
     14
     15    ok = True
     16    if not drive() == 7:
     17        msg.warn( drive.state()[0] + "  NOT ok")
     18        ok = False
     19    if not feedback() == 12:
     20        msg.warn( feedback.state()[0] + "  NOT ok")
     21        ok = False
     22    if not bias() == 9:
     23        msg.warn( bias.state()[0] + "  NOT ok")
     24        ok = False
     25    if not fad() == 4:
     26        msg.warn( fad.state()[0] + "  NOT ok")
     27        ok = False
     28   
     29    if ok:
     30        msg.ok( " all ok " )
     31
     32    return ok
    3133
    3234def StopTracking( verbose = True ):
    33         msg = MSG()
    34         msg.output = verbose
    35 
    36         # defining a shortcut
    37         drive = drive_control
    38 
    39         drive.stop()
    40         if not drive.wait(5, 10):
    41                 msg.warn("drive did not reach state 5 after 10 seconds")
    42                 msg.warn( drive.state()[0].rstrip('\x00') )
    43                 return False
    44 
    45         return True
     35    msg = MSG()
     36    msg.output = verbose
     37
     38    # defining a shortcut
     39    drive = drive_control
     40
     41    drive.stop()
     42    if not drive.wait(5, 10):
     43        msg.warn("drive did not reach state 5 after 10 seconds")
     44        msg.warn( drive.state()[0].rstrip('\x00') )
     45        return False
     46
     47    return True
    4648
    4749def TakeDataRun( verbose = True ):
    48         fad = fad_control       
    49         msg = MSG()
    50         msg.output = verbose
    51         if not IsReadyForDataTaking( verbose=False ):
    52                 msg.fail("System not Ready for DataTaking")
    53                 IsReadyForDataTaking( verbose=True )
    54                 return False
    55         mcp.start(300,-1,'data\0')
    56         if not fad.wait(8, 10):
    57                 msg.warn("FAD not in Writing Data after 10seconds")
    58                 return False
    59         msg("... taking data: 300 seconds - normal data run")
    60         if not fad.wait(4, 330):
    61                 msg.warn("FAD did not return to Connected, after 330 seconds")
    62                 return False
    63         return True
     50    fad = fad_control   
     51    msg = MSG()
     52    msg.output = verbose
     53    if not IsReadyForDataTaking( verbose=False ):
     54        msg.fail("System not Ready for DataTaking")
     55        IsReadyForDataTaking( verbose=True )
     56        return False
     57    mcp.start(300,-1,'data\0')
     58    if not fad.wait(8, 10):
     59        msg.warn("FAD not in Writing Data after 10seconds")
     60        return False
     61    msg("... taking data: 300 seconds - normal data run")
     62    if not fad.wait(4, 330):
     63        msg.warn("FAD did not return to Connected, after 330 seconds")
     64        return False
     65    return True
    6466
    6567def TrackSource( Shift=0.6, Angle=50, SrcName='Crab', verbose=True):
    66         drive = drive_control
    67        
    68         msg = MSG()
    69         msg.output = verbose
    70 
    71         if not drive.wait(5, 10):
    72                 msg.warn("drive not ready after 10sec")
    73                 msg.warn( drive.state()[0].rstrip('\x00') )
    74                 return False
    75 
    76         SrcName += '\0'
    77         drive.track_source( Shift, Angle, SrcName)
    78        
    79         return True
     68    drive = drive_control
     69   
     70    msg = MSG()
     71    msg.output = verbose
     72
     73    if not drive.wait(5, 10):
     74        msg.warn("drive not ready after 10sec")
     75        msg.warn( drive.state()[0].rstrip('\x00') )
     76        return False
     77
     78    SrcName += '\0'
     79    drive.track_source( Shift, Angle, SrcName)
     80   
     81    return True
    8082
    8183def WaitForTracking( CalmDownTime = 30, verbose = True):
    82         drive = drive_control
    83 
    84         msg = MSG()
    85         msg.output = verbose
    86 
    87         if not drive.wait(6, 10):
    88                 msg.warn("drive not in state moving after 10sec")
    89                 return False
    90 
    91         if not drive.wait(7, 10):
    92                 msg.warn("drive not in state Tracking after 10sec")
    93                 return False
    94 
    95         msg("waiting "+str(CalmDownTime)\
    96                         +"sec for drive to calm down and tracking to be stable")
    97         time.sleep(CalmDownTime)
    98         zoreturn True
     84    drive = drive_control
     85
     86    msg = MSG()
     87    msg.output = verbose
     88
     89    if not drive.wait(6, 10):
     90        msg.warn("drive not in state moving after 10sec")
     91        return False
     92
     93    if not drive.wait(7, 10):
     94        msg.warn("drive not in state Tracking after 10sec")
     95        return False
     96
     97    msg("waiting "+str(CalmDownTime)\
     98            +"sec for drive to calm down and tracking to be stable")
     99    time.sleep(CalmDownTime)
     100    return True
    99101
    100102def PrepareBias( verbose = True):
    101         msg = MSG()
    102         msg.output = verbose
    103         bias = bias_control
    104 
    105         if feedback() != 12:
    106                 msg.warn("feedback is not in Current Control")
    107                 return False
    108 
    109         bias.set_global_dac(1)
    110         if not bias.wait(9, 10):
    111                 msg.warn("bias not in Voltage ON after 10sec")
    112                 return False
    113         if not bias.wait(5, 10):
    114                 msg.warn("bias not Ramping after 10sec")
    115                 return False
    116         if not bias.wait(9, 30):
    117                 msg.warn("bias not fully ramped up after 30sec")
    118                 return False
    119 
    120         msg("waiting 45sec...")
    121         time.sleep(45)
    122         return True
     103    msg = MSG()
     104    msg.output = verbose
     105    bias = bias_control
     106
     107    if feedback() != 12:
     108        msg.warn("feedback is not in Current Control")
     109        return False
     110
     111    bias.set_global_dac(1)
     112    if not bias.wait(9, 10):
     113        msg.warn("bias not in Voltage ON after 10sec")
     114        return False
     115    if not bias.wait(5, 10):
     116        msg.warn("bias not Ramping after 10sec")
     117        return False
     118    if not bias.wait(9, 30):
     119        msg.warn("bias not fully ramped up after 30sec")
     120        return False
     121
     122    msg("waiting 45sec...")   
     123    time.sleep(45)
     124    return True
    123125
    124126def TakePedestalOnRun( verbose = True ):
    125         msg = MSG()
    126         msg.output = verbose
    127         if not IsReadyForDataTaking( verbose=False ):
    128                 msg.fail("System not Ready for DataTaking")
    129                 IsReadyForDataTaking( verbose=True )
    130                 return False
    131         mcp.start(-1,1000,'pedestal\0')
    132         if not fad.wait(8, 10):
    133                 msg.warn("FAD not in Writing Data after 10seconds")
    134                 return False
    135         msg("... taking ped: 1000evts @25Hz")
    136         if not fad.wait(4, 50):
    137                 msg.warn("FAD did not return to Connected, after 50 seconds")
    138                 return False
    139         return True
    140        
     127    msg = MSG()
     128    msg.output = verbose
     129    if not IsReadyForDataTaking( verbose=False ):
     130        msg.fail("System not Ready for DataTaking")
     131        IsReadyForDataTaking( verbose=True )
     132        return False
     133    mcp.start(-1,1000,'pedestal\0')
     134    if not fad.wait(8, 10):
     135        msg.warn("FAD not in Writing Data after 10seconds")
     136        return False
     137    msg("... taking ped: 1000evts @25Hz")
     138    if not fad.wait(4, 50):
     139        msg.warn("FAD did not return to Connected, after 50 seconds")
     140        return False
     141    return True
     142   
    141143def TakeExtLpRun( verbose = True ):
    142         msg = MSG()
    143         msg.output = verbose
    144         if not IsReadyForDataTaking( verbose=False ):
    145                 msg.fail("System not Ready for DataTaking")
    146                 IsReadyForDataTaking( verbose=True )
    147                 return False
    148         mcp.start(-1,1000,'light-pulser-ext\0')
    149         if not fad.wait(8, 10):
    150                 msg.warn("FAD not in Writing Data after 10seconds")
    151                 return False
    152         msg("... taking light-pulser-ext: 1000evts @25Hz")
    153         if not fad.wait(4, 50):
    154                 msg.warn("FAD did not return to Connected, after 50 seconds")
    155                 return False
    156         zoreturn True
     144    msg = MSG()
     145    msg.output = verbose
     146    if not IsReadyForDataTaking( verbose=False ):
     147        msg.fail("System not Ready for DataTaking")
     148        IsReadyForDataTaking( verbose=True )
     149        return False
     150    mcp.start(-1,1000,'light-pulser-ext\0')
     151    if not fad.wait(8, 10):
     152        msg.warn("FAD not in Writing Data after 10seconds")
     153        return False
     154    msg("... taking light-pulser-ext: 1000evts @25Hz")
     155    if not fad.wait(4, 50):
     156        msg.warn("FAD did not return to Connected, after 50 seconds")
     157        return False
     158    return True
    157159
    158160def TakeData( verbose = True):
    159         msg = MSG()
    160         msg.output = verbose
    161         TakePedestalOnRun()
    162         TakeExtLpRun()
    163         for i in range(4):
    164                 i +=1
    165                 msg("Taking Data Run "+str(i)+" of 4")
    166                 TakeDataRun()
     161    msg = MSG()
     162    msg.output = verbose
     163    TakePedestalOnRun()
     164    TakeExtLpRun()
     165    for i in range(4):
     166        i +=1
     167        msg("Taking Data Run "+str(i)+" of 4")
     168        TakeDataRun()
    167169
    168170def Take( time=0, events=0, runtype='drs-pedestal', verbose=True):
    169         msg = MSG()
    170         msg.output = verbose
    171         fad = fad_control
    172         runtype += '\0'
    173         if not fad.wait(4, 10):
    174                 msg.warn("fad not connected after 10sec")
    175                 return False
    176         mcp.start( time, events, runtype)
    177         if not fad.wait(8, 30):
    178                 msg.warn("fad not Writing Data after 30sec")
    179                 return False
    180         timeout = float('inf')
    181         if time != -1:
    182                 timeout = time*1.1
    183         if not fad.wait(4, timeout):
    184                 msg.warn("Data Writing not finished after "+str(timeout)+"sec")
    185                 return False
    186         return True
     171    msg = MSG()
     172    msg.output = verbose
     173    fad = fad_control
     174    runtype += '\0'
     175    if not fad.wait(4, 10):
     176        msg.warn("fad not connected after 10sec")
     177        return False
     178    mcp.start( time, events, runtype)
     179    if not fad.wait(8, 30):
     180        msg.warn("fad not Writing Data after 30sec")
     181        return False
     182    timeout = float('inf')
     183    if time != -1:
     184        timeout = time*1.1
     185    if not fad.wait(4, timeout):
     186        msg.warn("Data Writing not finished after "+str(timeout)+"sec")
     187        return False
     188    return True
    187189
    188190def TakeDrsCalibration( verbose = True):
    189         msg = MSG()
    190         msg.output = verbose
    191         bias = bias_control
    192         fad = fad_control
    193 
    194         bias.set_zero_voltage()
    195         if not bias.wait(7, 10):
    196                 msg.warn("bias has not switched of after 10sec")
    197                 return False
    198         fad.start_drs_calibration()
    199         Take( -1, 1000, 'drs-pedestal')
    200         Take( -1, 1000, 'drs-gain')
    201         Take( -1, 1000, 'drs-pedestal')
    202         fad.set_file_format(2)
    203         Take( -1, 1000, 'drs-pedestal')
    204         Take( -1, 1000, 'drs-time')
    205         Take( -1, 1000, 'drs-time-upshifted')
    206         fad.reset_secondary_drs_baseline()
    207         Take(-1, 1000, 'pedestal')
    208         fad.set_file_format(2)
    209         Take(-1, 1000, 'pedestal')
     191    msg = MSG()
     192    msg.output = verbose
     193    bias = bias_control
     194    fad = fad_control
     195
     196    bias.set_zero_voltage()
     197    if not bias.wait(7, 10):
     198        msg.warn("bias has not switched of after 10sec")
     199        return False
     200    fad.start_drs_calibration()
     201    Take( -1, 1000, 'drs-pedestal')
     202    Take( -1, 1000, 'drs-gain')
     203    Take( -1, 1000, 'drs-pedestal')
     204    fad.set_file_format(2)
     205    Take( -1, 1000, 'drs-pedestal')
     206    Take( -1, 1000, 'drs-time')
     207    Take( -1, 1000, 'drs-time-upshifted')
     208    fad.reset_secondary_drs_baseline()
     209    Take(-1, 1000, 'pedestal')
     210    fad.set_file_format(2)
     211    Take(-1, 1000, 'pedestal')
    210212
    211213def BlinkenLights(verbose = True):
    212         msg = MSG(verbose)
    213         fad = fad_control
    214 
    215         for i in range(10):
    216                 fad.set_file_format(2)
    217                 time.sleep(1)
    218                 fad.set_file_format(0)
    219                 time.sleep(1)
     214    msg = MSG(verbose)
     215    fad = fad_control
     216
     217    for i in range(10):
     218        fad.set_file_format(2)
     219        time.sleep(1)
     220        fad.set_file_format(0)
     221        time.sleep(1)
    220222
    221223def TakeAmplCalib( roi=1024, verbose=True):
    222         msg = MSG(verbose)
    223         bias = bias_control
    224         fad  = fad_control
    225         if (roi!=1024) and (roi!=300):
    226                 raise ValueError('roi must be 300 or 1024')
    227         # I do not understand, why the out put needs to be ENABLED??
    228         feedback.enable_output(0)
    229         bias.set_zero_voltage()
    230         bias.wait(7) # VoltageOff
    231         fad.start_drs_calibration
    232        
    233         Take(-1, 1000, 'drs-pedestal')
    234         Take(-1, 1000, 'drs-gain')
    235         if roi == 300:
    236                 Take(-1, 1000, 'pedestal')
    237         if roi == 1024:
    238                 Take(-1, 1000, 'drs-pedestal')
    239 
    240         fad.set_file_format(2)
    241         if roi == 300:
    242                 Take(-1, 1000, 'pedestal')
    243         if roi == 1024:
    244                 Take(-1, 1000, 'drs-pedestal')
     224    msg = MSG(verbose)
     225    bias = bias_control
     226    fad  = fad_control
     227    if (roi!=1024) and (roi!=300):
     228        raise ValueError('roi must be 300 or 1024')
     229    # I do not understand, why the out put needs to be ENABLED??
     230    feedback.enable_output(0)
     231    bias.set_zero_voltage()
     232    bias.wait(7) # VoltageOff
     233    fad.start_drs_calibration
     234   
     235    Take(-1, 1000, 'drs-pedestal')
     236    Take(-1, 1000, 'drs-gain')
     237    if roi == 300:
     238        Take(-1, 1000, 'pedestal')
     239    if roi == 1024:
     240        Take(-1, 1000, 'drs-pedestal')
     241
     242    fad.set_file_format(2)
     243    if roi == 300:
     244        Take(-1, 1000, 'pedestal')
     245    if roi == 1024:
     246        Take(-1, 1000, 'drs-pedestal')
    245247
    246248def TakeTimeCalib( verbose=True ):
    247         msg = MSG( verbose )
    248         feedback.enable_output(0)
    249         if bias() != 7:
    250                 bias.set_zero_voltage()
    251                 if not bias.wait(7, 10):
    252                         msg.warn("bias not ramped down after 10sec")
    253                         return False
    254         fad.set_file_format(2)
    255         Take(-1, 1000, 'drs-time')
    256         Take(-1, 1000, 'drs-time-upshifted')
     249    msg = MSG( verbose )
     250    feedback.enable_output(0)
     251    if bias() != 7:
     252        bias.set_zero_voltage()
     253        if not bias.wait(7, 10):
     254            msg.warn("bias not ramped down after 10sec")
     255            return False
     256    fad.set_file_format(2)
     257    Take(-1, 1000, 'drs-time')
     258    Take(-1, 1000, 'drs-time-upshifted')
     259
     260
     261# create introduction:
     262class INTRO(object):
     263    def __init__(self):
     264        # nothing to do
     265        pass
     266       
     267    def __repr__(self):
     268        print "welcome to PyDimCtrl V0.1:"
     269        print "--------------------------"
     270        print "If the hardware is ON but not all the software is connected try:"
     271        print "      Connect()"
     272        print "If all the programs are already up and running, you might want to"
     273        print "     TakeDrsAmplitudeCalibration(roi=1024) or "
     274        print "     TakeDrsAmplitudeCalibration(roi=300)"
     275        print "         i.e. ped, gain, trigger_offset + extra ped(for X-check)"
     276        print "     TakeDrsTimeCalibration( type='upshifted' ) or "
     277        print "     TakeDrsTimeCalibration( type='old' ) or "
     278        print "     "
     279        print "In case you would like to ramp up the Bias voltage try:"
     280        print "     VoltageOn( mode='temperature' ) or"
     281        print "     VoltageOn( mode='current' ) or"
     282        print "     VoltageOn( mode='light_pulser' )"
     283        print "Switch off with:"
     284        print "     VoltageOff()"
     285        print ""
     286        print "In case you would like a Watchdog to check, if the Voltage is up"
     287        print "and the BiasCrate is not disconnected, then try:"
     288        print "     VoltageOn( mode='--see above--', Watchdog=True )"
     289        print "PLEASE NOTE: The Watchdog will monitor the State of BIAS_CONTROL"
     290        print "and in case of a connection loss, it will: "
     291        print "     * print a warning"
     292        print "     * issue a the RECONNECT command"
     293        print "     * issue SET_ZERO_VOLTAGE - since this is the only way to get referenced"
     294        print "     * Ramp up again, using the same settings as before"
     295        print "     * possible OverCurrent situation will be treated as usual"
     296        print "The Watchdog will not react on any other state change, like OverCurrent or VoltageOff"
     297        print ""
     298        print ""
     299        return ""
     300       
     301
     302intro = INTRO()
    257303
    258304if __name__ == '__main__':
    259         IsReadyForDataTaking()
    260         TrackSource( Shift=0.6, Angle=50, SrcName='Crab', verbose=True)
    261         WaitForTracking( CalmDownTime = 30, verbose = True)
    262         TakeDataRun()
    263         StopTracking()
     305    print "welcome:"
     306    print " type: intro"
     307    print " for a short introduction"
     308
     309   
     310    #IsReadyForDataTaking()
     311    #TrackSource( Shift=0.6, Angle=50, SrcName='Crab', verbose=True)
     312    #WaitForTracking( CalmDownTime = 30, verbose = True)
     313    #TakeDataRun()
     314    #StopTracking()
Note: See TracChangeset for help on using the changeset viewer.