Index: fact/tools/PyDimCtrl/ScriptsForPyDimCtrl.py
===================================================================
--- fact/tools/PyDimCtrl/ScriptsForPyDimCtrl.py	(revision 14464)
+++ fact/tools/PyDimCtrl/ScriptsForPyDimCtrl.py	(revision 14466)
@@ -13,4 +13,29 @@
 
 report_length = 0
+
+source_list = [
+  ['Crab',          0.6,  50, -130],
+  ["1ES 2344+51.4", 0.6,  90, -90 ],
+  ["Mrk 501",       0.6, -22, -22+180 ],
+  ["Mrk 421",       0.6,  90, -90 ],
+  ["1ES 1218+304",  0.6,  -5, -5+180 ],
+  ["1ES 1959+650",  0.6, 155, 155-180 ],
+  ["Dark Patch 2",  0.6,  90, -90 ],
+  ["Dark Patch 3",  0.6,  90, -90 ],
+  ["H 1426+428",    0.6,  90, -90 ],
+  ["IC 310",        0.6, -18, -18+180 ],
+  ["PKS 2155-304",  0.6,  90, -90 ] ]
+  
+sourcedict = {}
+def make_sourcedict():
+  for s in source_list:
+    sourcedict[s[0]] = {}
+    sourcedict[s[0]]['wobble_offset'] = s[1]
+    sourcedict[s[0]]['wobble_angle1'] = s[2]
+    sourcedict[s[0]]['wobble_angle2'] = s[3]
+
+
+
+
 
 def wait_nice(self, state_num, timeout=None):                            
@@ -98,31 +123,35 @@
 
 
-def IsReadyForDataTaking():
+def IsReadyForDataTaking( verbose=False ):
   """ Checking the system statuses if they are ready for data taking
   """
-
-  print "--------------------------------------"
-  print "Checking the system statuses of:"
-  print "FEEDBACK, BIAS, FAD and DRIVE_CONTROL"
-  print "--------------------------------------"
-
-  print "...waiting for FEEDBACK"
-  print "   to be in state 12: CurrentControl"
+  if verbose:
+    print "--------------------------------------"
+    print "Checking the system statuses of:"
+    print "FEEDBACK, BIAS, FAD and DRIVE_CONTROL"
+    print "--------------------------------------"
+
+    print "...waiting for FEEDBACK"
+    print "   to be in state 12: CurrentControl"
   feedback.wait(12)
 
-  print "...waiting for BIAS_CONTROL"
-  print "   to be in state 9: VoltageOn"
+  if verbose:
+    print "...waiting for BIAS_CONTROL"
+    print "   to be in state 9: VoltageOn"
   bias_control.wait(9)
 
-  print "...waiting for FAD_CONTROL"
-  print "   to be in state 4: Connected"
+  if verbose:
+    print "...waiting for FAD_CONTROL"
+    print "   to be in state 4: Connected"
   fad_control.wait(4)
 
-  print "...waiting for drive_CONTROL"
-  print "   to be in state 8: Tracking"
+  if verbose:
+    print "...waiting for drive_CONTROL"
+    print "   to be in state 8: Tracking"
   drive_control.wait(8)
 
-  print "...system statuses OK"
-  print "--------------------------------------"
+  if verbose:
+    print "...system statuses OK"
+    print "--------------------------------------"
 
 def NotReadyForDataTaking( servers_n_targets = [ (feedback, 12),
@@ -286,5 +315,5 @@
   """
   runtype += '\0'
-
+  
   if verbose:
     print ' taking', runtype,'. ', num_events, 'events in', time, 'seconds'
@@ -299,4 +328,125 @@
   if verbose:
     print '... done'
+
+def TakeBetter( time, num_events, runtype, 
+                Bias = None,
+                Drive = None,
+                
+                verbose=False):
+  """
+  """
+  if Bias not in [None, 'On', 'Off']:
+    raise ValueError('Bias needs to be one of [None, 'On', 'Off']')
+    return False
+
+
+  runtype += '\0'
+  
+  # FAD:
+  #
+  # It makes no sense to try to take data, when the FADs are not well connected.
+  # Also I think it makes no sense to start datataking, when FAD is in WritingData
+  # and when MCP is not in an Idle state...
+  #
+  # we will check if FAD is in Connected(4), if in Writing_Data(8), we will send: close_all_open_files()
+  # if in one of the configuring states(5,6,7) we will send reset_configure
+  # if in Connecting(3), we will try to find which board is making problems...
+  # and disconnect and connect it --> THREE TIMES
+  # if it doesn't help.
+  # we abort.
+  # 
+  # 
+
+  
+  # FTM:
+  # the ftm is not so critcal, since it makes no problems normally... 
+  # It can be in triggerON(4) or Idle(3)
+  # Connected(2) is not good here we need a power cycle
+  # Any of the Configured States (5,6,7) should be treated with reset_configure()
+  #
+  # we will anyway check if in Connected(2) before starting.
+
+  # DRIVE_CONTROL:
+  # in case *Drive* is a valid sourcename from sourcedict, 
+  # we will give the command to point to that source in ON mode
+  # in case *Drive* is a tuple of ('sourcename', 1 || 2)
+  # We will point to that soource in wobble mode.
+  #
+  # If Drive is 'Stop. The Drive will be stopped 
+  # 
+  # In anycase The Drive will be checked for not beeing in the state ERROR
+  # in that case we will send DRIVE_CONTROL/STOP and the last tracking 
+  # command or nothing in case Drive = 'Stop'
+  #
+  # In case Drive is None no commands will be send to DRIVE_CONTROL at allow
+  
+  # RATE_CTRL
+  #
+  # Rate_control should be in Connected(4) and not lower
+  # 5,6,7 should not be the case ... STOP will help, I hope
+  # 
+  # we will try to get it into Connected, by sending STOP once
+  # if not successful we abort
+  
+  start_time = time.time()
+  duration = 10.
+  while fad_control.stn != 4:
+    if fad_control.stn in [5,6,7]: # Configure State --> Reset_Configure
+      fad_control.reset_configure()
+    elif fad_control.stn == 8: #WritingData --> Close_all_open_files()
+      fad_control.close_open_files()
+    elif fad_control.stn == 3: #Connecting --> try to find 'bad' board and reconnect
+      duration = 60.
+      print 'fad_control in state Connecting ... trying to find "bad" board'
+      print 'timeout increased to 60.sec'
+      conn = GetFadConnections()
+      bad = np.where( conn != 0x42 )[0]
+      print 'possible bad boards', bad
+      print 'disconnecting'
+      for b in bad:
+        fad_control.disconnect(b)
+      time.sleep(3.)
+      for b in bad:
+        fad_control.connect(b)
+    else:                       # really bad .. abort
+      print 'ERROR: FAD_CTRL in state', fad_control.stn, fad_control.sts
+      print 'I do not know how to treat that ... aborting'
+      return False
+  
+    time.sleep(1.)
+    if time.time() - start_time > duration:
+      print 'Timeout during try to get FAD into Connected'
+      return False
+  
+  # BIAS
+  #
+  # As well it makes no sense to try to take data, when the Bias control is in an
+  # undefined state.
+  # When *Bias* is 'On' we will take care that the Bias voltage is on, and stays on
+  # When *Bias* is 'Off' we will shut bias down and do nothing more
+  # When *Bias* is None -default- then no commands will be send to BiasCtrl
+  
+  start_time = time.time()
+  duration = 20.
+  if Bias == 'On':
+    if (bias_control.voltage()[0:320].mean() > 60) and 
+      ( (bias_control.stn == 5) or (bias_control.stn == 9) )
+      
+  elif Bias == 'Off':
+    
+
+  if verbose:
+    print ' taking', runtype,'. ', num_events, 'events in', time, 'seconds'
+  mcp.start(time, num_events, runtype)
+
+  if verbose:
+    print '...waiting for FAD to be in state 8: Writing Data'
+  fad_control.wait(8) # Writing Data
+  if verbose:
+    print '...waiting for FAD to be in state 4: Connected'
+  fad_control.wait_nice(4) # Connected
+  if verbose:
+    print '... done'
+
 
 
@@ -464,9 +614,9 @@
     # this 10sec wait is needed in order for the bias not to disconect all the time...
     print " ... current calibration done"
-    time.sleep(10)
+    #time.sleep(10)
 
     print " switching off bias"
     bias_control.set_zero_voltage()
-    time.sleep(5)
+    #time.sleep(5)
     print " ...waiting for BIAS to be in state 7: VoltageOff"
     bias_control.wait(7)
@@ -486,5 +636,5 @@
 
   fad_control.start_drs_calibration()
-  time.sleep(0.5)
+  #time.sleep(0.5)
   Take( -1, 1000, 'drs-pedestal')
 
@@ -803,27 +953,4 @@
   print '... done'
 
-source_list = [
-  ['Crab', 0.6 , 50, -130],
-  ["1ES 2344+51.4", 0.6 , 90, -90 ],
-  ["Mrk 501", 0.6,  -22, -22+180 ],
-  ["Mrk 421", 0.6, 90, -90 ],
-  ["1ES 1218+304", 0.6, -5, -5+180 ],
-  ["1ES 1959+650", 0.6,  155, 155-180 ],
-  ["Dark Patch 2", 0.6 , 90, -90 ],
-  ["Dark Patch 3", 0.6 , 90, -90 ],
-  ["H 1426+428", 0.6 , 90, -90 ],
-  ["IC 310", 0.6,  -18, -18+180 ],
-  ["PKS 2155-304", 0.6,  90, -90 ] ]
-  
-sourcedict = {}
-
-def make_sourcedict():
-  for s in source_list:
-    sourcedict[s[0]] = {}
-    sourcedict[s[0]]['wobble_offset'] = s[1]
-    sourcedict[s[0]]['wobble_angle1'] = s[2]
-    sourcedict[s[0]]['wobble_angle2'] = s[3]
-
-
 def TakeSource( name ):
   if name not in sourcedict:
@@ -860,4 +987,22 @@
 
 
+
+def GetFadConnections( verbose = False ):
+  """ return np.array(40) with bitmaps, showing the FADs connection status:
+      apperently this is the meaning:
+      0x43 -- well connected and well configured           -- green with white tick mark
+      0x42 -- well connected                               -- green
+      0x09 -- something is wrong with the connection       -- orange or red?
+      0x00 -- not connected, and not attempting to connect -- grey
+  """
+  
+  conn = np.array(map( ord, fad_control.connections()[0] ))
+  if verbose:
+    for crate in range(4):
+      print map( hex, conn[crate*10: (crate+1) *10 ] )
+  return conn
+  
+  
+  
 if __name__ == '__main__':
   print 'Welcome to PyDimCtrl'
@@ -871,2 +1016,4 @@
     print dim.name,
   print
+
+
