def main(): # this setup stuff should eventually go into the data base phi_node_dict = {} node_prefix = "payload.mu_deserialization." offsets = [] node_names = [] for j in range(2): # for both endcap+ and overlap+ 60 degrees sectors for i in range(6): # 6 channels each offsets.append(i*96 + 24) for i in range(12): # for barrel 12*30 degree wedges offsets.append((i * 48 + 576 - 24) % 576) for j in range(2): # for both endcap- and overlap- 60 degrees sectors for i in range(6): # 6 channels each offsets.append(i*96 + 24) for quad in range(9): for channel in range(4): node_name = node_prefix + "mu_quad{q}.phi_offset_{ch}".format(q=quad, ch=channel) phi_node_dict[node_name] = offsets[quad*4+channel] node_names.append(node_name) opts = parse_options() uhal.setLogLevelTo(uhal.LogLevel.ERROR) cm = uhal.ConnectionManager("file://${MP7_TESTS}/etc/mp7/connections-test.xml") board = cm.getDevice(opts.board) board.getNode('ctrl.id').read() try: board.dispatch() except: # print something here when if times out print 'MP7 access failed (name:', board.id(), 'uri:', board.uri(), ')' sys.exit(-1) if opts.mode == "read": values = {} for node, value in phi_node_dict.iteritems(): values[node] = board.getNode(node).read() try: board.dispatch() except: print 'read failed' sys.exit(-1) for node in node_names: print node, " = ", hex(values[node]), " .. should be", hex(phi_node_dict[node]) return if opts.mode == "write": for node, value in phi_node_dict.iteritems(): board.getNode(node).write(value) try: board.dispatch() except: print 'write failed' sys.exit(-1) print "wrote values to phi offset registers."
def getinfo(): uhal.setLogLevelTo(uhal.LogLevel.WARNING) cm = uhal.ConnectionManager( 'file://${TIMING_SHARE}/config/etc/connections.xml') device = cm.getDevice('OVLD_TUN') readMAC(device)
def init_board(library, deviceaddress, xmlfile): global board uhal.setLogLevelTo(uhal.LogLevel.INFO) board = uhal.getDevice("glib", "ipbusudp-2.0://" + deviceaddress + ":50001", "file://" + xmlfile) board.getClient().setTimeoutPeriod(10000) nodeslist = board.getNodes() deletelist = [] return nodeslist
def run(board, sdfile): if not sdfile: logging.error( 'No firmware image given. Listing image names on uSD...') hlp.listFilesOnSD(board) else: logging.info("Rebooting FPGA with firmware image %s..." % sdfile) uhal.setLogLevelTo(uhal.LogLevel.FATAL) board.rebootFPGA(sdfile) uhal.setLogLevelTo(uhal.LogLevel.ERROR)
def __init__(self,name,go=True,freq=100,odir="blah"): self._name = name; self._go = go; self._freq = freq; self._odir = odir; self._manager = uhal.ConnectionManager("file://../data/vipram_connections.xml"); self._hw = self._manager.getDevice("Mezz1") uhal.setLogLevelTo( uhal.LogLevel.ERROR ) self._ident = self._hw.getNode("VipMEM.Ident").read(); self._vers = self._hw.getNode("VipMEM.FWver").read(); self._hw.dispatch(); print "Firmware identity = ", hex(self._ident), ", firmware version = ", self._vers; self._iSteps = 0; self._fSteps = 32; self._stepIncrement = 32; self._blockSize = 1024; ################### ## define registers self._registers = []; self._registers.append( 'CheckData' ); # CheckData for i in range(32-1,-1,-1): self._registers.append( 'Out'+str(i) ); self._registers.append( 'ReqL0' ); self._registers.append( 'Miss2' ); self._registers.append( 'Miss1' ); self._registers.append( 'Miss0' ); self._registers.append( 'RunMode' ); self._registers.append( 'Primary' ); self._registers.append( 'Latch' ); self._registers.append( 'EvRearm' ); for i in range(7): self._registers.append( "RA"+str(i) ); for i in range(5): self._registers.append( "CA"+str(i) ); for i in range(1,16): self._registers.append( "A"+str(i) ); self._registers.append( "A0" ); for i in range(1,16): self._registers.append( "B"+str(i) ); self._registers.append( "B0" ); for i in range(1,16): self._registers.append( "C"+str(i) ); self._registers.append( "C0" ); for i in range(1,16): self._registers.append( "D"+str(i) ); self._registers.append( "D0" ); print "registers size = ", len(self._registers); ################### # power numbers self._i_dvdd = []; self._i_vdd = []; self._i_prech = []; self._difftimes = [];
def GetUhalDevice(LogLevel = uhal.LogLevel.WARNING): uhal.setLogLevelTo(LogLevel) global uhalDevice if uhalDevice == 0: f = "addresses.xml" if not FileExists(f): f = "common/addresses.xml" if not FileExists(f): f = "../common/addresses.xml" if not FileExists(f): print Error_("Could not find file \"addresses.xml\"") raise uhalDevice = uhal.getDevice("fpga", "ipbusudp-2.0://134.158.152.64:50001", "file://"+f) # print "Creating device" return uhalDevice
def useUhalParser(test_xml, HDLPath, regMapTemplate, pkgTemplate="", verbose=False, debug=False, yml2hdl=False): # configure logger global log log = logging.getLogger("main") formatter = logging.Formatter('%(name)s %(levelname)s: %(message)s') handler = logging.StreamHandler(sys.stdout) handler.setFormatter(formatter) log.addHandler(handler) log.setLevel(logging.WARNING) uhal.setLogLevelTo(uhal.LogLevel.WARNING) if verbose: log.setLevel(logging.INFO) uhal.setLogLevelTo(uhal.LogLevel.INFO) if debug: log.setLevel(logging.DEBUG) uhal.setLogLevelTo(uhal.LogLevel.DEBUG) try: device = uhal.getDevice( "dummy", "ipbusudp-1.3://localhost:12345", "file://" + test_xml) except Exception: raise Exception( "File '%s' does not exist or has incorrect format" % test_xml) if not os.path.exists(HDLPath): os.makedirs(HDLPath) cwd = os.getcwd() os.chdir(os.path.abspath(HDLPath)) for i in device.getNodes(): if i.count('.') == 0: mytree = tree.tree(device.getNode(i), log, yml2hdl=yml2hdl) mytree.generatePkg() mytree.generateRegMap(regMapTemplate=regMapTemplate) # test array-type # findArrayType(mytree.root) os.chdir(cwd)
class GEMDAQTestSuite: """ This python script will test the GLIB, optical links, OH, and VFAT2 functionalities. Simply follow the instructions on the screen in order to diagnose the setup. Thomas Lenzi - [email protected] Jared Sturdy - [email protected] (Adapted for uHAL) """ uhal.setLogLevelTo(uhal.LogLevel.FATAL) allTests = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"] def __init__(self, slot, gtx, tests="", test_params=TEST_PARAMS(), debug=False): """ """ self.slot = slot self.gtx = gtx self.tests = tests.upper().split(',') if ("J" in self.tests): self.tests.append("B") pass if ("I" in self.tests): self.tests.append("E") pass if ("H" in self.tests): self.tests.append("G") pass if ("G" in self.tests): self.tests.append("E") pass if ("F" in self.tests): self.tests.append("E") pass if ("E" in self.tests): self.tests.append("B") pass if ("D" in self.tests): self.tests.append("B") pass if ("C" in self.tests): self.tests.append("A") pass if ("B" in self.tests): self.tests.append("A") pass self.tests = list(set(self.tests)) self.test_params = test_params self.debug = debug self.uTCAslot = 170 if self.slot: uTCAslot = 160 + self.slot pass if self.debug: print self.slot, uTCAslot pass self.ipaddr = '192.168.0.%d' % (uTCAslot) self.address_table = "file://${GEM_ADDRESS_TABLE_PATH}/glib_address_table.xml" self.uri = "chtcp-2.0://localhost:10203?target=%s:50001" % ( self.ipaddr) self.glib = uhal.getDevice("glib", self.uri, self.address_table) self.oh_basenode = "GLIB.OptoHybrid_%d.OptoHybrid" % (self.gtx) self.presentVFAT2sSingle = [] self.presentVFAT2sFifo = [] self.chipIDs = None self.vfatmask = 0xff000000 self.test = {} self.test["A"] = False self.test["B"] = False self.test["C"] = False self.test["D"] = False self.test["E"] = False self.test["F"] = False self.test["G"] = False self.test["H"] = False self.test["I"] = False self.test["J"] = False return #################################################### def GLIBPresenceTest(self): txtTitle("A. Testing the GLIB's presence") print " Trying to read the GLIB board ID... If this test fails, the script will stop." if (readRegister(self.glib, "GLIB.SYSTEM.BOARD_ID") != 0): print Passed else: print Failed sys.exit() pass self.test["A"] = True print #################################################### def OptoHybridPresenceTest(self): txtTitle("B. Testing the OH's presence") print " Trying to set the OptoHybrid registers... If this test fails, the script will stop." # setReferenceClock( self.glib, self.gtx, 1) setTriggerSource(self.glib, self.gtx, 1) setTriggerThrottle(self.glib, self.gtx, 0) if (getTriggerSource(self.glib, self.gtx) == 1): print Passed else: print Failed, "oh_trigger_source %d" % (getTriggerSource( self.glib, self.gtx)) sys.exit() pass # if (getReferenceClock(self.glib,self.gtx) == 1): # print Passed # else: # print Failed, "oh_clk_src %d"%(getReferenceClock(self.glib,self.gtx)) # sys.exit() # pass if (getTriggerThrottle(self.glib, self.gtx) == 0): print Passed else: print Failed, "oh_trg_throttle %d" % (getTriggerThrottle( self.glib, self.gtx)) sys.exit() pass self.test["B"] = True print return #################################################### def GLIBRegisterTest(self): txtTitle("C. Testing the GLIB registers") print " Performing single reads on the GLIB counters and ensuring they increment." countersSingle = [] countersTest = True for i in range(0, self.test_params.GLIB_REG_TEST): countersSingle.append( readRegister(self.glib, "GLIB.COUNTERS.IPBus.Strobe.Counters")) pass for i in range(1, self.test_params.GLIB_REG_TEST): if (countersSingle[i - 1] + 1 != countersSingle[i]): print "\033[91m > #%d previous %d, current %d \033[0m" % ( i, countersSingle[i - 1], countersSingle[i]) countersTest = False pass pass if (countersTest): print Passed else: print Failed pass self.test["C"] = countersTest print return #################################################### def OptoHybridRegisterTest(self): txtTitle("D. Testing the OH registers") print " Performing single reads on the OptoHybrid counters and ensuring they increment." countersSingle = [] countersTest = True for i in range(0, self.test_params.OH_REG_TEST): countersSingle.append( readRegister( self.glib, "%s.COUNTERS.WB.MASTER.Strobe.GTX" % (self.oh_basenode))) pass for i in range(1, self.test_params.OH_REG_TEST): if (countersSingle[i - 1] + 1 != countersSingle[i]): print "\033[91m > #%d previous %d, current %d \033[0m" % ( i, countersSingle[i - 1], countersSingle[i]) countersTest = False pass pass if (countersTest): print Passed else: print Failed pass self.test["D"] = countersTest print return #################################################### def VFAT2DetectionTest(self): txtTitle("E. Detecting the VFAT2s over I2C") print " Detecting VFAT2s on the GEM by reading out their chip ID." # writeRegister(self.glib,"%s.GEB.Broadcast.Reset"%(self.oh_basenode), 0) # readRegister(self.glib,"%s.GEB.Broadcast.Request.ChipID0"%(self.oh_basenode)) self.chipIDs = getAllChipIDs(self.glib, self.gtx) for i in range(0, 24): # missing VFAT shows 0x0003XX00 in I2C broadcast result # 0x05XX0800 # XX is slot number # so if ((result >> 16) & 0x3) == 0x3, chip is missing # or if ((result) & 0x30000) == 0x30000, chip is missing if (((readRegister( self.glib, "%s.GEB.VFATS.VFAT%d.ChipID0" % (self.oh_basenode, i)) >> 24) & 0x5) != 0x5): self.presentVFAT2sSingle.append(i) pass if (self.chipIDs[i] not in [0x0000, 0xdead]): self.presentVFAT2sFifo.append(i) pass pass if (self.presentVFAT2sSingle == self.presentVFAT2sFifo): print Passed pass else: print Failed pass self.test["E"] = True print " Detected", str(len( self.presentVFAT2sSingle)), "VFAT2s:", str( self.presentVFAT2sSingle) print self.vfatmask = setVFATTrackingMask(self.glib, self.gtx) return #################################################### def VFAT2I2CRegisterTest(self): txtTitle("F. Testing the I2C communication with the VFAT2s") print " Performing random read/write operation on each connect VFAT2." self.test["F"] = True for i in self.presentVFAT2sSingle: validOperations = 0 for j in range(0, self.test_params.I2C_TEST): writeData = random.randint(0, 255) writeVFAT(self.glib, self.gtx, i, "ContReg3", writeData) readData = (readVFAT(self.glib, self.gtx, i, "ContReg3") & 0xff) if (readData == writeData): validOperations += 1 pass else: print "0x%02x not 0x%02x" % (readData, writeData) pass writeVFAT(self.glib, self.gtx, i, "ContReg3", 0) if (validOperations == self.test_params.I2C_TEST): print Passed, "#%d" % (i) else: print Failed, "#%d received %d, expected %d" % ( i, validOperations, self.test_params.I2C_TEST) self.test["F"] = False pass pass print return #################################################### def TrackingDataReadoutTest(self): txtTitle("G. Reading out tracking data") print " Sending triggers and testing if the Event Counter adds up." broadcastWrite(self.glib, self.gtx, "ContReg0", 0x36) self.test["G"] = True for i in self.presentVFAT2sSingle: t1_mode = 0 t1_type = 0 t1_n = self.test_params.TK_RD_TEST t1_interval = 400 resetLocalT1(self.glib, self.gtx) writeVFAT(self.glib, self.gtx, i, "ContReg0", 0x37) setVFATTrackingMask(self.glib, self.gtx, ~(0x1 << i)) flushTrackingFIFO(self.glib, self.gtx) nPackets = 0 timeOut = 0 ecs = [] sendL1A(self.glib, self.gtx, t1_interval, t1_n) while ((readFIFODepth(self.glib, self.gtx)["Occupancy"]) != 7 * self.test_params.TK_RD_TEST): timeOut += 1 if (timeOut == 10 * self.test_params.TK_RD_TEST): break pass while ((readFIFODepth(self.glib, self.gtx)["isEMPTY"]) != 1): packets = readTrackingInfo(self.glib, self.gtx) if (len(packets) == 0): print "read data packet length is 0" continue ec = int((0x00000ff0 & packets[0]) >> 4) nPackets += 1 ecs.append(ec) pass writeVFAT(self.glib, self.gtx, i, "ContReg0", 0x36) if (nPackets != self.test_params.TK_RD_TEST): print Failed, "#%d received %d, expected %d" % ( i, nPackets, self.test_params.TK_RD_TEST) if self.debug: raw_input("press enter to continue") pass else: followingECS = True for j in range(0, self.test_params.TK_RD_TEST - 1): if (ecs[j + 1] == 0 and ecs[j] == 255): pass elif (ecs[j + 1] - ecs[j] != 1): followingECS = False print "\033[91m > #%d previous %d, current %d \033[0m" % ( i, ecs[j], ecs[j + 1]) pass pass if (followingECS): print Passed, "#" + str(i) else: print Failed, "#%d received %d, expected %d, noncontinuous ECs" % ( i, nPackets, self.test_params.TK_RD_TEST) if self.debug: raw_input("press enter to continue") pass self.test["G"] = False pass pass pass print return #################################################### def SimultaneousTrackingDataReadoutTest(self): txtTitle("H. Reading out tracking data") print " Turning on all VFAT2s and looking that all the Event Counters add up." self.test["H"] = True if (self.test["G"]): broadcastWrite(self.glib, self.gtx, "ContReg0", 0x37) mask = 0 for i in self.presentVFAT2sSingle: mask |= (0x1 << i) pass setVFATTrackingMask(self.glib, self.gtx, ~(mask)) sendResync(self.glib, self.gtx, 10, 1) flushTrackingFIFO(self.glib, self.gtx) t1_mode = 0 t1_type = 0 t1_n = self.test_params.TK_RD_TEST t1_interval = 400 resetLocalT1(self.glib, self.gtx) nPackets = 0 timeOut = 0 ecs = [] sendL1A(self.glib, self.gtx, t1_interval, t1_n) while ((readFIFODepth(self.glib, self.gtx)["Occupancy"]) != len(self.presentVFAT2sSingle) * self.test_params.TK_RD_TEST): timeOut += 1 if (timeOut == 20 * self.test_params.TK_RD_TEST): break pass while ((readFIFODepth(self.glib, self.gtx)["isEMPTY"]) != 1): packets = readTrackingInfo(self.glib, self.gtx) ec = int((0x00000ff0 & packets[0]) >> 4) nPackets += 1 ecs.append(ec) pass broadcastWrite(self.glib, self.gtx, "ContReg0", 0x36) if (nPackets != len(self.presentVFAT2sSingle) * self.test_params.TK_RD_TEST): print Failed, "#%d received: %d, expected: %d" % ( i, nPackets, len(self.presentVFAT2sSingle) * self.test_params.TK_RD_TEST) else: followingECS = True for i in range(0, self.test_params.TK_RD_TEST - 1): for j in range(0, len(self.presentVFAT2sSingle) - 1): if (ecs[i * len(self.presentVFAT2sSingle) + j + 1] != ecs[i * len(self.presentVFAT2sSingle) + j]): print "\033[91m > #%d saw %d, %d saw %d \033[0m" % ( j + 1, ecs[i * len(self.presentVFAT2sSingle) + j + 1], j, ecs[i * len(self.presentVFAT2sSingle) + j]) followingECS = False pass pass if (ecs[(i + 1) * len(self.presentVFAT2sSingle)] == 0 and ecs[i * len(self.presentVFAT2sSingle)] == 255): pass elif (ecs[(i + 1) * len(self.presentVFAT2sSingle)] - ecs[i * len(self.presentVFAT2sSingle)] != 1): print "\033[91m > #%d previous %d, current %d \033[0m" % ( i, ecs[i * len(self.presentVFAT2sSingle)], ecs[(i + 1) * len(self.presentVFAT2sSingle)]) followingECS = False pass pass if (followingECS): print Passed else: print Failed self.test["H"] = False pass pass resetLocalT1(self.glib, self.gtx) pass
metavar="errorRate") parser.add_option("-u", "--user", action="store_true", dest="userOnly", help="print user information only", metavar="userOnly") (options, args) = parser.parse_args() links = {} for link in options.activeLinks: pair = map(int, link.split(",")) links[pair[0]] = pair[1] print "links", links uhal.setLogLevelTo(uhal.LogLevel.FATAL) uTCAslot = 175 if options.slot: uTCAslot = 160 + options.slot print options.slot, uTCAslot ipaddr = '192.168.0.%d' % (uTCAslot) address_table = "file://${BUILD_HOME}/data/glib_address_table.xml" uri = "chtcp-2.0://localhost:10203?target=%s:50001" % (ipaddr) glib = uhal.getDevice("glib", uri, address_table) ######################################## # IP address ######################################## print print "--=======================================--"
help="character to trigger capture " "- default: %(default)s") parser_cap.add_argument("--nwords", dest='ncapture', type=int, metavar='N', default=4, help="Number of words to capture from each link" "- default: 0x%(default)i") parser_cap.add_argument("--expected", metavar='pattern.txt', help="Pattern file with 1 word/line in hex") args = parser.parse_args() if args.verbose: logging.basicConfig(level=logging.INFO) uhal.setLogLevelTo(uhal.LogLevel.WARNING) else: uhal.setLogLevelTo(uhal.LogLevel.WARNING) logging.basicConfig(level=logging.WARNING) if not args.connection: args.connection = os.environ['CTP6_CONNECTION'] if not args.links: log.debug("Using all links") args.links = range(48) else: args.links = list(api.expand_links(args.links)) hw_connection = 'file://%s' % args.connection log.info("Setting up connection: %s", hw_connection)
def __init__(self, name, go=True, freq=100, odir="blah", vprech=38, vdd=38, dvdd=38): self._name = name self._go = go self._freq = freq self._odir = odir self._vprech = vprech self._vdd = vdd self._dvdd = dvdd self._manager = uhal.ConnectionManager("file://../data/vipram_connections.xml") self._hw = self._manager.getDevice("Mezz1") uhal.setLogLevelTo(uhal.LogLevel.ERROR) # self._hw.dispatch(); self._hw.getNode("VipMEM.VPRECH").write(vprech) self._hw.getNode("VipMEM.VDD").write(vdd) self._hw.getNode("VipMEM.DVDD").write(dvdd) # self._hw.dispatch(); self._ident = self._hw.getNode("VipMEM.Ident").read() self._vers = self._hw.getNode("VipMEM.FWver").read() self._VprechargeRead = self._hw.getNode("VipMEM.VPRECH").read() self._VprechargeMea = self._hw.getNode("VipMEM.V_VPRECH").read() self._VDDRead = self._hw.getNode("VipMEM.VDD").read() self._VDDMea = self._hw.getNode("VipMEM.V_VDD").read() self._DVDDRead = self._hw.getNode("VipMEM.DVDD").read() self._DVDDMea = self._hw.getNode("VipMEM.V_DVDD").read() self._hw.dispatch() print "Firmware identity = ", hex( self._ident ), ", firmware version = ", self._vers, ", Vpre bit = ", self._VprechargeRead, ", Vpre measured = ", self._VprechargeMea print "Vdd bit = ", self._VDDRead, ", Vdd measured = ", self._VDDMea, "Dvdd bit = ", self._DVDDRead, ", Dvdd measured = ", self._DVDDMea self._iSteps = 0 self._fSteps = 32 self._stepIncrement = 32 self._blockSize = 1024 ################### ## define registers self._registers = [] self._registers.append("CheckData") # CheckData for i in range(32 - 1, -1, -1): self._registers.append("Out" + str(i)) self._registers.append("ReqL0") self._registers.append("Miss2") self._registers.append("Miss1") self._registers.append("Miss0") self._registers.append("RunMode") self._registers.append("Primary") self._registers.append("Latch") self._registers.append("EvRearm") for i in range(7): self._registers.append("RA" + str(i)) for i in range(5): self._registers.append("CA" + str(i)) for i in range(1, 16): self._registers.append("A" + str(i)) self._registers.append("A0") for i in range(1, 16): self._registers.append("B" + str(i)) self._registers.append("B0") for i in range(1, 16): self._registers.append("C" + str(i)) self._registers.append("C0") for i in range(1, 16): self._registers.append("D" + str(i)) self._registers.append("D0") print "registers size = ", len(self._registers) ################### # power numbers self._i_dvdd = [] self._i_vdd = [] self._i_prech = [] self._difftimes = []
def gemsupervisor(request): global state global m_AMC13manager global m_AMCmanager global verbosity global m_filename global form global m_monitor global lt def updateStatus(): status = m_AMC13manager.device.getStatus() status.SetHTML() # Create pipe and dup2() the write end of it on top of stdout, saving a copy # of the old stdout out = OutputGrabber() out.start() status.Report(verbosity) out.stop() shtml = out.capturedtext with open("webdaq/templates/amc13status.html", "w") as text_file: text_file.write(shtml) with open("webdaq/templates/amcstatus.html", "w") as text_file: text_file.write(m_AMCmanager.getStatus(verbosity)) def parkData(): #call root converter call_command = os.getenv( 'BUILD_HOME') + '/gem-light-dqm/gemtreewriter/bin/' + os.getenv( 'XDAQ_OS') + '/' + os.getenv('XDAQ_PLATFORM') + '/unpacker' command_args = "/tmp/" + m_filename + ".dat sdram" call([call_command + ' ' + command_args], shell=True) #create dirs in tmp for i in range(24): call(["mkdir -p /tmp/dqm_hists/%s" % (i)], shell=True) call(["mkdir -p /tmp/dqm_hists/OtherData"], shell=True) call(["mkdir -p /tmp/dqm_hists/canvases"], shell=True) #call dqm call_command = os.getenv( 'BUILD_HOME') + '/gem-light-dqm/dqm-root/bin/' + os.getenv( 'XDAQ_OS') + '/' + os.getenv('XDAQ_PLATFORM') + '/dqm' command_args = "/tmp/" + m_filename + ".raw.root" os.system(call_command + ' ' + command_args) #call dqm printer call_command = os.getenv( 'BUILD_HOME') + '/gem-light-dqm/dqm-root/bin/' + os.getenv( 'XDAQ_OS') + '/' + os.getenv('XDAQ_PLATFORM') + '/gtprinter' command_args = "/tmp/" + m_filename + ".analyzed.root" os.system(call_command + ' ' + command_args) #copy results to DQM display form #call_command = "/home/mdalchen/work/ldqm-browser/LightDQM/LightDQM/test/" call_command = os.getenv('LDQM_STATIC') + '/' # call_command += m_filename[10:15] # call_command += "/" # call_command += m_filename[:9] # call_command += "/" # call_command += "TAMU/GEB-GTX0-Long/" call(["mkdir -p " + call_command], shell=True) call(["cp -r /tmp/" + m_filename + " " + call_command], shell=True) if request.POST: if 'configure' in request.POST: form = ConfigForm(request.POST) if form.is_valid(): amc13N = form.cleaned_data['amc13_choice'] amc_list = form.cleaned_data['amc_list'] amc_str = "" for amcN in amc_list: amc_str += str(amcN) + "," amc_str = amc_str[:-1] trigger_type = form.cleaned_data['trigger_type'] if trigger_type == '1': lt = True m_monitor = True else: lt = False m_monitor = False trigger_rate = int(form.cleaned_data['trigger_rate']) verbosity = int(form.cleaned_data['verbosity']) uhal.setLogLevelTo(uhal.LogLevel.ERROR) #configure GLIB. Currently supports only one GLIB try: m_AMC13manager.connect(str(amc13N), verbosity) m_AMC13manager.configureInputs(amc_str) m_AMC13manager.reset() for amcN in amc_list: m_AMCmanager.connect(int(amcN)) m_AMCmanager.reset() n_gtx = m_AMCmanager.activateGTX() print "N GTX links %s" % (n_gtx) # retrieve VFAT slot numberd and ChipIDs from HW for gtx in range(n_gtx): chipids = m_AMCmanager.getVFATs(gtx) # retrieve VFAT slot numberd and ChipIDs from DB vfats = VFAT.objects.all() # Check if the VFATs are in DB, add if not v_list = [] for chip in chipids.keys(): t_chipid = "0x%04x" % (chipids[chip]) if t_chipid in vfats.filter( Slot=chip).values_list("ChipID", flat=True): pass else: print "Adding VFAT(ChipID = %s, Slot = %d)" % ( t_chipid, chip) v = VFAT(ChipID=t_chipid, Slot=chip) v.save() v_list.append( VFAT.objects.get(ChipID=t_chipid, Slot=chip)) #t_chamberID = 'OHv2aM'#hard code now, read from HW later when available t_chamberID = 'GTX-' + str( gtx ) #use gtx link number now, read from HW later when available print "t_chamberID = %s" % (t_chamberID) g_list = [] gebs = GEB.objects.filter(ChamberID=t_chamberID) t_flag = False for geb in gebs: if v_list == list(geb.vfats.all()): t_flag = True g_list.append(geb) break if t_flag: pass else: print "Update DB" g = GEB(Type="Long", ChamberID=t_chamberID) g.save() for v in v_list: g.vfats.add(v) g_list.append(g) t_flag = False #t_boardID = "47-20120013"#hard code now, read from HW later when available t_boardID = "AMC-" + str( amcN ) #hard code now, read from HW later when available a_list = [] amcs = AMC.objects.filter(BoardID=t_boardID) for amc in amcs: if g_list == list(amc.gebs.all()): t_flag = True a_list.append(amc) if t_flag: pass else: print "Update DB" a = AMC(Type="GLIB", BoardID=t_boardID) a.save() for g in g_list: a.gebs.add(g) a_list.append(a) # create a new run. Some values are hard-coded for now runs = Run.objects.filter(Period="2016T", Type="bench", Station="TAMU") rns = list( int(x) for x in list(runs.values_list("Number", flat=True))) nrs = u'%s' % (max(rns) + 1) nrs = nrs.zfill(6) t_date = str(datetime.date.today()) m_filename = "run" + str( nrs) + "" + "_bench_TAMU_" + t_date newrun = Run(Name=m_filename, Type="bench", Number=str(nrs), Date=datetime.date.today(), Period="2016T", Station="TAMU") newrun.save() for a in a_list: newrun.amcs.add(a) m_AMC13manager.configureTrigger(lt, 2, 1, int(trigger_rate), 0) updateStatus() state = 'configured' except ValueError, e: print colors.YELLOW, e, colors.ENDC state = 'halted' elif 'halt' in request.POST: form = ConfigForm() m_AMC13manager.reset() state = 'halted' elif 'run' in request.POST: print "running" #form = ConfigForm() updateStatus() nevents = int(request.POST['nevents']) t = threading.Thread(target=m_AMC13manager.startDataTaking, args=["/tmp/" + m_filename + ".dat"]) t.start() state = 'running' elif 'stop' in request.POST: m_AMC13manager.stopDataTaking() updateStatus() sleep(1) t_p = threading.Thread(target=parkData) t_p.start() state = 'configured' elif "monitoring" in request.POST: updateStatus()
def main(): parser = argparse.ArgumentParser() parser.add_argument("command", choices=['reset', 'status', 'capture'], help="Action to perform") parser.add_argument("links", nargs='*', help="Specify links. " "If none are specified, reset all.") parser.add_argument("--connection", help="Manually connection XML file. " "If not specified, take from CTP6_CONNECTION env.") parser.add_argument("--verbose", action='store_true', help="Increase verbosity") parser_rst = parser.add_argument_group('reset') parser_stat = parser.add_argument_group('status') parser_cap = parser.add_argument_group('capture') # Reset arguments parser_rst.add_argument("--power-down", action='store_true', dest='power_down', help="Additionally power down the links") # Capture arguments parser_cap.add_argument("--orbit-capture-char", dest='capture_char', type=str, metavar='0xbc', default='0xbc', help="character to trigger capture " "- default: %(default)s") parser_cap.add_argument("--nwords", dest='ncapture', type=int, metavar='N', default=4, help="Number of words to capture from each link" "- default: 0x%(default)i") parser_cap.add_argument("--expected", metavar='pattern.txt', help="Pattern file with 1 word/line in hex") args = parser.parse_args() if args.verbose: logging.basicConfig(level=logging.INFO) uhal.setLogLevelTo(uhal.LogLevel.WARNING) else: uhal.setLogLevelTo(uhal.LogLevel.WARNING) logging.basicConfig(level=logging.WARNING) if not args.connection: args.connection = os.environ['CTP6_CONNECTION'] if not args.links: log.debug("Using all links") args.links = range(48) else: args.links = list(api.expand_links(args.links)) hw_connection = 'file://%s' % args.connection log.info("Setting up connection: %s", hw_connection) manager = uhal.ConnectionManager(hw_connection) hw = manager.getDevice('ctp6.frontend') commands = { 'reset': do_reset, 'status': do_status, 'capture': do_capture } commands[args.command](hw, args) log.info("done.") return 0
def __init__(self, dev_name, man_file, parsed_cfg): uhal.setLogLevelTo(uhal.LogLevel.NOTICE ) ## Get rid of initial flood of IPBUS messages self.isRunning = False section_name = "Producer.fmctlu" self.dev_name = dev_name #man_file= parsed_cfg.get(section_name, "ConnectionFile") self.manager = uhal.ConnectionManager(man_file) self.hw = self.manager.getDevice(self.dev_name) # #Get Verbose setting self.verbose = parsed_cfg.getint(section_name, "verbose") #self.nDUTs= 4 #Number of DUT connectors self.nDUTs = parsed_cfg.getint(section_name, "nDUTs") #self.nChannels= 6 #Number of trigger inputs self.nChannels = parsed_cfg.getint(section_name, "nTrgIn") #self.VrefInt= 2.5 #Internal DAC voltage reference self.VrefInt = parsed_cfg.getfloat(section_name, "VRefInt") #self.VrefExt= 1.3 #External DAC voltage reference self.VrefExt = parsed_cfg.getfloat(section_name, "VRefExt") #self.intRefOn= False #Internal reference is OFF by default self.intRefOn = int(parsed_cfg.get(section_name, "intRefOn")) self.fwVersion = self.hw.getNode("version").read() self.hw.dispatch() print "TLU V1E FIRMWARE VERSION= ", hex(self.fwVersion) # Instantiate a I2C core to configure components self.TLU_I2C = I2CCore(self.hw, 10, 5, "i2c_master", None) #self.TLU_I2C.state() enableCore = True #Only need to run this once, after power-up self.enableCore() ####### EEPROM AX3 testing doAtmel = False if doAtmel: self.ax3eeprom = ATSHA204A(self.TLU_I2C, 0x64) print "shiftR\tdatBit\tcrcBit\tcrcReg \n", self.ax3eeprom._CalculateCrc( [255, 12, 54, 28, 134, 89], 3) self.ax3eeprom._wake(True, True) print self.ax3eeprom._GetCommandPacketSize(8) #self.eepromAX3read() ####### EEPROM AX3 testing end # Instantiate clock chip and configure it (if necessary) #self.zeClock=si5345(self.TLU_I2C, 0x68) clk_addr = int(parsed_cfg.get(section_name, "I2C_CLK_Addr"), 16) self.zeClock = si5345(self.TLU_I2C, clk_addr) res = self.zeClock.getDeviceVersion() if (int(parsed_cfg.get(section_name, "CONFCLOCK"), 16)): #clkRegList= self.zeClock.parse_clk("./../../bitFiles/TLU_CLK_Config_v1e.txt") clkRegList = self.zeClock.parse_clk( parsed_cfg.get(section_name, "CLOCK_CFG_FILE")) self.zeClock.writeConfiguration(clkRegList, self.verbose) ###### self.zeClock.checkDesignID() # Instantiate DACs and configure them to use reference based on TLU setting #self.zeDAC1=AD5665R(self.TLU_I2C, 0x13) #self.zeDAC2=AD5665R(self.TLU_I2C, 0x1F) dac_addr1 = int(parsed_cfg.get(section_name, "I2C_DAC1_Addr"), 16) self.zeDAC1 = AD5665R(self.TLU_I2C, dac_addr1) dac_addr2 = int(parsed_cfg.get(section_name, "I2C_DAC2_Addr"), 16) self.zeDAC2 = AD5665R(self.TLU_I2C, dac_addr2) self.zeDAC1.setIntRef(self.intRefOn, self.verbose) self.zeDAC2.setIntRef(self.intRefOn, self.verbose) # Instantiate the serial line expanders and configure them to default values #self.IC6=PCA9539PW(self.TLU_I2C, 0x74) exp1_addr = int(parsed_cfg.get(section_name, "I2C_EXP1_Addr"), 16) self.IC6 = PCA9539PW(self.TLU_I2C, exp1_addr) self.IC6.setInvertReg(0, 0x00) # 0= normal, 1= inverted self.IC6.setIOReg(0, 0x00) # 0= output, 1= input self.IC6.setOutputs(0, 0xFF) # If output, set to XX self.IC6.setInvertReg(1, 0x00) # 0= normal, 1= inverted self.IC6.setIOReg(1, 0x00) # 0= output, 1= input self.IC6.setOutputs(1, 0xFF) # If output, set to XX #self.IC7=PCA9539PW(self.TLU_I2C, 0x75) exp2_addr = int(parsed_cfg.get(section_name, "I2C_EXP2_Addr"), 16) self.IC7 = PCA9539PW(self.TLU_I2C, exp2_addr) self.IC7.setInvertReg(0, 0x00) # 0= normal, 1= inverted self.IC7.setIOReg(0, 0x00) # 0= output, 1= input self.IC7.setOutputs(0, 0x00) # If output, set to XX self.IC7.setInvertReg(1, 0x00) # 0= normal, 1= inverted self.IC7.setIOReg(1, 0x00) # 0= output, 1= input self.IC7.setOutputs(1, 0xB0) # If output, set to XX #Instantiate Display self.DISP = CFA632(self.TLU_I2C, 0x2A) # #Instantiate Power/Led Module dac_addr_module = int( parsed_cfg.get(section_name, "I2C_DACModule_Addr"), 16) exp1_addr = int(parsed_cfg.get(section_name, "I2C_EXP1Module_Addr"), 16) exp2_addr = int(parsed_cfg.get(section_name, "I2C_EXP2Module_Addr"), 16) pmtCtrVMax = parsed_cfg.getfloat(section_name, "PMT_vCtrlMax") self.pwdled = PWRLED(self.TLU_I2C, dac_addr_module, pmtCtrVMax, exp1_addr, exp2_addr) #self.pwdled.setIndicatorRGB(1, [0, 0, 1]) #self.pwdled.setIndicatorRGB(2, [0, 0, 1]) #self.pwdled.setIndicatorRGB(3, [0, 0, 1]) #self.pwdled.setIndicatorRGB(4, [0, 0, 1]) #self.pwdled.setIndicatorRGB(5, [0, 0, 1]) #self.pwdled.setIndicatorRGB(6, [0, 0, 1]) #self.pwdled.setIndicatorRGB(7, [0, 0, 1]) #self.pwdled.setIndicatorRGB(8, [0, 0, 1]) #self.pwdled.setIndicatorRGB(9, [0, 0, 1]) #self.pwdled.setIndicatorRGB(10, [0, 0, 1]) #self.pwdled.setIndicatorRGB(11, [0, 0, 1]) self.pwdled.allGreen() time.sleep(0.1) self.pwdled.allBlue() time.sleep(0.1) self.pwdled.allBlack() time.sleep(0.1) #self.pwdled.kitt() time.sleep(0.1) #self.pwdled.allBlack() #self.pwdled.allRed() #time.sleep(0.1) self.pwdled.allWhite()
parser.add_option('-b', action='store_true', dest='noX', default=False, help='no X11 windows') parser.add_option('--go', action='store_true', dest='go', default=False, help='go!') parser.add_option('--reset', action='store_true', dest='reset', default=False, help='go!') (options, args) = parser.parse_args() ############################################ ############################################################ def randuint32(): return randint(0, 0xffffffff) if __name__ == '__main__': manager = uhal.ConnectionManager("file://../data/vipram_connections.xml") hw = manager.getDevice("Mezz1") uhal.setLogLevelTo( uhal.LogLevel.NOTICE ) reg0 = hw.getNode("VipMEM.V_DVDD").read() reg1 = hw.getNode("VipMEM.V_VDD").read() reg2 = hw.getNode("VipMEM.V_VPRECH").read() ireg0 = hw.getNode("VipMEM.I_DVDD").read() ireg1 = hw.getNode("VipMEM.I_VDD").read() ireg2 = hw.getNode("VipMEM.I_VPRECH").read() vccreg = hw.getNode("VipMEM.V_VCC3V3").read() tmpreg = hw.getNode("VipMEM.Temperature").read() ltcreg = hw.getNode("VipMEM.LTC2991").read() hw.dispatch();
(options, args) = parser.parse_args() ############################################ ############################################################ def randuint32(): return randint(0, 0xffffffff) if __name__ == '__main__': manager = uhal.ConnectionManager("file://../data/vipram_connections.xml") hw = manager.getDevice("Mezz1") uhal.setLogLevelTo(uhal.LogLevel.NOTICE) reg0 = hw.getNode("VipMEM.V_DVDD").read() reg1 = hw.getNode("VipMEM.V_VDD").read() reg2 = hw.getNode("VipMEM.V_VPRECH").read() ireg0 = hw.getNode("VipMEM.I_DVDD").read() ireg1 = hw.getNode("VipMEM.I_VDD").read() ireg2 = hw.getNode("VipMEM.I_VPRECH").read() vccreg = hw.getNode("VipMEM.V_VCC3V3").read() tmpreg = hw.getNode("VipMEM.Temperature").read() ltcreg = hw.getNode("VipMEM.LTC2991").read() hw.dispatch()
from optparse import OptionParser parser = OptionParser() parser.add_option("-s", "--slot", type="int", dest="slot", help="slot in uTCA crate", metavar="slot", default=4) parser.add_option("-o", "--links", type="string", dest="activeLinks", action='append', help="pair of connected optical links (GLIB,OH)", metavar="activeLinks", default=[]) (options, args) = parser.parse_args() links = {} for link in options.activeLinks: pair = map(int, link.split(",")) links[pair[0]] = pair[1] print "links", links uhal.setLogLevelTo( uhal.LogLevel.FATAL ) if not links.keys(): print "No optical links specified, exiting" exit(1) # Create window window = Window("Scan a VFAT2's threshold") # Get GLIB access glib = GLIB(options.slot,links) glib.setWindow(window) ######################################### # Introduction Window # #########################################
def get_amc_version(xml_config): uhal.setLogLevelTo(uhal.LogLevel.ERROR) #TODO: this is setting log level globally, which is not very nice... device = amc13.AMC13(xml_config) return (hex(device.read(device.Board.T1, 'STATUS.FIRMWARE_VERS')), hex(device.read(device.Board.T2, 'STATUS.FIRMWARE_VERS')))
def main(localSlavesYAML, remoteSlavesYAML, CMyaml, outputDir): #address table top node top = ET.Element("node", {"id": "top"}) #local slaves RecreateDir(outputDir + "address_table/modules") slavesFile = open(localSlavesYAML) slaves = yaml.load(slavesFile) for slave in slaves['UHAL_MODULES']: if "XML" in slaves['UHAL_MODULES'][slave]: for iFile in range(0, len(slaves['UHAL_MODULES'][slave]["XML"])): #copy XML files xmlFile = slaves['UHAL_MODULES'][slave]["XML"][iFile] try: shutil.copyfile(os.path.abspath(xmlFile), outputDir + xmlFile) except OSError: pass if iFile == 0: relPath = slaves['UHAL_MODULES'][slave]['XML'][iFile] relPath = relPath[relPath.find("module"):] slaves['UHAL_MODULES'][slave]['XML'][iFile] = relPath AddAddressTableNode(slave, slaves['UHAL_MODULES'][slave], top) remoteSlaves = list() #append CM.yaml remote slaves try: if type(CMyaml) == type(' '): CMFile = open(CMyaml) remotes = yaml.load(CMFile) if remotes: for remote in remotes: filename = "os/" + remote + "_slaves.yaml" remoteSlaves.append(filename) except IOError: pass #remote slaves (explicit) if type(remoteSlavesYAML) == type(list()): for CM in remoteSlavesYAML: remoteSlaves.append(CM) #go through all found remote slaves for CM in remoteSlaves: slavesFile = open(CM) slaves = yaml.load(slavesFile) nameCM = os.path.basename(CM)[0:os.path.basename(CM).find("_")] for slave in slaves['UHAL_MODULES']: if "XML" in slaves['UHAL_MODULES'][slave]: for iFile in range(0, len(slaves['UHAL_MODULES'][slave]["XML"])): #change the file path to be relative on the apollo relPath = slaves['UHAL_MODULES'][slave]['XML'][iFile] relPath = nameCM + "_" + relPath[relPath.find("module"):] slaves['UHAL_MODULES'][slave]['XML'][iFile] = relPath AddAddressTableNode(slave, slaves['UHAL_MODULES'][slave], top) #generate the final address table file BuildAddressTable(outputDir + "address_table/address_apollo.xml", top) #generate a connections file connFile = open(outputDir + "address_table/connections.xml", "w") connFile.write('<?xml version="1.0" encoding="UTF-8"?>\n') connFile.write('\n') connFile.write('<connections>\n') connFile.write( ' <!-- be sure to use the same file in both "uri" and "address_table" -->\n' ) connFile.write( ' <connection id="test.0" uri="uioaxi-1.0:///opt/address_table/address_apollo.xml" address_table="file:///opt/address_table/address_apollo.xml" />\n' ) connFile.write('</connections>\n') connFile.close() #check files uhal.setLogLevelTo(uhal.LogLevel.WARNING) try: device = uhal.getDevice( "dummy", "ipbusudp-1.3://localhost:12345", "file://" + outputDir + "address_table/address_apollo.xml") except Exception: raise Exception("File '%s' does not exist or has incorrect format" % outputDir + "address_table/address_apollo.xml")
#!/usr/bin/python import uhal import time import sys from I2CuHal import I2CCore from si5344 import si5344 uhal.setLogLevelTo(uhal.LogLevel.INFO) manager = uhal.ConnectionManager("file://connections.xml") hw = manager.getDevice(sys.argv[1]) hw.getNode("io.freq_ctr.ctrl.chan_sel").write(0) hw.getNode("io.freq_ctr.ctrl.en_crap_mode").write(0) hw.dispatch() time.sleep(2) fq = hw.getNode("io.freq_ctr.freq.count").read() fv = hw.getNode("io.freq_ctr.freq.valid").read() hw.dispatch() print "Freq:", int(fv), int(fq) * 119.20928 / 1000000 hw.getNode("daq.timing.csr.ctrl.en_ext_sync").write(0) f_stat = hw.getNode("csr.stat").read() hw.dispatch() print "csr.stat", hex(f_stat) f_ctrl = hw.getNode("csr.ctrl").read() hw.dispatch() print "csr.ctrl:", hex(f_ctrl)
def __init__(self, name, go=True, freq=100, odir="blah"): self._name = name self._go = go self._freq = freq self._odir = odir self._manager = uhal.ConnectionManager( "file://../data/vipram_connections.xml") self._hw = self._manager.getDevice("Mezz1") uhal.setLogLevelTo(uhal.LogLevel.ERROR) #self._hw.dispatch(); self._hw.getNode("VipMEM.VPRECH").write(38) self._hw.getNode("VipMEM.VDD").write(38) self._hw.getNode("VipMEM.DVDD").write(38) #self._hw.dispatch(); self._ident = self._hw.getNode("VipMEM.Ident").read() self._vers = self._hw.getNode("VipMEM.FWver").read() self._VprechargeRead = self._hw.getNode("VipMEM.VPRECH").read() self._VprechargeMea = self._hw.getNode("VipMEM.V_VPRECH").read() self._VDDRead = self._hw.getNode("VipMEM.VDD").read() self._VDDMea = self._hw.getNode("VipMEM.V_VDD").read() self._DVDDRead = self._hw.getNode("VipMEM.DVDD").read() self._DVDDMea = self._hw.getNode("VipMEM.V_DVDD").read() self._hw.dispatch() print "Firmware identity = ", hex( self._ident ), ", firmware version = ", self._vers, ", Vpre bit = ", self._VprechargeRead, ", Vpre measured = ", self._VprechargeMea print "Vdd bit = ", self._VDDRead, ", Vdd measured = ", self._VDDMea, "Dvdd bit = ", self._DVDDRead, ", Dvdd measured = ", self._DVDDMea self._iSteps = 0 self._fSteps = 32 self._stepIncrement = 32 self._blockSize = 1024 ################### ## define registers self._registers = [] self._registers.append('CheckData') # CheckData for i in range(32 - 1, -1, -1): self._registers.append('Out' + str(i)) self._registers.append('ReqL0') self._registers.append('Miss2') self._registers.append('Miss1') self._registers.append('Miss0') self._registers.append('RunMode') self._registers.append('Primary') self._registers.append('Latch') self._registers.append('EvRearm') for i in range(7): self._registers.append("RA" + str(i)) for i in range(5): self._registers.append("CA" + str(i)) for i in range(1, 16): self._registers.append("A" + str(i)) self._registers.append("A0") for i in range(1, 16): self._registers.append("B" + str(i)) self._registers.append("B0") for i in range(1, 16): self._registers.append("C" + str(i)) self._registers.append("C0") for i in range(1, 16): self._registers.append("D" + str(i)) self._registers.append("D0") print "registers size = ", len(self._registers) ################### # power numbers self._i_dvdd = [] self._i_vdd = [] self._i_prech = [] self._difftimes = []
def main(): parser = argparse.ArgumentParser() parser.add_argument("command", choices=['reset', 'status', 'capture'], help="Action to perform") parser.add_argument("links", nargs='*', help="Specify links. " "If none are specified, reset all.") parser.add_argument("--connection", help="Manually connection XML file. " "If not specified, take from CTP6_CONNECTION env.") parser.add_argument("--verbose", action='store_true', help="Increase verbosity") parser_rst = parser.add_argument_group('reset') parser_stat = parser.add_argument_group('status') parser_cap = parser.add_argument_group('capture') # Reset arguments parser_rst.add_argument("--power-down", action='store_true', dest='power_down', help="Additionally power down the links") # Capture arguments parser_cap.add_argument("--orbit-capture-char", dest='capture_char', type=str, metavar='0xbc', default='0xbc', help="character to trigger capture " "- default: %(default)s") parser_cap.add_argument("--nwords", dest='ncapture', type=int, metavar='N', default=4, help="Number of words to capture from each link" "- default: 0x%(default)i") parser_cap.add_argument("--expected", metavar='pattern.txt', help="Pattern file with 1 word/line in hex") args = parser.parse_args() if args.verbose: logging.basicConfig(level=logging.INFO) uhal.setLogLevelTo(uhal.LogLevel.WARNING) else: uhal.setLogLevelTo(uhal.LogLevel.WARNING) logging.basicConfig(level=logging.WARNING) if not args.connection: args.connection = os.environ['CTP6_CONNECTION'] if not args.links: log.debug("Using all links") args.links = range(48) else: args.links = list(api.expand_links(args.links)) hw_connection = 'file://%s' % args.connection log.info("Setting up connection: %s", hw_connection) manager = uhal.ConnectionManager(hw_connection) hw = manager.getDevice('ctp6.frontend') commands = {'reset': do_reset, 'status': do_status, 'capture': do_capture} commands[args.command](hw, args) log.info("done.") return 0
# 0 <= ret <= (2^32-1) val = randint(0, 4294967295) if len(bin(val).replace("0b", "")) > 32: #dirty check for me print hex(val) return val def get_lut_16bit_word(address): from random import randint # 0 <= ret <= (2^32-1) val = randint(0, 65535) if len(bin(val).replace("0b", "")) > 16: #dirty check for me print hex(val) return val opts, args = parse_options() uhal.setLogLevelTo(uhal.LogLevel.ERROR) hlp.initLogging(logging.DEBUG) cm = uhal.ConnectionManager(opts.connectionFile) board = cm.getDevice( opts.board ) # run a simple access test hlp.testAccess(board) v = board.getNode('ctrl.id').read() try: board.dispatch() except: import sys # print something here when if times out print 'MP7 access failed (name:',board.id(),'uri:',board.uri(),')'
class VFATSCurveTools: """ This set of tools provides functionality to produce S-Curve results for VFAT2 chips @author: Hugo DeWitt @modifiedby: Christine McClean Jared Sturdy - [email protected] (Adapted for uHAL) """ uhal.setLogLevelTo(uhal.LogLevel.FATAL) def __init__(self, glib, slot, gtx, scan_params, doLatency=False, debug=False): """ """ self.glib = glib self.slot = slot self.gtx = gtx self.scan_params = scan_params self.doLatency = doLatency self.THRESH_ABS = scan_params.THRESH_ABS self.THRESH_REL = scan_params.THRESH_REL self.THRESH_MIN = scan_params.THRESH_MIN self.THRESH_MAX = scan_params.THRESH_MAX self.LAT_ABS = scan_params.LAT_ABS self.LAT_MIN = scan_params.LAT_MIN self.LAT_MAX = scan_params.LAT_MAX self.N_EVENTS_THRESH = scan_params.N_EVENTS_THRESH self.N_EVENTS_LAT = scan_params.N_EVENTS_LAT self.N_EVENTS_SCURVE = scan_params.N_EVENTS_SCURVE self.N_EVENTS_TRIM = scan_params.N_EVENTS_TRIM self.VCAL_MIN = scan_params.VCAL_MIN self.VCAL_MAX = scan_params.VCAL_MAX self.MAX_TRIM_IT = scan_params.MAX_TRIM_IT self.CHAN_MIN = scan_params.CHAN_MIN self.CHAN_MAX = scan_params.CHAN_MAX self.DAC_DEF = scan_params.DAC_DEF self.T1_PARAMS_N = scan_params.T1_PARAMS_N self.T1_PARAMS_INTERVAL = scan_params.T1_PARAMS_INTERVAL self.T1_PARAMS_DELAY = scan_params.T1_PARAMS_DELAY self.debug = debug self.startTime = None self.subname = None self.f = None self.m = None self.z = None self.h = None self.g = None return def cleanup(self, debug=False): """ """ self.startTime = None self.subname = None self.f = None self.m = None self.z = None self.h = None self.g = None return def setupVFAT(self, vfat, debug=False): """ """ print "------------------------------------------------------" print "-------------- Testing VFAT2 position %2d -------------" % ( vfat) print "------------------------------------------------------" if vfat not in range(0, 24): print "Invalid VFAT specified %d is no in [0,23]" % (vfat) sys.exit(-1) pass self.TotVCal = {} self.TotVCal["0"] = [] self.TotVCal["16"] = [] self.TotVCal["31"] = [] self.TotFoundVCal = [] self.VCal_ref = {} self.VCal_ref["0"] = 0 self.VCal_ref["31"] = 0 self.VCal_ref["avg"] = 0 import datetime self.startTime = datetime.datetime.now().strftime("%d_%m_%Y_%Hh%M") chipID = getChipID(self.glib, self.gtx, vfat) self.subname = "AMC_%02d_OH_%02d_VFAT2_%d_ID_0x%04x" % ( self.slot, self.gtx, vfat, chipID) self.f = open("%s_Data_%s" % (self.startTime, self.subname), 'w') self.m = open( "%s_SCurve_by_channel_%s" % (self.startTime, self.subname), 'w') self.z = open("%s_Setting_%s" % (self.startTime, self.subname), 'w') self.h = open("%s_VCal_%s" % (self.startTime, self.subname), 'w') self.g = open("%s_TRIM_DAC_value_%s" % (self.startTime, self.subname), 'w') self.m.close() self.h.close() self.g.close() self.z.write("%s-%s\n" % (time.strftime("%Y/%m/%d"), time.strftime("%H:%M:%S"))) self.z.write("chip ID: 0x%04x\n" % (chipID)) # should make sure all chips are off first? writeAllVFATs(self.glib, self.gtx, reg="ContReg0", value=0x0, mask=0xff000000) setTriggerSource(self.glib, self.gtx, 1) biasVFAT(self.glib, self.gtx, vfat) self.z.write("ipreampin: 168\n") self.z.write("ipreampfeed: 80\n") self.z.write("ipreampout: 150\n") self.z.write("ishaper: 150\n") self.z.write("ishaperfeed: 100\n") self.z.write("icomp: 75\n") self.z.write("vthreshold2: 0\n") self.z.write("vthreshold1: 0\n") print sendL1ACalPulse(self.glib, self.gtx, self.T1_PARAMS_DELAY, self.T1_PARAMS_INTERVAL, self.T1_PARAMS_N) stopLocalT1(self.glib, self.gtx) self.z.write("DACs default value: %s\n" % (self.DAC_DEF)) for channel in range(self.CHAN_MIN, self.CHAN_MAX): ## old script had *all* channels set up to receive a pulse at this point, why? setChannelRegister(self.glib, self.gtx, vfat, channel, mask=0x0, pulse=0x0, trim=self.DAC_DEF) pass return def scanThresholdByVFAT(self, vfat, debug=False): """ """ configureScanModule(self.glib, self.gtx, SCAN_THRESH_TRIG, vfat, scanmin=self.THRESH_MIN, scanmax=self.THRESH_MAX, stepsize=1, numtrigs=self.N_EVENTS_THRESH, debug=debug) startScanModule(self.glib, self.gtx) if (debug): printScanConfiguration(self.glib, self.gtx) print "LocalT1Controller status %d" % (getLocalT1Status( self.glib, self.gtx)) pass data_threshold = getScanResults(self.glib, self.gtx, self.THRESH_MAX - self.THRESH_MIN, debug=debug) return data_threshold def scanLatencyByVFAT(self, vfat, debug=False): """ """ channel = 10 setChannelRegister(self.glib, self.gtx, vfat, channel, mask=0x0, pulse=0x1, trim=self.DAC_DEF) writeVFAT(self.glib, self.gtx, vfat, "VCal", 0xff) configureScanModule(self.glib, self.gtx, SCAN_LATENCY, vfat, scanmin=self.LAT_MIN, scanmax=self.LAT_MAX, stepsize=1, numtrigs=self.N_EVENTS_LAT, debug=debug) startScanModule(self.glib, self.gtx) if (debug): printScanConfiguration(self.glib, self.gtx) print "LocalT1Controller status %d" % (getLocalT1Status( self.glib, self.gtx)) pass data_latency = getScanResults(self.glib, self.gtx, self.LAT_MAX - self.LAT_MIN, debug=debug) setChannelRegister(self.glib, self.gtx, vfat, channel, mask=0x0, pulse=0x0, trim=self.DAC_DEF) writeVFAT(self.glib, self.gtx, vfat, "VCal", 0x0) return data_latency def scanVCalByVFAT(self, vfat, channel, trim, ntrigs, debug=False): """ """ setChannelRegister(self.glib, self.gtx, vfat, channel, mask=0x0, pulse=0x1, trim=trim) if debug: print "Channel %d register 0x%08x" % ( channel, getChannelRegister(self.glib, self.gtx, vfat, channel)) pass configureScanModule(self.glib, self.gtx, SCAN_VCAL, vfat, channel=channel, scanmin=self.VCAL_MIN, scanmax=self.VCAL_MAX, stepsize=1, numtrigs=ntrigs, debug=debug) startScanModule(self.glib, self.gtx) if (debug): printScanConfiguration(self.glib, self.gtx) print "LocalT1Controller status %d" % (getLocalT1Status( self.glib, self.gtx)) pass data_scurve = getScanResults(self.glib, self.gtx, self.VCAL_MAX - self.VCAL_MIN, debug=debug) setChannelRegister(self.glib, self.gtx, vfat, channel, mask=0x0, pulse=0x0, trim=trim, debug=True) if debug: print "Channel %d register 0x%08x" % ( channel, getChannelRegister(self.glib, self.gtx, vfat, channel)) pass return data_scurve def runAllChannels(self, vfat, debug=False): """ """ # for each channel, disable the cal pulse for channel in range(self.CHAN_MIN, self.CHAN_MAX): setChannelRegister(self.glib, self.gtx, vfat, channel, mask=0x0, pulse=0x0, trim=self.DAC_DEF) pass for channel in range(self.CHAN_MIN, self.CHAN_MAX): if self.debug and (channel > 10): continue self.scanChannel(vfat, channel, debug=debug) pass return def scanChannel(self, vfat, channel, debug=False): """ """ print "--------------------- Channel %03d ---------------------------" % ( channel) self.m = open( "%s_SCurve_by_channel_%s" % (self.startTime, self.subname), 'a') for trim in [0, 16, 31]: print "---------------- S-Curve data trimDAC %2d --------------------" % ( trim) data_scurve = self.scanVCalByVFAT(vfat, channel, trim, ntrigs=self.N_EVENTS_SCURVE, debug=debug) if (trim == 16): self.m.write("SCurve_%d\n" % (channel)) pass try: if debug: print "Length of returned data_scurve = %d" % ( len(data_scurve)) print "First data word: 0x%08x" % (data_scurve[0]) for d in range(0, len(data_scurve)): "%d ==> %3.4f" % ((data_scurve[d] & 0xff000000) >> 24, (data_scurve[d] & 0xffffff) / (1. * self.N_EVENTS_SCURVE)) pass pass passed = False for d in data_scurve: VCal = (d & 0xff000000) >> 24 Eff = (d & 0xffffff) / (1. * self.N_EVENTS_SCURVE) if self.debug: print "%d => %3.4f" % (VCal, Eff) pass if (Eff >= 0.48 and not passed): if not passed: print "%d => %3.4f" % (VCal, Eff) self.TotVCal["%s" % (trim)].append(VCal) pass passed = True if trim in [0, 31]: break # stop scanning for high and low trim values pass if (trim == 16): self.m.write( "%d\t%f\n" % (VCal, Eff)) # write to file for trim == 16 pass pass # if self.doQC3: # return except: ex = sys.exc_info()[0] print "Caught exception: %s" % (ex) print "Error while reading the data, they will be ignored" self.m.close() pass pass self.m.close() return def adjustTrims(self, vfat, debug=False): """ """ print print "------------------------ TrimDAC routine ------------------------" print self.h = open("%s_VCal_%s" % (self.startTime, self.subname), 'a') if debug: for trim in [0, 16, 31]: print "TotVCal[%d](length = %d) = %s" % ( trim, len(self.TotVCal["%d" % (trim)]), self.TotVCal["%d" % (trim)]) pass pass try: self.VCal_ref["0"] = sum(self.TotVCal["0"]) / len( self.TotVCal["0"]) print "VCal_ref[0] %d" % (self.VCal_ref["0"]) self.VCal_ref["31"] = sum(self.TotVCal["31"]) / len( self.TotVCal["31"]) print "VCal_ref[31] %d" % (self.VCal_ref["31"]) self.VCal_ref["avg"] = (self.VCal_ref["0"] + self.VCal_ref["31"]) / 2 print "VCal_ref[avg] %d" % (self.VCal_ref["avg"]) self.h.write("%s\n" % (self.TotVCal["0"])) self.h.write("%s\n" % (self.TotVCal["31"])) except: ex = sys.exc_info()[0] print "Caught exception: %s" % (ex) print "S-Curve did not work" self.h.close() # changed from self.f.close() return False self.g = open("%s_TRIM_DAC_value_%s" % (self.startTime, self.subname), 'a') for channel in range(self.CHAN_MIN, self.CHAN_MAX): if self.debug and (channel > 10): continue self.adjustChannelTrims(vfat, channel, debug) pass self.h.write("%s\n" % (self.TotFoundVCal)) # VCalList = [] ## where is this used??? # minVcal = 0 ## where is this used??? self.h.close() self.g.close() return True def adjustChannelTrims(self, vfat, channel, debug=False): """ """ TRIM_IT = 0 print "TrimDAC Channel%d" % (channel) trimDAC = 16 foundGood = False foundVCal = None # this was not properly scoped previosly, where do we want to initialize it? while (foundGood == False): data_trim = self.scanVCalByVFAT(vfat, channel, trimDAC, ntrigs=self.N_EVENTS_SCURVE, debug=debug) if debug: print "First data word: 0x%08x" % (data_trim[0]) pass try: for d in data_trim: VCal = (d & 0xff000000) >> 24 Eff = (d & 0xffffff) / (1. * self.N_EVENTS_SCURVE) if (Eff >= 0.48): print "%d => %3.4f" % (VCal, Eff) foundVCal = VCal break pass pass except: ex = sys.exc_info()[0] print "Caught exception: %s" % (ex) print "Error while reading the data, they will be ignored" continue if (foundVCal > self.VCal_ref["avg"] and TRIM_IT < self.MAX_TRIM_IT and trimDAC < 31): trimDAC += 1 TRIM_IT += 1 elif (foundVCal < self.VCal_ref["avg"] and TRIM_IT < self.MAX_TRIM_IT and trimDAC > 0): trimDAC -= 1 TRIM_IT += 1 else: self.g.write("%d\n" % (trimDAC)) self.TotFoundVCal.append(foundVCal) self.f.write("S_CURVE_%d\n" % (channel)) for d in data_trim: self.f.write("%d\t%f\n" % ((d & 0xff000000) >> 24, (d & 0xffffff) / (1. * self.N_EVENTS_TRIM))) pass break pass return def setAllTrims(self, vfat, debug=False): """ """ self.g = open("%s_TRIM_DAC_value_%s" % (self.startTime, self.subname), 'r') for channel in range(self.CHAN_MIN, self.CHAN_MAX): if self.debug and (channel > 10): continue trimDAC = (self.g.readline()).rstrip('\n') print "Setting channel %d trimDAC to %s" % (channel, trimDAC) setChannelRegister(self.glib, self.gtx, vfat, channel, mask=0x0, pulse=0x0, trim=int(trimDAC)) pass self.g.close() return ########################## Main routine per VFAT ###################### def runScanRoutine(self, vfat, debug=False): """ """ chipID = getChipID(self.glib, self.gtx, vfat) print "AMC%02d OH%02d VFAT%02d 0x%04x" % (self.slot, self.gtx, vfat, chipID) print ########################## Setup the VFAT ###################### print "Setup the VFAT" self.setupVFAT(vfat) ########################## Initial threshold scan ###################### print "Initial threshold scan" data_threshold = self.scanThresholdByVFAT(vfat, debug=debug) print "Length of returned data_threshold = %d" % (len(data_threshold)) threshold = 0 noise = 100 * (data_threshold[0] & 0xffffff) / (1. * self.N_EVENTS_THRESH) if debug: print "First data word: 0x%08x" % (data_threshold[0]) pass print "%d = %3.4f" % (((data_threshold[0] & 0xff000000) >> 24), noise) for d in range(1, len(data_threshold) - 1): noise = 100 * (data_threshold[d] & 0xffffff) / (1. * self.N_EVENTS_THRESH) lastnoise = 100 * (data_threshold[d - 1] & 0xffffff) / (1. * self.N_EVENTS_THRESH) nextnoise = 100 * (data_threshold[d + 1] & 0xffffff) / (1. * self.N_EVENTS_THRESH) passAbs = (noise) < self.THRESH_ABS passLastRel = (lastnoise - noise) < self.THRESH_REL passNextRel = abs(noise - nextnoise) < self.THRESH_REL print "%d = %3.4f" % (( (data_threshold[d] & 0xff000000) >> 24), noise) if passAbs and passLastRel and passNextRel: # why is the threshold set to the previous value? threshold = (data_threshold[d] >> 24) setVFATThreshold(self.glib, self.gtx, vfat, vt1=(threshold), vt2=0) print "Threshold set to: %d" % (threshold) self.f.write("Threshold set to: %d\n" % (threshold)) self.z.write("vthreshold1: %d\n" % (threshold)) break pass # self.z.close() if threshold == 0 or threshold == 255: print "ignored" for d in range(0, len(data_threshold)): self.f.write("%d\t%f\n" % ((data_threshold[d] & 0xff000000) >> 24, 100 * (data_threshold[d] & 0xffffff) / (1. * self.N_EVENTS_THRESH))) pass self.f.close() return for d in range(0, len(data_threshold)): self.f.write("%d\t%f\n" % ((data_threshold[d] & 0xff000000) >> 24, 100 * (data_threshold[d] & 0xffffff) / (1. * self.N_EVENTS_THRESH))) pass ##################Parts of the routine require the L1A+CalPulse ###################### startLocalT1(self.glib, self.gtx) ########################## Initial latency scan ###################### if self.doLatency: print "Initial latency scan" data_latency = self.scanLatencyByVFAT(vfat, debug=debug) print "Length of returned data_latency = %d" % (len(data_latency)) if not len(data_latency): print "data_latency is empty" return if debug: print "First data word: 0x%08x" % (data_latency[0]) pass eff = 100 * (data_latency[0] & 0xffffff) / (1. * self.N_EVENTS_LAT) print "%d = %3.4f" % (((data_latency[0] & 0xff000000) >> 24), eff) for d in range(1, len(data_latency) - 1): eff = 100 * (data_latency[d] & 0xffffff) / (1. * self.N_EVENTS_LAT) lasteff = 100 * (data_latency[d - 1] & 0xffffff) / (1. * self.N_EVENTS_LAT) nexteff = 100 * (data_latency[d + 1] & 0xffffff) / (1. * self.N_EVENTS_LAT) print "%d = %3.4f" % (( (data_latency[d] & 0xff000000) >> 24), eff) if (eff) > self.LAT_ABS and (nexteff) > self.LAT_ABS and ( lasteff) <= self.LAT_ABS: latency = (data_latency[d + 1] >> 24) writeVFAT(self.glib, self.gtx, vfat, "Latency", (latency)) print "Latency set to: %d" % (latency) self.f.write("Latency set to: %d\n" % (latency)) self.z.write("latency: %d\n" % (latency)) #if not debug: break #pass pass pass else: writeVFAT(self.glib, self.gtx, vfat, "Latency", (37)) print "Latency set to: %d" % (37) self.f.write("Latency set to: %d\n" % (37)) self.z.write("latency: %d\n" % (37)) pass self.z.close() ################## Run S-Curves on all channels ###################### print "Run S-Curves on all channels" self.runAllChannels(vfat, debug=debug) # if self.doQC3: # return ################## Adjust the trim for each channel ###################### print "Adjust the trim for each channel" if self.adjustTrims(vfat, debug=debug): ################# Set all the TrimDACs to the right value ################# print "Set all the TrimDACs to the right value" self.setAllTrims(vfat, debug=debug) pass ########################## Final threshold scan ###################### print "Final threshold scan" stopLocalT1(self.glib, self.gtx) self.f.write("second_threshold\n") data_threshold = self.scanThresholdByVFAT(vfat, debug=debug) if not len(data_threshold): print "data_threshold is empty" return if debug: print "First data word: 0x%08x" % (data_threshold[0]) pass for d in data_threshold: self.f.write("%d\t%f\n" % ((d & 0xff000000) >> 24, 100 * (d & 0xffffff) / (1. * self.N_EVENTS_THRESH))) pass ########################## Final latency scan ###################### if self.doLatency: print "Final latency scan" startLocalT1(self.glib, self.gtx) data_latency = self.scanLatencyByVFAT(vfat, debug=debug) print "Length of returned data_latency = %d" % (len(data_latency)) if not len(data_latency): print "data_latency is empty" return if debug: print "First data word: 0x%08x" % (data_latency[0]) pass eff = 100 * (data_latency[0] & 0xffffff) / (1. * self.N_EVENTS_LAT) print "%d = %3.4f" % (((data_latency[0] & 0xff000000) >> 24), eff) for d in range(1, len(data_latency) - 1): eff = 100 * (data_latency[d] & 0xffffff) / (1. * self.N_EVENTS_LAT) lasteff = 100 * (data_latency[d - 1] & 0xffffff) / (1. * self.N_EVENTS_LAT) nexteff = 100 * (data_latency[d + 1] & 0xffffff) / (1. * self.N_EVENTS_LAT) print "%d = %3.4f" % (( (data_latency[d] & 0xff000000) >> 24), eff) if (eff) > self.LAT_ABS and (nexteff) > self.LAT_ABS and ( lasteff) <= self.LAT_ABS: writeVFAT(self.glib, self.gtx, vfat, "Latency", (d + 1)) print "Latency set to: %d" % (d + 1) break pass pass else: pass self.f.close() self.cleanup() if debug: raw_input("enter to finish") pass ##################### Stop local T1 controller ###################### resetLocalT1(self.glib, self.gtx) return
def get_hw(self): uhal.setLogLevelTo(uhal.LogLevel.DEBUG) self.hw = uhal.getDevice("HappyDaq.udp.0", self.device_uri, self.address_table_uri) return self.hw
def gemsupervisor(request): global state global m_AMC13manager global m_AMCmanager global verbosity global m_filename global form global m_monitor global lt def updateStatus(): status = m_AMC13manager.device.getStatus() status.SetHTML() # Create pipe and dup2() the write end of it on top of stdout, saving a copy # of the old stdout out = OutputGrabber() out.start() status.Report(verbosity) out.stop() shtml = out.capturedtext with open("webdaq/templates/amc13status.html", "w") as text_file: text_file.write(shtml) with open("webdaq/templates/amcstatus.html", "w") as text_file: text_file.write(m_AMCmanager.getStatus(verbosity)) def parkData(): #call root converter call_command = os.getenv('BUILD_HOME')+'/gem-light-dqm/gemtreewriter/bin/'+os.getenv('XDAQ_OS')+'/'+os.getenv('XDAQ_PLATFORM')+'/unpacker' command_args = "/tmp/"+m_filename+".dat sdram" call([call_command+' '+command_args],shell=True) #create dirs in tmp for i in range (24): call(["mkdir -p /tmp/dqm_hists/%s"%(i)],shell=True) call(["mkdir -p /tmp/dqm_hists/OtherData"],shell=True) call(["mkdir -p /tmp/dqm_hists/canvases"],shell=True) #call dqm call_command = os.getenv('BUILD_HOME')+'/gem-light-dqm/dqm-root/bin/'+os.getenv('XDAQ_OS')+'/'+os.getenv('XDAQ_PLATFORM')+'/dqm' command_args = "/tmp/"+m_filename+".raw.root" os.system(call_command+' '+command_args) #call dqm printer call_command = os.getenv('BUILD_HOME')+'/gem-light-dqm/dqm-root/bin/'+os.getenv('XDAQ_OS')+'/'+os.getenv('XDAQ_PLATFORM')+'/gtprinter' command_args = "/tmp/"+m_filename+".analyzed.root" os.system(call_command+' '+command_args) #copy results to DQM display form #call_command = "/home/mdalchen/work/ldqm-browser/LightDQM/LightDQM/test/" call_command = os.getenv('LDQM_STATIC')+'/' # call_command += m_filename[10:15] # call_command += "/" # call_command += m_filename[:9] # call_command += "/" # call_command += "TAMU/GEB-GTX0-Long/" call(["mkdir -p "+call_command],shell=True) call(["cp -r /tmp/"+m_filename+" "+call_command],shell=True) if request.POST: if 'configure' in request.POST: form = ConfigForm(request.POST) if form.is_valid(): amc13N = form.cleaned_data['amc13_choice'] amc_list = form.cleaned_data['amc_list'] amc_str = "" for amcN in amc_list: amc_str += str(amcN) + "," amc_str = amc_str[:-1] trigger_type = form.cleaned_data['trigger_type'] if trigger_type == '1': lt=True m_monitor = True else: lt=False m_monitor = False trigger_rate = int(form.cleaned_data['trigger_rate']) verbosity = int(form.cleaned_data['verbosity']) uhal.setLogLevelTo(uhal.LogLevel.ERROR) #configure GLIB. Currently supports only one GLIB try: m_AMC13manager.connect(str(amc13N),verbosity) m_AMC13manager.configureInputs(amc_str) m_AMC13manager.reset() for amcN in amc_list: m_AMCmanager.connect(int(amcN)) m_AMCmanager.reset() n_gtx = m_AMCmanager.activateGTX() print "N GTX links %s" %(n_gtx) # retrieve VFAT slot numberd and ChipIDs from HW for gtx in range(n_gtx): chipids = m_AMCmanager.getVFATs(gtx) # retrieve VFAT slot numberd and ChipIDs from DB vfats = VFAT.objects.all() # Check if the VFATs are in DB, add if not v_list = [] for chip in chipids.keys(): t_chipid = "0x%04x"%(chipids[chip]) if t_chipid in vfats.filter(Slot=chip).values_list("ChipID", flat=True): pass else: print "Adding VFAT(ChipID = %s, Slot = %d)"%(t_chipid,chip) v = VFAT(ChipID = t_chipid, Slot = chip) v.save() v_list.append(VFAT.objects.get(ChipID = t_chipid, Slot = chip)) #t_chamberID = 'OHv2aM'#hard code now, read from HW later when available t_chamberID = 'GTX-'+str(gtx) #use gtx link number now, read from HW later when available print "t_chamberID = %s" %(t_chamberID) g_list = [] gebs = GEB.objects.filter(ChamberID=t_chamberID) t_flag = False for geb in gebs: if v_list == list(geb.vfats.all()): t_flag = True g_list.append(geb) break if t_flag: pass else: print "Update DB" g = GEB(Type="Long",ChamberID = t_chamberID) g.save() for v in v_list: g.vfats.add(v) g_list.append(g) t_flag = False #t_boardID = "47-20120013"#hard code now, read from HW later when available t_boardID = "AMC-"+str(amcN)#hard code now, read from HW later when available a_list = [] amcs = AMC.objects.filter(BoardID = t_boardID) for amc in amcs: if g_list == list(amc.gebs.all()): t_flag = True a_list.append(amc) if t_flag: pass else: print "Update DB" a = AMC(Type="GLIB",BoardID = t_boardID) a.save() for g in g_list: a.gebs.add(g) a_list.append(a) # create a new run. Some values are hard-coded for now runs = Run.objects.filter(Period = "2016T", Type = "bench", Station = "TAMU") rns = list(int(x) for x in list(runs.values_list("Number", flat=True))) nrs = u'%s'%(max(rns)+1) nrs = nrs.zfill(6) t_date = str(datetime.date.today()) m_filename = "run"+str(nrs)+""+"_bench_TAMU_"+t_date newrun = Run(Name=m_filename, Type = "bench", Number = str(nrs), Date = datetime.date.today(), Period = "2016T", Station = "TAMU") newrun.save() for a in a_list: newrun.amcs.add(a) m_AMC13manager.configureTrigger(lt,2,1,int(trigger_rate),0) updateStatus() state = 'configured' except ValueError,e: print colors.YELLOW,e,colors.ENDC state = 'halted' elif 'halt' in request.POST: form = ConfigForm() m_AMC13manager.reset() state = 'halted' elif 'run' in request.POST: print "running" #form = ConfigForm() updateStatus() nevents = int(request.POST['nevents']) t = threading.Thread(target = m_AMC13manager.startDataTaking, args = ["/tmp/"+m_filename+".dat"]) t.start() state = 'running' elif 'stop' in request.POST: m_AMC13manager.stopDataTaking() updateStatus() sleep(1) t_p = threading.Thread(target = parkData) t_p.start() state = 'configured' elif "monitoring" in request.POST: updateStatus()
#!/usr/bin/python # This script resets the board from __future__ import print_function import uhal import time import sys import collections uhal.setLogLevelTo(uhal.LogLevel.ERROR) manager = uhal.ConnectionManager("file://connections.xml") board = manager.getDevice(sys.argv[1]) board.getClient().setTimeoutPeriod(10000) v = board.getNode("csr.id").read() board.dispatch() print("Board ID:", hex(v)) board.getNode("daq.timing.csr.ctrl.rst").write(1) # Hold clk40 domain in reset board.dispatch() board.getNode("csr.ctrl.soft_rst").write(1) # Reset ipbus registers board.dispatch()
def main(): # configure logger global log log = logging.getLogger("main") formatter = logging.Formatter('%(name)s %(levelname)s: %(message)s') handler = logging.StreamHandler(sys.stdout) handler.setFormatter(formatter) log.addHandler(handler) log.setLevel(logging.WARNING) #tell uHAL to calm down. uhal.setLogLevelTo(uhal.LogLevel.WARNING) #command line parser = argparse.ArgumentParser( description="Create auto-generated files for the build system.") parser.add_argument("--slavesFile", "-s", help="YAML file storing the slave info for generation", required=True) parser.add_argument("--addSlaveTCLPath", "-t", help="Path for AddSlaves.tcl", required=True) parser.add_argument("--addressTablePath", "-a", help="Path for address table generation yaml", required=True) parser.add_argument("--dtsiPath", "-d", help="Path for dtsi yaml", required=True) args = parser.parse_args() #AddSlaves tcl file tclFile = open(args.addSlaveTCLPath + "/AddSlaves.tcl", "w") tclFile.write( "#================================================================================\n" ) tclFile.write("# Configure and add AXI slaves\n") tclFile.write("# Auto-generated by \n") tclFile.write( "#================================================================================\n" ) #dtsi yaml file dtsiYAMLFile = open(args.dtsiPath + "/slaves.yaml", "w") dtsiYAML = dict() #address table yaml file addressTableYAMLFile = open(args.addressTablePath + "/slaves.yaml", "w") aTableYAML = dict() #source slave yaml to drive the rest of the build slavesFile = open(args.slavesFile) slaves = yaml.load(slavesFile) for slave in slaves['AXI_SLAVES']: #update all the files for this slave LoadSlave(slave, slaves["AXI_SLAVES"][slave], tclFile, dtsiYAML, aTableYAML, "") dtsiYAML = {"DTSI_CHUNKS": dtsiYAML} aTableYAML = {"UHAL_MODULES": aTableYAML} dtsiYAMLFile.write( yaml.dump(dtsiYAML, Dumper=MyDumper, default_flow_style=False)) addressTableYAMLFile.write( yaml.dump(aTableYAML, Dumper=MyDumper, default_flow_style=False))
###################################################################### if __name__ == '__main__': if len(sys.argv) < 3: print "Please specify the device IP address" \ " and the top-level address table file to use" sys.exit(1) device_ip = sys.argv[1] device_uri = "ipbusudp-2.0://" + device_ip + ":50001" address_table_name = sys.argv[2] address_table_uri = "file://" + address_table_name uhal.setLogLevelTo(uhal.LogLevel.WARNING) hw = uhal.getDevice("dummy", device_uri, address_table_uri) reg_name_base = "sysmon." regs = ["temp", "vccint", "vccaux", "vrefp", "vrefn", "vccbram"] max_len = max([len(i) for i in regs]) print "IPBus SysMon/XADC demo:" for reg_name_spec in regs: reg_name = reg_name_base + reg_name_spec node = hw.getNode(reg_name) val_raw = node.read() hw.dispatch() # NOTE: Yes, flexible but ugly. val = val_raw.value()
def __init__(self, dev_name, man_file): uhal.setLogLevelTo(uhal.LogLevel.NOTICE ) ## Get rid of initial flood of IPBUS messages self.dev_name = dev_name self.manager = uhal.ConnectionManager(man_file) self.hw = self.manager.getDevice(self.dev_name) #self.fwVersion = self.hw.getNode("version").read() #self.hw.dispatch() #print "--", self.dev_name, "FIRMWARE VERSION= " , hex(self.fwVersion) # Instantiate a I2C core to configure components #self.i2c_master= I2CCore(self.hw, 10, 5, "i2c_master", None) self.i2c_master = I2CCore(self.hw, 10, 5, "io.i2c", None) # Instantiate a secondary I2C core for SFP cage (not working yet) #self.i2c_secondary= I2CCore(self.hw, 10, 5, "io.usfp_i2c", None) # Enable the I2C interface on enclustra enableCore = True #Only need to run this once, after power-up self._enableCore() # Instantiate EEPROM self.zeEEPROM = E24AA025E48T(self.i2c_master, 0x57) # Instantiate clock chip self.zeClock = si5345(self.i2c_master, 0x68) res = self.zeClock.getDeviceVersion() self.zeClock.checkDesignID() # Instantiate expander for the equalizers (IC28) self.exp_EQ = PCA9539PW(self.i2c_master, 0x74) self.exp_EQ.setInvertReg(0, 0x00) # 0= normal self.exp_EQ.setIOReg(0, 0x00) # 0= output <<<<<<<<<<<<<<<<<<< self.exp_EQ.setInvertReg(1, 0x00) # 0= normal self.exp_EQ.setIOReg(1, 0x00) # 0= output <<<<<<<<<<<<<<<<<<< # Instantiate expander for SFP signals (IC29) self.exp_SFP = PCA9539PW(self.i2c_master, 0x75) self.exp_SFP.setInvertReg(0, 0x00) # 0= normal self.exp_SFP.setIOReg(0, 0x00) # 0= output <<<<<<<<<<<<<<<<<<< self.exp_SFP.setInvertReg(1, 0x00) # 0= normal self.exp_SFP.setIOReg(1, 0xFF) # FF= input <<<<<<<<<<<<<<<<<<< # Instantiate expander for LED control (IC27) self.exp_LED = PCA9539PW(self.i2c_master, 0x76) self.exp_LED.setInvertReg(0, 0x00) # 0= normal self.exp_LED.setIOReg(0, 0x00) # 0= output (LED) <<<<<<<<<<<<<<<<<<< self.exp_LED.setInvertReg(1, 0x00) # 0= normal self.exp_LED.setIOReg(1, 0x00) # 0= output <<<<<<<<<<<<<<<<<<< # Instantiate I2C multiplexer self.mux_I2C = PCA9548ADW(self.i2c_master, 0x73) # Instantiate a generic SFP transceiver for one of the 8 downstream self.SFP_ds = SFPI2C(self.i2c_master, 0x50) # Instantiate CDR for upstream and multiplexer self.cdr_UPS = ADN2814ACPZ(self.i2c_master, 0x40) self.cdr_MUX = ADN2814ACPZ(self.i2c_master, 0x60) #Instantiate Display doDisplaytest = False if doDisplaytest: self.DISP = LCD09052(self.i2c_master, 0x3A) #3A self.DISP.clear() self.DISP.test()