def write_files(): fwrC = rogue.utilities.fileio.StreamWriter() fwrC.setBufferSize(BufferSize) fwrC.setMaxSize(MaxSize) fwrU = rogue.utilities.fileio.StreamWriter() fwrU.setBufferSize(BufferSize) fwrU.setMaxSize(MaxSize) prbs = rogue.utilities.Prbs() comp = rogue.utilities.StreamZip() pyrogue.streamConnect(prbs,fwrU.getChannel(0)) pyrogue.streamTap(prbs,comp) pyrogue.streamConnect(comp,fwrC.getChannel(0)) fwrC.open("compressed.dat") fwrU.open("uncompressed.dat") print("Writing data files") for _ in range(FrameCount): prbs.genFrame(FrameSize) time.sleep(5) fwrC.close() fwrU.close()
def fifo_path(): # PRBS prbsTx = rogue.utilities.Prbs() prbsRx = rogue.utilities.Prbs() # FIFO fifo = rogue.interfaces.stream.Fifo(0,0,False); # Client stream pyrogue.streamConnect(prbsTx,fifo) # Server stream pyrogue.streamConnect(fifo,prbsRx) print("Generating Frames") for _ in range(FrameCount): prbsTx.genFrame(FrameSize) time.sleep(30) if prbsRx.getRxErrors() != 0: raise AssertionError('PRBS Frame errors detected! Errors = {}'.format(prbsRx.getRxErrors())) if prbsRx.getRxCount() != FrameCount: raise AssertionError('Frame count error. Got = {} expected = {}'.format(prbsRx.getRxCount(),FrameCount)) print("Done testing")
def __init__(self): pyrogue.Root.__init__(self, name='dummyTree', description="Dummy tree for example") # Use a memory space emulator sim = pyrogue.interfaces.simulation.MemEmulate() # Add Device self.add(surf.axi.AxiVersion(memBase=sim, offset=0x0)) # File writer example self.add(pyrogue.DataWriter()) self.add(pyrogue.RunControl()) self.test = TestClass() pyrogue.streamConnect(self, self.test) # Start the tree with pyrogue server, internal nameserver, default interface # Set pyroHost to the address of a network interface to specify which nework to run on # set pyroNs to the address of a standalone nameserver (startPyrorNs.py) self.start(timeout=2.0, pyroGroup='testGroup', pyroAddr="127.0.0.1", pyroNsAddr=None)
def data_path(): # Bridge server serv = rogue.interfaces.stream.TcpServer("127.0.0.1",9000) # Bridge client client = rogue.interfaces.stream.TcpClient("127.0.0.1",9000) # PRBS prbsTx = rogue.utilities.Prbs() prbsRx = rogue.utilities.Prbs() # Client stream pyrogue.streamConnect(prbsTx,serv) # Server stream pyrogue.streamConnect(client,prbsRx) time.sleep(5) print("Generating Frames") for _ in range(FrameCount): prbsTx.genFrame(FrameSize) time.sleep(20) if prbsRx.getRxCount() != FrameCount: raise AssertionError('Frame count error. Got = {} expected = {}'.format(prbsRx.getRxCount(),FrameCount)) if prbsRx.getRxErrors() != 0: raise AssertionError('PRBS Frame errors detected! Errors = {}'.format(prbsRx.getRxErrors())) print("Done testing")
def __init__(self, ip_addr, port): super().__init__() # Create a Rogue UDP client. self._udp_receiver = rogue.protocols.udp.Client(ip_addr, port, True) # Create a KeepAlive object and connect it to the UDP client. self._keep_alive = KeepAlive() pyrogue.streamConnect(self._keep_alive, self._udp_receiver) # Start the KeepAlive thread self._keep_alive.start()
def __init__(self): pyrogue.Root.__init__(self,name='evalBoard',description='Evaluation Board') # File writer dataWriter = pyrogue.utilities.fileio.StreamWriter(name='dataWriter') self.add(dataWriter) # Create the PGP interfaces udp = pyrogue.protocols.UdpRssiPack(host='192.168.2.194',port=8192,size=1400) # Create and Connect SRP to VC0 srp = rogue.protocols.srp.SrpV3() pyrogue.streamConnectBiDir(srp,udp.application(0)) # Add configuration stream to file as channel 0 pyrogue.streamConnect(self,dataWriter.getChannel(0x0)) pyrogue.streamConnect(udp.application(1),dataWriter.getChannel(0x1)) # PRBS Receiver as secdonary receiver for VC1 #prbsRx = pyrogue.utilities.prbs.PrbsRx('prbsRx') #pyrogue.streamTap(udp.application(1),prbsRx) #self.add(prbsRx) # Add Devices self.add(surf.axi.AxiVersion(memBase=srp,offset=0x0,expand=False)) #self.add(surf.protocols.ssi.SsiPrbsTx(memBase=srp,offset=0x40000)) self.add(pyrogue.LocalVariable(name='list',value=([0] * 10))) self.smem = pyrogue.smem.SMemControl(group='rogueTest',root=self) # Run control self.add(pyrogue.RunControl(name='runControl' , rates={1:'1 Hz', 10:'10 Hz',30:'30 Hz'})) #cmd=self.SsiPrbsTx.oneShot())) # Export remote objects #self.start(pollEn=True,pyroGroup='rogueTest',pyroHost='134.79.229.11',pyroNs='134.79.229.11') #self.start(pollEn=True,pyroGroup='rogueTest',pyroHost='134.79.229.11') #self.start(pollEn=True,pyroGroup='rogueTest') self.start(pollEn=True,pyroGroup='rogueTest') # Create epics node pvMap = {'evalBoard.AxiVersion.UpTimeCnt':'testCnt', 'evalBoard.AxiVersion.ScratchPad':'testPad'} pvMap = None # Comment out to enable map self.epics = pyrogue.epics.EpicsCaServer(base='rogueTest',root=self,pvMap=pvMap) self.epics.start() self.mysql = pyrogue.mysql.MysqlGw(dbHost='localhost',dbName='rogue',dbUser='******',dbPass='******',root=self) self.mysql.start()
def main(arg): # Create the objects fileReader = rogue.utilities.fileio.StreamReader() eventReader = EventReader() # Connect the fileReader to our event processor pyrogue.streamConnect(fileReader,eventReader) # Open the data file fileReader.open(arg) time.sleep(1)
def __init__(self, serial=None, **kwargs): super().__init__(**kwargs) if serial is not None: # Attach the serial devices self._rx = clink.ClinkSerialRx() pr.streamConnect(serial, self._rx) self._tx = clink.ClinkSerialTx() pr.streamConnect(self._tx, serial) @self.command(value='', name='SendString', description='Send a command string') def sendString(arg): if self._tx is not None: self._tx.sendString(arg)
def init_hardware(self, session, params=None): self.base = pr.Root(name='AMCc', description='') self.base.add(FpgaTopLevel( simGui = self.args["simGui"], commType = self.args['commType'], ipAddr = self.args['ipAddr'], pcieRssiLink = (int(self.args['slot']) - 2) )) streamDataWriter = pr.utilities.fileio.StreamWriter(name="streamDataWriter") self.base.add(streamDataWriter) pr.streamConnect(self.base.FpgaTopLevel.stream.application(0xC1), self.base.streamDataWriter.getChannel(0)) self.base.start(pollEn = self.args['pollEn']) return True, "Hardware Initialized"
def __init__(self, **kwargs): pyrogue.Root.__init__(self, name="AMCc", initRead=True, pollEn=True, **kwargs) # Use the StreamDataSource as a data source self._streaming_stream = pysmurf.core.emulators.StreamDataSource() self.add(self._streaming_stream) # Add a frame statistics module to count the number of generated frames self._smurf_frame_stats = pysmurf.core.counters.FrameStatistics( name="FrameRxStats") self.add(self._smurf_frame_stats) # Add the SmurfProcessor # The SmurfProcessor needs con container 'TimerWithStats' objects in it # in order to get output profile data. self._smurf_processor = smurf.core.processors.SmurfProcessor() # Configure the SmurfProcessor self._smurf_processor.setMask([0] * 2000) self._smurf_processor.setOrder(4) self._smurf_processor.setA( [1.0, -3.74145562, 5.25726624, -3.28776591, 0.77203984] + [0] * 11, ) self._smurf_processor.setB([ 5.28396689e-06, 2.11358676e-05, 3.17038014e-05, 2.11358676e-05, 5.28396689e-06 ] + [0] * 11) #self._smurf_processor.setUnwrapperDisable(True); print(f"Number of channels = {self._smurf_processor.getNumCh()}") print(f"Filter order = {self._smurf_processor.getOrder()}") print(f"Filter gain = {self._smurf_processor.getGain()}") print(f"Filter A = {self._smurf_processor.getA()}") print(f"Filter B = {self._smurf_processor.getB()}") # Connect the StreamDataSource data source to the FrameRxStats # and the FrameRxStats to the SmurfProcessor pyrogue.streamConnect(self._streaming_stream, self._smurf_frame_stats) pyrogue.streamConnect(self._smurf_frame_stats, self._smurf_processor)
def read_files(): frdC = rogue.utilities.fileio.StreamReader() frdU = rogue.utilities.fileio.StreamReader() prbsC = rogue.utilities.Prbs() prbsU = rogue.utilities.Prbs() comp = rogue.utilities.StreamUnZip() pyrogue.streamConnect(frdU,prbsU) pyrogue.streamConnect(frdC,comp) pyrogue.streamConnect(comp,prbsC) frdU.open("uncompressed.dat.1") frdC.open("compressed.dat.1") print("Reading data files") frdU.closeWait() frdC.closeWait() if prbsU.getRxCount() != FrameCount: raise AssertionError('Read uncompressed error. Incorrect number of frames read. Got = {} expected = {}'.format(prbsU.getRxCount(),FrameCount)) if prbsU.getRxErrors() != 0: raise AssertionError('Read uncompressed error. PRBS Frame errors detected!') if prbsC.getRxCount() != FrameCount: raise AssertionError('Read compressed error. Incorrect number of frames read. Got = {} expected = {}'.format(prbsC.getRxCount(),FrameCount)) if prbsC.getRxErrors() != 0: raise AssertionError('Read compressed error. PRBS Frame errors detected!')
def __init__(self, **kwargs): pyrogue.Root.__init__(self, name="AMCc", initRead=True, pollEn=True, **kwargs) # Use the DataFromFile as a stream data source self._streaming_stream = pysmurf.core.emulators.DataFromFile() self.add(self._streaming_stream) # Add the SmurfProcessor, using the DataToFile transmitter # to write the results to a text file self._smurf_processor = pysmurf.core.devices.SmurfProcessor( name="SmurfProcessor", description="Process the SMuRF Streaming Data Stream", root=self, txDevice=pysmurf.core.transmitters.DataToFile()) self.add(self._smurf_processor) # Connect the DataFromFile data source to the SmurfProcessor pyrogue.streamConnect(self._streaming_stream, self._smurf_processor)
def main(binFileName, verbose=False, pklFileName='', rootFileName=''): fileReader = rogue.utilities.fileio.StreamReader() eventReader = EventReader() pyrogue.streamConnect(fileReader, eventReader) fileReader.open(binFileName) time.sleep(5) nhits = [0, 0, 0] events = eventReader._getEvents() # write condensed data first before processing if len(pklFileName) > 0: pickle.dump(events, open(pklFileName, 'wb'), pickle.HIGHEST_PROTOCOL) for event in events: for i_asic in range(3): nhits[i_asic] += event._getCondensedData()._getNhits()[i_asic] print("Filename = %s" % binFileName) print("No. events = %d" % len(events)) print("Total hits = %d,%d,%d" % (nhits[0], nhits[1], nhits[2])) print("Avg hits per event = %.3f,%.3f,%.3f" % (nhits[0] / len(events), nhits[1] / len(events), nhits[2] / len(events))) if verbose or (len(rootFileName) > 0): summary_hists = generate_summary_histograms(events) if len(rootFileName) > 0: rootFile = ROOT.TFile(rootFileName, "RECREATE") rootFile.cd() for histDict in summary_hists: histDict["pixelMap"].Write() histDict["isValidData"].Write() histDict["isMultiHit"].Write()
def __init__(self, name="MyRoot", description="my root container", **kwargs): super().__init__(name=name, description=description, **kwargs) # Setup the TCP sockets connections self.srv = rogue.interfaces.stream.TcpClient('localhost', 9000) self.clt = rogue.interfaces.stream.TcpClient('localhost', 9002) # Out of order module on client side self.srvToClt = RssiOutOfOrder(period=2) self.cltToSrv = RssiOutOfOrder(period=1) # Insert out of order from server to client pyrogue.streamConnect(self.srv, self.srvToClt) pyrogue.streamConnect(self.srvToClt, self.clt) # Insert out of order from client to server pyrogue.streamConnect(self.clt, self.cltToSrv) pyrogue.streamConnect(self.cltToSrv, self.srv)
def __init__(self, *, sendCount=False, width=None, taps=None, stream=None, **kwargs): pyrogue.Device.__init__(self, description='PRBS Software Transmitter', **kwargs) self._prbs = rogue.utilities.Prbs() if width is not None: self._prbs.setWidth(width) if taps is not None: self._prbs.setTaps(taps) if stream is not None: pyrogue.streamConnect(self, stream) self._prbs.sendCount(sendCount) self.add( pyrogue.LocalVariable(name='txSize', description='PRBS Frame Size', units='Bytes', localSet=self._txSize, mode='RW', value=1024, typeStr='UInt32')) self.add( pyrogue.LocalVariable(name='txEnable', description='PRBS Run Enable', mode='RW', value=False, localSet=self._txEnable)) self.add( pyrogue.LocalCommand(name='genFrame', description='Generate n frames', value=1, function=self._genFrame)) self.add( pyrogue.LocalVariable(name='txErrors', description='TX Error Count', mode='RO', pollInterval=1, value=0, typeStr='UInt32', localGet=self._prbs.getTxErrors)) self.add( pyrogue.LocalVariable(name='txCount', description='TX Count', mode='RO', pollInterval=1, value=0, typeStr='UInt32', localGet=self._prbs.getTxCount)) self.add( pyrogue.LocalVariable(name='txBytes', description='TX Bytes', mode='RO', pollInterval=1, value=0, typeStr='UInt32', localGet=self._prbs.getTxBytes)) self.add( pyrogue.LocalVariable(name='genPayload', description='Payload Generate Enable', mode='RW', value=True, localSet=self._plEnable)) self.add( pyrogue.LocalVariable(name='txRate', description='TX Rate', disp="{:.3e}", mode='RO', pollInterval=1, value=0.0, units='Frames/s', localGet=self._prbs.getTxRate)) self.add( pyrogue.LocalVariable(name='txBw', description='TX BW', disp="{:.3e}", mode='RO', pollInterval=1, value=0.0, units='Bytes/s', localGet=self._prbs.getTxBw))
def __init__(self, serial=None, **kwargs): super().__init__(**kwargs) # Attach the serial devices self._rx = clink.UartUp900cl12bRx(self.path) pr.streamConnect(serial,self._rx) self._tx = clink.ClinkSerialTx(self.path) pr.streamConnect(self._tx,serial) @self.command(value='', name='SendString', description='Send a command string') def sendString(arg): if self._tx is not None: self._tx.sendString(arg) ############################## # Variables ############################## self.add(pr.LocalVariable( name = 'RU', description = 'Recall user page: Must have a number after “ru” such as 1, 2, 3 or 4', mode = 'RW', value = '', localSet = lambda value: self._tx.sendString(f'ru{value}') if value!='' else '' )) self.add(pr.BaseCommand( name = 'RP', description = 'Report current camera setting', function = lambda cmd: self._tx.sendString('rp') )) self.add(pr.BaseCommand( name = 'RF', description = 'Recall factory setting page', function = lambda cmd: self._tx.sendString('rf') )) self.add(pr.LocalVariable( name = 'SM', description = 'Shutter mode: Must have a number after sm (1 ~ f), refer to section 3.3 for details.', mode = 'RW', value = '', localSet = lambda value: self._tx.sendString(f'sm{value}') if value!='' else '' )) self.add(pr.LocalVariable( name = 'SP', description = 'Save user page: There are 4 user page available', mode = 'RW', value = '', localSet = lambda value: self._tx.sendString(f'sp{value}') if value!='' else '' )) self.add(pr.BaseCommand( name = 'NS', description = 'Normal speed: Refer to camera specifications', function = lambda cmd: self._tx.sendString('ns') )) self.add(pr.BaseCommand( name = 'DS', description = 'Double speed: Refer to camera specifications', function = lambda cmd: self._tx.sendString('ds') )) self.add(pr.BaseCommand( name = 'NM', description = 'Normal mode: Normal free running', function = lambda cmd: self._tx.sendString('nm') )) self.add(pr.BaseCommand( name = 'AM', description = 'Asynchronous mode: Asynchronous reset', function = lambda cmd: self._tx.sendString('am') )) self.add(pr.LocalVariable( name = 'GI', description = 'Gain increase: ### = Hexadecimals (000 ~ 3ff). If no number entered, gain will be increased by factor of 1. If a number is entered, then number will be added to stored gain.', mode = 'RW', value = '', localSet = lambda value: self._tx.sendString(f'gi{value}') if value!='' else '' )) self.add(pr.LocalVariable( name = 'GD', description = 'Gain decrease: ### = Hexadecimals (000 ~ 3ff). Same as gi, except it will be decreased.', mode = 'RW', value = '', localSet = lambda value: self._tx.sendString(f'gd{value}') if value!='' else '' )) self.add(pr.LocalVariable( name = 'GN', description = 'Gain number: ### = Hexadecimals (000 ~ 3ff). Refer to the gain curves below for details', mode = 'RW', value = '', localSet = lambda value: self._tx.sendString(f'gn{value}') if value!='' else '' )) self.add(pr.LocalVariable( name = 'BI', description = 'Reference increase: ### = Hexadecimals (000 ~ 3ff). If no number entered, reference will be increased by factor of 1. If a number is entered, then number will be added to stored reference. Note: It’s very uncommon to change reference level, contact UNIQ for further details.', mode = 'RW', value = '', localSet = lambda value: self._tx.sendString(f'bi{value}') if value!='' else '' )) self.add(pr.LocalVariable( name = 'BD', description = 'Reference decrease: ### = Hexadecimals (000 ~ 3ff). If no number entered, reference will be increased by factor of 1. If a number is entered, then number will be added to stored reference. Note: It’s very uncommon to change reference level, contact UNIQ for further details.', mode = 'RW', value = '', localSet = lambda value: self._tx.sendString(f'bd{value}') if value!='' else '' )) self.add(pr.LocalVariable( name = 'BN', description = 'Reference number: ### = Hexadecimals (000 ~ 3ff). If no number entered, reference will be increased by factor of 1. If a number is entered, then number will be added to stored reference. Note: It’s very uncommon to change reference level, contact UNIQ for further details.', mode = 'RW', value = '', localSet = lambda value: self._tx.sendString(f'bn{value}') if value!='' else '' ))
def __init__(self, name='Top', description='Container for FEB FPGA', ip=['10.0.0.1'], pollEn=True, initRead=True, configProm=False, advanceUser=False, refClkSel=['IntClk'], loadYaml=True, userYaml=[''], defaultFile='config/defaults.yml', **kwargs): super().__init__(name=name, description=description, **kwargs) # Set the min. firmware Version support by the software self.minFpgaVersion = 0x20000060 # Enable Init after config self.InitAfterConfig._default = True # Cache the parameters self.advanceUser = advanceUser self.configProm = configProm self.ip = ip self.numEthDev = len(ip) if (ip[0] != 'simulation') else 1 self._timeout = 1.0 if (ip[0] != 'simulation') else 100.0 self._pollEn = pollEn if (ip[0] != 'simulation') else False self._initRead = initRead if (ip[0] != 'simulation') else False self.usrLoadYaml = loadYaml self.userYaml = userYaml self.defaultFile = defaultFile self.pllConfig = [None for i in range(self.numEthDev)] # Check if missing refClkSel configuration if (len(refClkSel) < len(ip)): errMsg = f'len(refClkSel) = {len(refClkSel)} < len(ip) = {len(ip)}.\nMake sure to define a refClkSel for each IP address' click.secho(errMsg, bg='red') raise ValueError(errMsg) # Set the path of the PLL configuration file for i in range(self.numEthDev): if (refClkSel[i] == 'IntClk'): self.pllConfig[ i] = 'config/pll-config/Si5345-RevD-Registers-IntClk.csv' elif (refClkSel[i] == 'ExtSmaClk'): self.pllConfig[ i] = 'config/pll-config/Si5345-RevD-Registers-ExtSmaClk.csv' elif (refClkSel[i] == 'ExtLemoClk'): self.pllConfig[ i] = 'config/pll-config/Si5345-RevD-Registers-ExtLemoClk.csv' else: errMsg = f'refClkSel[{i}] argument must be either [IntClk,ExtSmaClk,ExtLemoClk]' click.secho(errMsg, bg='red') raise ValueError(errMsg) # File writer self.dataWriter = pr.utilities.fileio.StreamWriter() self.add(self.dataWriter) # Create arrays to be filled self.rudp = [None for i in range(self.numEthDev)] self.srpStream = [None for i in range(self.numEthDev)] self.dataStream = [None for i in range(self.numEthDev)] self.semStream = [None for i in range(self.numEthDev)] self.memMap = [None for i in range(self.numEthDev)] # SEM monitor streams self.semDataWriter = SemAsciiFileWriter() # Loop through the devices for i in range(self.numEthDev): ###################################################################### if (self.ip[0] == 'simulation'): self.srpStream[i] = rogue.interfaces.stream.TcpClient( 'localhost', 9000) self.dataStream[i] = rogue.interfaces.stream.TcpClient( 'localhost', 9002) else: self.rudp[i] = pr.protocols.UdpRssiPack(host=ip[i], port=8192, packVer=2, jumbo=False) self.srpStream[i] = self.rudp[i].application(0) self.dataStream[i] = self.rudp[i].application(1) self.semStream[i] = self.rudp[i].application(2) ###################################################################### # Connect the SRPv3 to PGPv3.VC[0] self.memMap[i] = rogue.protocols.srp.SrpV3() pr.streamConnectBiDir(self.memMap[i], self.srpStream[i]) # Check if not PROM loading if not self.configProm: # Connect data stream to file as channel to dataStream pr.streamConnect(self.dataStream[i], self.dataWriter.getChannel(i)) # Connect to the SEM monitor streams and file writer pr.streamConnect(self.semStream[i], self.semDataWriter) pr.streamTap(self.semStream[i], self.dataWriter.getChannel(i + 128)) ###################################################################### # Add devices self.add( common.Fpga( name=f'Fpga[{i}]', memBase=self.memMap[i], offset=0x00000000, configProm=self.configProm, advanceUser=self.advanceUser, expand=True, )) ###################################################################### self.add( pr.LocalVariable( name="LiveDisplayRst", mode="RW", value=0x0, hidden=True, )) @self.command() def LiveDisplayReset(arg): print('LiveDisplayReset()') self.LiveDisplayRst.set(1) for reset in self.reset_list: reset() self.LiveDisplayRst.set(0) @self.command( description= 'This command is intended to be executed before self.dataWriter is closed' ) def StopRun(arg): click.secho('StopRun()', bg='yellow') # Stop the Master First for i in range(self.numEthDev): if self.Fpga[i].Asic.Trig.TrigTypeSel.getDisp() == 'Master': self.Fpga[i].Asic.Trig.EnableReadout.set(0x0) click.secho( f'self.Fpga[{i}].Asic.Trig.EnableReadout.set(0x0)', bg='bright_magenta') # Stop the Slave after the Master for i in range(self.numEthDev): if self.Fpga[i].Asic.Trig.TrigTypeSel.getDisp() == 'Slave': self.Fpga[i].Asic.Trig.EnableReadout.set(0x0) click.secho( f'self.Fpga[{i}].Asic.Trig.EnableReadout.set(0x0)', bg='magenta') @self.command( description= 'This command is intended to be executed after self.dataWriter is opened' ) def StartRun(arg): click.secho('StartRun()', bg='blue') # Reset the sequence and trigger counters for i in range(self.numEthDev): self.Fpga[i].Asic.Trig.countReset() self.Fpga[i].Asic.Readout.SeqCntRst() # Start the Slave First for i in range(self.numEthDev): if self.Fpga[i].Asic.Trig.TrigTypeSel.getDisp() == 'Slave': self.Fpga[i].Asic.Trig.EnableReadout.set(0x1) click.secho( f'self.Fpga[{i}].Asic.Trig.EnableReadout.set(0x1)', bg='magenta') # Start the Master after the Slave for i in range(self.numEthDev): if self.Fpga[i].Asic.Trig.TrigTypeSel.getDisp() == 'Master': self.Fpga[i].Asic.Trig.EnableReadout.set(0x1) click.secho( f'self.Fpga[{i}].Asic.Trig.EnableReadout.set(0x1)', bg='bright_magenta') @self.command( description= 'This command is intended to be executed after self.dataWriter is opened' ) def ResumeRun(arg): click.secho('ResumeRun()', bg='blue') # Start the Slave First for i in range(self.numEthDev): if self.Fpga[i].Asic.Trig.TrigTypeSel.getDisp() == 'Slave': self.Fpga[i].Asic.Trig.EnableReadout.set(0x1) click.secho( f'self.Fpga[{i}].Asic.Trig.EnableReadout.set(0x1)', bg='magenta') # Start the Master after the Slave for i in range(self.numEthDev): if self.Fpga[i].Asic.Trig.TrigTypeSel.getDisp() == 'Master': self.Fpga[i].Asic.Trig.EnableReadout.set(0x1) click.secho( f'self.Fpga[{i}].Asic.Trig.EnableReadout.set(0x1)', bg='bright_magenta') ###################################################################### # Start the system self.start( pollEn=self._pollEn, initRead=self._initRead, timeout=self._timeout, )
def __init__(self, name='TopLevel', description='Container for FPGA Top-Level', dev0='/dev/datadev_0', dev1='/dev/datadev_1', lane=0, ip=None, loopback=False, swRx=True, swTx=True, allLane=False, **kwargs): super().__init__(name=name, description=description, **kwargs) if ip is not None: self.rudp = pr.protocols.UdpRssiPack( host=ip, port=8198, packVer=2, jumbo=True, expand=False, ) # self.add(self.rudp) self.vc0Srp = self.rudp.application(0) # AxiStream.tDest = 0x0 self.vc1Prbs = self.rudp.application(1) # AxiStream.tDest = 0x1 # TDEST 0 routed to stream 0 (SRPv3) self.srp = rogue.protocols.srp.SrpV3() pr.streamConnectBiDir(self.vc0Srp, self.srp) if (loopback): # Loopback the PRBS data pr.streamConnect(self.vc1Prbs, self.vc1Prbs) else: if (swTx): # Connect VC1 to FW RX PRBS self.prbTx = pr.utilities.prbs.PrbsTx(name="PrbsTx", width=128, expand=False) pr.streamConnect(self.prbTx, self.vc1Prbs) self.add(self.prbTx) if (swRx): # Connect VC1 to FW TX PRBS self.prbsRx = pr.utilities.prbs.PrbsRx(name='PrbsRx', width=128, expand=True) pr.streamConnect(self.vc1Prbs, self.prbsRx) self.add(self.prbsRx) self.add(Fpga( memBase=self.srp, expand=True, )) # Add registers elif allLane != 0: self.vc0Srp = [None for i in range(6)] self.vc1Prbs = [None for i in range(6)] self.srp = [None for i in range(6)] self.prbsTx = [None for i in range(6)] self.prbsRx = [None for i in range(6)] for i in range(allLane): self.vc0Srp[i] = rogue.hardware.axi.AxiStreamDma( dev0, (i * 0x100) + 0, True) # self.vc1Prbs[i] = rogue.hardware.axi.AxiStreamDma(dev1,(i*0x100)+1,True) self.vc1Prbs[i] = rogue.hardware.axi.AxiStreamDma( dev1, (i * 0x100) + 0xC1, True) self.srp[i] = rogue.protocols.srp.SrpV3() pr.streamConnectBiDir(self.vc0Srp[i], self.srp[i]) self.add(Fpga( name=f'Fpga[{i}]', memBase=self.srp[i], )) if (loopback): # Loopback the PRBS data pr.streamConnect(self.vc1Prbs[i], self.vc1Prbs[i]) else: if (swTx): # Connect VC1 to FW RX PRBS self.prbsTx[i] = pr.utilities.prbs.PrbsTx( name=f'PrbsTx[{i}]', width=128, expand=False) pr.streamConnect(self.prbsTx[i], self.vc1Prbs[i]) self.add(self.prbsTx[i]) if (swRx): # Connect VC1 to FW TX PRBS self.prbsRx[i] = pr.utilities.prbs.PrbsRx( name=f'PrbsRx[{i}]', width=128, expand=True) pr.streamConnect(self.vc1Prbs[i], self.prbsRx[i]) self.add(self.prbsRx[i]) else: self.vc0Srp = rogue.hardware.axi.AxiStreamDma( dev0, (lane * 0x100) + 0, True) # self.vc1Prbs = rogue.hardware.axi.AxiStreamDma(dev1,(lane*0x100)+1,True) self.vc1Prbs = rogue.hardware.axi.AxiStreamDma( dev1, (lane * 0x100) + 0xC1, True) # TDEST 0 routed to stream 0 (SRPv3) self.srp = rogue.protocols.srp.SrpV3() pr.streamConnectBiDir(self.vc0Srp, self.srp) if (loopback): # Loopback the PRBS data pr.streamConnect(self.vc1Prbs, self.vc1Prbs) else: if (swTx): # Connect VC1 to FW RX PRBS self.prbTx = pr.utilities.prbs.PrbsTx(name="PrbsTx[0]", width=128, expand=False) pr.streamConnect(self.prbTx, self.vc1Prbs) self.add(self.prbTx) if (swRx): # Connect VC1 to FW TX PRBS self.prbsRx = pr.utilities.prbs.PrbsRx(name='PrbsRx[0]', width=128, expand=True) pr.streamConnect(self.vc1Prbs, self.prbsRx) self.add(self.prbsRx) self.add(Fpga( name='Fpga[0]', memBase=self.srp, ))
ba = self.genHeader(False, modAddr, regAddr) ba[2] = (data >> 8) & 0x7F ba[3] = (data >> 22) & 0x3F ba[4] = data & 0xFF ba[5] = (data >> 16) & 0x3F self.sendCmd(ba) def read(self, modAddr, regAddr): ba = self.genHeader(True, modAddr, regAddr) self.sendCmd(ba) exoCmd = rogue.hardware.exo.TemCmd() exoData = rogue.hardware.exo.TemData() print("Exo PCI Version = 0x%08x" % (exoCmd.getInfo().version)) print("Exo PCI Build = %s" % (exoCmd.getInfo().buildString())) cmdTx = exoCmdTx() cmdRx = exoCmdRx() dataRx = exoDataRx() pyrogue.streamConnect(exoCmd, cmdRx) pyrogue.streamConnect(exoData, dataRx) pyrogue.streamConnect(cmdTx, exoCmd) while (True): cmdTx.write(0xA, 0xB, 0x1234567) #cmdTx.read(0xA,0xB) time.sleep(5)
def __lshift__(self, other): pr.streamConnect(other, self) return other
def __init__(self, name, description, root=None, txDevice=None, **kwargs): pyrogue.Device.__init__(self, name=name, description=description, **kwargs) # Add a data emulator module, at the beginning of the chain self.pre_data_emulator = pysmurf.core.emulators.StreamDataEmulatorI16( name="PreDataEmulator") self.add(self.pre_data_emulator) # Add a frame statistics module self.smurf_frame_stats = pysmurf.core.counters.FrameStatistics( name="FrameRxStats") self.add(self.smurf_frame_stats) # Add the SmurfProcessor C++ device. This module implements: channel mapping, # data unwrapping, filter, and downsampling. Python wrapper for these functions # are added here to give the same tree structure as the modular version. self.smurf_processor = smurf.core.processors.SmurfProcessor() self.smurf_mapper = SmurfChannelMapper(name="ChannelMapper", device=self.smurf_processor) self.add(self.smurf_mapper) self.smurf_unwrapper = Unwrapper(name="Unwrapper", device=self.smurf_processor) self.add(self.smurf_unwrapper) self.smurf_filter = GeneralAnalogFilter(name="Filter", device=self.smurf_processor) self.add(self.smurf_filter) self.smurf_downsampler = Downsampler(name="Downsampler", device=self.smurf_processor) self.add(self.smurf_downsampler) # This device doesn't have any user configurations, so we don't add it to the tree self.smurf_header2smurf = pysmurf.core.conventers.Header2Smurf( name="Header2Smurf") # Add a data emulator module, at the end of the chain self.post_data_emulator = pysmurf.core.emulators.StreamDataEmulatorI32( name="PostDataEmulator") self.add(self.post_data_emulator) # Use a standard Rogue file writer. # - Channel 0 will be use for the smurf data # - Channel 1 will be use for the configuration data (aka metadata) self.file_writer = pyrogue.utilities.fileio.StreamWriter( name='FileWriter') self.add(self.file_writer) # Add a Fifo. It will hold up to 100 copies of processed frames, to be processed by # downstream slaves. The frames will be tapped before the file writer. self.fifo = rogue.interfaces.stream.Fifo(100, 0, False) # Connect devices pyrogue.streamConnect(self.pre_data_emulator, self.smurf_frame_stats) pyrogue.streamConnect(self.smurf_frame_stats, self.smurf_processor) pyrogue.streamConnect(self.smurf_processor, self.smurf_header2smurf) pyrogue.streamConnect(self.smurf_header2smurf, self.post_data_emulator) pyrogue.streamConnect(self.post_data_emulator, self.file_writer.getChannel(0)) pyrogue.streamTap(self.post_data_emulator, self.fifo) # If a root was defined, connect it to the file writer, on channel 1 if root: pyrogue.streamConnect(root, self.file_writer.getChannel(1)) # If a TX device was defined, add it to the tree # and connect it to the chain, after the fifo if txDevice: self.transmitter = txDevice self.add(self.transmitter) # Connect the data channel to the FIFO. pyrogue.streamConnect(self.fifo, self.transmitter.getDataChannel()) # If a root was defined, connect it to the meta channel. # Use streamTap as it was already connected to the file writer. if root: pyrogue.streamTap(root, self.transmitter.getMetaChannel())
def __init__(self, *, width=None, checkPayload=True, taps=None, stream=None, **kwargs): pyrogue.Device.__init__(self, description='PRBS Software Receiver', **kwargs) self._prbs = rogue.utilities.Prbs() if width is not None: self._prbs.setWidth(width) if taps is not None: self._prbs.setTaps(taps) if stream is not None: pyrogue.streamConnect(stream, self) self.add( pyrogue.LocalVariable( name='rxEnable', description='RX Enable', mode='RW', value=True, localGet=lambda: self._prbs.getRxEnable(), localSet=lambda value: self._prbs.setRxEnable(value))) self.add( pyrogue.LocalVariable(name='rxErrors', description='RX Error Count', mode='RO', pollInterval=1, value=0, typeStr='UInt32', localGet=self._prbs.getRxErrors)) self.add( pyrogue.LocalVariable(name='rxCount', description='RX Count', mode='RO', pollInterval=1, value=0, typeStr='UInt32', localGet=self._prbs.getRxCount)) self.add( pyrogue.LocalVariable(name='rxBytes', description='RX Bytes', mode='RO', pollInterval=1, value=0, typeStr='UInt32', localGet=self._prbs.getRxBytes)) self.add( pyrogue.LocalVariable(name='rxRate', description='RX Rate', disp="{:.3e}", mode='RO', pollInterval=1, value=0.0, units='Frames/s', localGet=self._prbs.getRxRate)) self.add( pyrogue.LocalVariable(name='rxBw', description='RX BW', disp="{:.3e}", mode='RO', pollInterval=1, value=0.0, units='Bytes/s', localGet=self._prbs.getRxBw)) self.add( pyrogue.LocalVariable(name='checkPayload', description='Payload Check Enable', mode='RW', value=checkPayload, localSet=self._plEnable))
# https://confluence.slac.stanford.edu/display/ppareg/LICENSE.html. # No part of the rogue_example software, including this file, may be # copied, modified, propagated, or distributed except according to the terms # contained in the LICENSE.txt file. #----------------------------------------------------------------------------- import rogue.utilities import pyrogue import pyrogue.simulation import time prbsA = rogue.utilities.Prbs() prbsB = rogue.utilities.Prbs() sim = pyrogue.simulation.StreamSim('localhost', 20, 1, True) pyrogue.streamConnect(prbsA, sim) pyrogue.streamConnect(sim, prbsB) prbsA.enable(1000) prbsB.enMessages(True) while (True): print("Generated: Count %i, Bytes %i" % (prbsA.getTxCount(), prbsA.getTxBytes())) print(" Received: Count %i, Bytes %i, Errors %i" % (prbsB.getRxCount(), prbsB.getRxBytes(), prbsB.getRxErrors())) print(" Gateway: TxCount %i, RxCount %i" % (sim.txCount, sim.rxCount)) #prbsA.genFrame(100) sim.sendOpCode(0xaa) sim.setData(0x7f)
class StreamProc(rogue.interfaces.stream.Master, rogue.interfaces.stream.Slave): def __init__(self): rogue.interfaces.stream.Master.__init__(self) rogue.interfaces.stream.Slave.__init__(self) def _acceptFrame(self, frame): p = bytearray(frame.getPayload()) frame.read(p, 0) # size=payload, zeroCopyEn=True, maxBuffSize=0 frameOut = self._reqFrame(frame.getPayload(), True, 0) for i in range(frame.getPayload()): p[i] += 3 frameOut.write(p, 0) self._sendFrame(frameOut) gen = StreamTx() prc = StreamProc() rx = StreamRx() pyrogue.streamConnect(gen, prc) pyrogue.streamConnect(prc, rx) while (True): time.sleep(1) gen.generate()
def __rshift__(self, other): pr.streamConnect(self, other) return other
def __init__( self, *, config_file=None, epics_prefix="EpicsPrefix", polling_en=True, pv_dump_file=None, txDevice=None, fpgaTopLevel=None, stream_pv_size=2**19, # Not sub-classed stream_pv_type='Int16', # Not sub-classed configure=False, VariableGroups=None, server_port=0, **kwargs): pyrogue.Root.__init__(self, name="AMCc", initRead=True, pollEn=polling_en, streamIncGroups='stream', serverPort=server_port, **kwargs) ######################################################################################### # The following interfaces are expected to be defined at this point by a sub-class # self._streaming_stream # Data stream interface # self._ddr_streams # 4 DDR Interface Streams # self._fpga = Top level FPGA # Add PySmurf Application Block self.add(pysmurf.core.devices.SmurfApplication()) # Add FPGA self.add(self._fpga) # File writer for streaming interfaces # DDR interface (TDEST 0x80 - 0x87) self._stm_data_writer = pyrogue.utilities.fileio.StreamWriter( name='streamDataWriter') self.add(self._stm_data_writer) # Streaming interface (TDEST 0xC0 - 0xC7) self._stm_interface_writer = pyrogue.utilities.fileio.StreamWriter( name='streamingInterface') self.add(self._stm_interface_writer) # Add the SMuRF processor device self._smurf_processor = pysmurf.core.devices.SmurfProcessor( name="SmurfProcessor", description="Process the SMuRF Streaming Data Stream", root=self, txDevice=txDevice) self.add(self._smurf_processor) # Connect smurf processor pyrogue.streamConnect(self._streaming_stream, self._smurf_processor) # Add data streams (0-3) to file channels (0-3) for i in range(4): ## DDR streams pyrogue.streamConnect(self._ddr_streams[i], self._stm_data_writer.getChannel(i)) ## Streaming interface streams # We have already connected TDEST 0xC1 to the smurf_processor receiver, # so we need to tapping it to the data writer. pyrogue.streamTap(self._streaming_stream, self._stm_interface_writer.getChannel(0)) # TES Bias Update Function # smurf_processor bias index 0 = TesBiasDacDataRegCh[2] - TesBiasDacDataRegCh[1] # smurf_processor bias index l = TesBiasDacDataRegCh[4] - TesBiasDacDataRegCh[3] def _update_tes_bias(idx): v1 = self.FpgaTopLevel.AppTop.AppCore.RtmCryoDet.RtmSpiMax.node( f'TesBiasDacDataRegCh[{(2*idx)+2}]').value() v2 = self.FpgaTopLevel.AppTop.AppCore.RtmCryoDet.RtmSpiMax.node( f'TesBiasDacDataRegCh[{(2*idx)+1}]').value() val = (v1 - v2) // 2 # Pass to data processor self._smurf_processor.setTesBias(index=idx, val=val) # Register TesBias values configuration to update stream processor # Bias values are ranged 1 - 32, matching tes bias indexes 0 - 16 for i in range(1, 33): idx = (i - 1) // 2 try: v = self.FpgaTopLevel.AppTop.AppCore.RtmCryoDet.RtmSpiMax.node( f'TesBiasDacDataRegCh[{i}]') v.addListener( lambda path, value, lidx=idx: _update_tes_bias(lidx)) except Exception: print(f"TesBiasDacDataRegCh[{i}] not found... Skipping!") # Run control for streaming interfaces self.add( pyrogue.RunControl(name='streamRunControl', description='Run controller', cmd=self._fpga.SwDaqMuxTrig, rates={ 1: '1 Hz', 10: '10 Hz', 30: '30 Hz' })) # lcaPut limits the maximun lenght of a string to 40 chars, as defined # in the EPICS R3.14 CA reference manual. This won't allowed to use the # command 'ReadConfig' with a long file path, which is usually the case. # This function is a workaround to that problem. Fomr matlab one can # just call this function without arguments an the function ReadConfig # will be called with a predefined file passed during startup # However, it can be usefull also win the GUI, so it is always added. self._config_file = config_file self.add( pyrogue.LocalCommand(name='setDefaults', description='Set default configuration', function=self._set_defaults_cmd)) # Flag that indicates if the default configuration should be loaded # once the root is started. self._configure = configure # Variable groups self._VariableGroups = VariableGroups # Add epics interface self._epics = None if epics_prefix: print("Starting EPICS server using prefix \"{}\"".format( epics_prefix)) from pyrogue.protocols import epics self._epics = epics.EpicsCaServer(base=epics_prefix, root=self) self._pv_dump_file = pv_dump_file # PVs for stream data # This should be replaced with DataReceiver objects if stream_pv_size: print( "Enabling stream data on PVs (buffer size = {} points, data type = {})" .format(stream_pv_size, stream_pv_type)) self._stream_fifos = [] self._stream_slaves = [] for i in range(4): self._stream_slaves.append( self._epics.createSlave(name="AMCc:Stream{}".format(i), maxSize=stream_pv_size, type=stream_pv_type)) # Calculate number of bytes needed on the fifo if '16' in stream_pv_type: fifo_size = stream_pv_size * 2 else: fifo_size = stream_pv_size * 4 self._stream_fifos.append( rogue.interfaces.stream.Fifo(1000, fifo_size, True)) # changes pyrogue.streamConnect(self._stream_fifos[i], self._stream_slaves[i]) pyrogue.streamTap(self._ddr_streams[i], self._stream_fifos[i]) # Update SaveState to not read before saving self.SaveState.replaceFunction( lambda arg: self.saveYaml(name=arg, readFirst=False, modes=['RW', 'RO', 'WO'], incGroups=None, excGroups='NoState', autoPrefix='state', autoCompress=True)) # Update SaveConfig to not read before saving self.SaveConfig.replaceFunction( lambda arg: self.saveYaml(name=arg, readFirst=False, modes=['RW', 'WO'], incGroups=None, excGroups='NoConfig', autoPrefix='config', autoCompress=False))
def __init__(self, name="Top", description="Container for FEB FPGA", dev='/dev/datadev_0', hwType='pcie', ip='10.0.0.1', **kwargs): super().__init__(name=name, description=description, **kwargs) # File writer dataWriter = pr.utilities.fileio.StreamWriter() self.add(dataWriter) ###################################################################### if (hwType == 'hsio-dtm') or (hwType == 'rce-dpm'): # Create the mmap interface rceMap = rogue.hardware.axi.AxiMemMap('/dev/rce_memmap') # Add RCE version device self.add(rceg3.RceVersion( memBase=rceMap, expand=False, )) # Add PGPv3 to the FEB self.add( pgp.Pgp3AxiL( name='Pgp3Mon', memBase=rceMap, offset=0xA0000000, numVc=1, writeEn=True, expand=False, )) if (hwType == 'hsio-dtm'): # Add PGPv2b to the HSIO FPGA self.add( pgp.Pgp2bAxi( name='Pgp2bMon', memBase=rceMap, offset=0xA1000000, expand=False, )) # Connect the SRPv0 to PGPv2b.VC[1] pgp2bVc1 = rogue.hardware.axi.AxiStreamDma( '/dev/axi_stream_dma_0', 1, True) srpV0 = rogue.protocols.srp.SrpV0() pr.streamConnectBiDir(srpV0, pgp2bVc1) if (hwType == 'pcie'): axiMemMap = rogue.hardware.axi.AxiMemMap(dev) self.add( pcie.AxiPcieCore( memBase=axiMemMap, offset=0x00000000, expand=False, )) # for i in range(8): # self.add(pgp.Pgp3AxiL( # memBase = axiMemMap, # name = ('Pgp3Mon[%d]' % i), # offset = (0x00800000 + i*0x10000), # numVc = 16, # writeEn = True, # expand = False, # )) ###################################################################### # Create an empty stream arrays configStream = [None] * 4 dataStream = [None] * 4 ######################################################################################################################## # https://github.com/slaclab/rogue/blob/master/include/rogue/hardware/axi/AxiStreamDma.h # static boost::shared_ptr<rogue::hardware::axi::AxiStreamDma> create (std::string path, uint32_t dest, bool ssiEnable); ######################################################################################################################## ###################################################################### # PGPv3.[VC=0] = FEB SRPv3 Register Access # PGPv3.[VC=1] = RD53[DPORT=0] Streaming ASIC Configuration Interface # PGPv3.[VC=2] = RD53[DPORT=1] Streaming ASIC Configuration Interface # PGPv3.[VC=3] = RD53[DPORT=2] Streaming ASIC Configuration Interface # PGPv3.[VC=4] = RD53[DPORT=3] Streaming ASIC Configuration Interface # PGPv3.[VC=5] = RD53[DPORT=0] Streaming Data Interface # PGPv3.[VC=6] = RD53[DPORT=1] Streaming Data Interface # PGPv3.[VC=7] = RD53[DPORT=2] Streaming Data Interface # PGPv3.[VC=8] = RD53[DPORT=3] Streaming Data Interface ###################################################################### if (hwType == 'simulation'): srpStream = pr.interfaces.simulation.StreamSim(host='localhost', dest=0, uid=12, ssi=True) for i in range(4): configStream[i] = pr.interfaces.simulation.StreamSim( host='localhost', dest=1 + i, uid=12, ssi=True) dataStream[i] = pr.interfaces.simulation.StreamSim( host='localhost', dest=5 + i, uid=12, ssi=True) elif (hwType == 'eth'): rudp = pr.protocols.UdpRssiPack(host=ip, port=8192, packVer=2) srpStream = rudp.application(0) for i in range(4): configStream[i] = rudp.application(1 + i) dataStream[i] = rudp.application(5 + i) else: srpStream = rogue.hardware.axi.AxiStreamDma(dev, 0, True) for i in range(4): configStream[i] = rogue.hardware.axi.AxiStreamDma( dev, 1 + i, True) dataStream[i] = rogue.hardware.axi.AxiStreamDma( dev, 5 + i, True) ###################################################################### # Connect the SRPv3 to PGPv3.VC[0] memMap = rogue.protocols.srp.SrpV3() pr.streamConnectBiDir(memMap, srpStream) for i in range(4): # Add data stream to file as channel [i] to dataStream[i] pr.streamConnect(dataStream[i], dataWriter.getChannel(i)) ###################################################################### # Add devices self.add( axiVer.AxiVersion( name='AxiVersion', memBase=memMap, offset=0x00000000, expand=False, )) self.add( xil.Xadc( name='Xadc', memBase=memMap, offset=0x00010000, expand=False, )) self.add( prom.AxiMicronP30( name='AxiMicronP30', memBase=memMap, offset=0x00020000, hidden=True, # Hidden in GUI because indented for scripting )) self.add( common.SysReg( name='SysReg', description= 'This device contains system level configuration and status registers', memBase=memMap, offset=0x00030000, expand=False, )) self.add( common.Ntc( name='Rd53Ntc', description= 'This device contains the four NTC MAX6682 readout modules', memBase=memMap, offset=0x00040000, expand=False, )) self.add( nxp.Sa56004x( name='BoardTemp', description= 'This device monitors the board temperature and FPGA junction temperature', memBase=memMap, offset=0x00050000, expand=False, )) self.add( linear.Ltc4151( name='BoardPwr', description= 'This device monitors the board power, input voltage and input current', memBase=memMap, offset=0x00050400, senseRes=20.E-3, # Units of Ohms expand=False, )) for i in range(4): self.add( common.RxPhyMon( name=('RxPhyMon[%d]' % i), memBase=memMap, offset=(0x01000000 * (i + 1) + 0x00100000), expand=False, )) self.add( common.Timing( name='Timing', description= 'This device monitors the TLU and timing/trigger emulator', memBase=memMap, offset=0x05000000, expand=False, ))
def __init__(self, ip_addr, config_file, server_mode, group_name, epics_prefix,\ polling_en, comm_type, pcie_rssi_link, stream_pv_size, stream_pv_type,\ pv_dump_file): try: pyrogue.Root.__init__(self, name='AMCc', description='AMC Carrier') # File writer for streaming interfaces # DDR interface (TDEST 0x80 - 0x87) stm_data_writer = pyrogue.utilities.fileio.StreamWriter( name='streamDataWriter') self.add(stm_data_writer) # Streaming interface (TDEST 0xC0 - 0xC7) stm_interface_writer = pyrogue.utilities.fileio.StreamWriter( name='streamingInterface') self.add(stm_interface_writer) # Workaround to FpgaTopLelevel not supporting rssi = None if pcie_rssi_link == None: pcie_rssi_link = 0 # Instantiate Fpga top level fpga = FpgaTopLevel(ipAddr=ip_addr, commType=comm_type, pcieRssiLink=pcie_rssi_link) # Add devices self.add(fpga) # Add data streams (0-7) to file channels (0-7) for i in range(8): # DDR streams pyrogue.streamConnect(fpga.stream.application(0x80 + i), stm_data_writer.getChannel(i)) # Streaming interface streams #pyrogue.streamConnect(fpga.stream.application(0xC0 + i), # new commended out # stm_interface_writer.getChannel(i)) # Our receiver data_fifo = rogue.interfaces.stream.Fifo(1000, 0, 1) # new self.my_processor = MyModule.MyProcessor() self.my_processor.setDebug(False) #pyrogue.streamConnect(base.FpgaTopLevel.stream.application(0xC1), data_fifo) # new #pyrogue.streamConnect(base.FpgaTopLevel.stream.Application(0xC1), data_fifo) # new pyrogue.streamConnect(fpga.stream.application(0xC1), data_fifo) pyrogue.streamConnect(data_fifo, self.my_processor) #pyrogue.streamTap(fpga.stream.application(0xC1), rx) # Run control for streaming interfaces self.add( pyrogue.RunControl(name='streamRunControl', description='Run controller', cmd=fpga.SwDaqMuxTrig, rates={ 1: '1 Hz', 10: '10 Hz', 30: '30 Hz' })) # PVs for stream data, used on PCAS-based EPICS server if epics_prefix and stream_pv_size: if use_pcas: print("Enabling stream data on PVs (buffer size = {} points, data type = {})"\ .format(stream_pv_size,stream_pv_type)) # Add data streams (0-7) to local variables so they are expose as PVs # Also add PVs to select the data format for i in range(8): # Calculate number of bytes needed on the fifo if '16' in stream_pv_type: fifo_size = stream_pv_size * 2 else: fifo_size = stream_pv_size * 4 # Setup a FIFO tapped to the steram data and a Slave data buffer # Local variables will talk to the data buffer directly. stream_fifo = rogue.interfaces.stream.Fifo( 0, fifo_size, 0) data_buffer = DataBuffer(size=stream_pv_size, data_type=stream_pv_type) stream_fifo._setSlave(data_buffer) #pyrogue.streamTap(fpga.stream.application(0x80 + i), stream_fifo) # Variable to read the stream data stream_var = pyrogue.LocalVariable( name='Stream{}'.format(i), description='Stream {}'.format(i), mode='RO', value=0, localGet=data_buffer.read, update=False, hidden=True) # Set the buffer callback to update the variable data_buffer.set_callback(stream_var.updated) # Variable to set the data format data_format_var = pyrogue.LocalVariable( name='StreamDataFormat{}'.format(i), description='Type of data being unpacked', mode='RW', value=0, enum={ i: j for i, j in enumerate( data_buffer.get_data_format_list()) }, localSet=data_buffer.set_data_format, localGet=data_buffer.get_data_format, hidden=True) # Variable to set the data byte order byte_order_var = pyrogue.LocalVariable( name='StreamDataByteOrder{}'.format(i), description='Byte order of data being unpacked', mode='RW', value=0, enum={ i: j for i, j in enumerate( data_buffer.get_data_byte_order_list()) }, localSet=data_buffer.set_data_byte_order, localGet=data_buffer.get_data_byte_order, hidden=True) # Variable to read the data format string format_string_var = pyrogue.LocalVariable( name='StreamDataFormatString{}'.format(i), description='Format string used to unpack the data', mode='RO', value=0, localGet=data_buffer.get_data_format_string, hidden=True) # Add listener to update the format string readback variable # when the data format or data byte order is changed data_format_var.addListener(format_string_var) byte_order_var.addListener(format_string_var) # Add the local variable to self self.add(stream_var) self.add(data_format_var) self.add(byte_order_var) self.add(format_string_var) # lcaPut limits the maximun lenght of a string to 40 chars, as defined # in the EPICS R3.14 CA reference manual. This won't allowed to use the # command 'ReadConfig' with a long file path, which is usually the case. # This function is a workaround to that problem. Fomr matlab one can # just call this function without arguments an the function ReadConfig # will be called with a predefined file passed during startup # However, it can be usefull also win the GUI, so it is always added. self.config_file = config_file self.add( pyrogue.LocalCommand(name='setDefaults', description='Set default configuration', function=self.set_defaults_cmd)) self.add( pyrogue.LocalCommand(name='runGarbageCollection', description='runGarbageCollection', function=self.run_garbage_collection)) self.add( pyrogue.LocalVariable( name='smurfProcessorDebug', description='Enable smurf processor transmit debug', mode='RW', value=False, localSet=lambda value: self.my_processor.setDebug(value), hidden=False)) # Start the root if group_name: # Start with Pyro4 server host_name = get_host_name() print( "Starting rogue server with Pyro using group name \"{}\"". format(group_name)) self.start(pollEn=polling_en, pyroGroup=group_name, pyroHost=host_name, pyroNs=None) else: # Start without Pyro4 server print("Starting rogue server") self.start(pollEn=polling_en) self.ReadAll() except KeyboardInterrupt: print("Killing server creation...") super(LocalServer, self).stop() exit() # Show image build information try: print("") print("FPGA image build information:") print("===================================") print("BuildStamp : {}"\ .format(self.FpgaTopLevel.AmcCarrierCore.AxiVersion.BuildStamp.get())) print("FPGA Version : 0x{:x}"\ .format(self.FpgaTopLevel.AmcCarrierCore.AxiVersion.FpgaVersion.get())) print("Git hash : 0x{:x}"\ .format(self.FpgaTopLevel.AmcCarrierCore.AxiVersion.GitHash.get())) except AttributeError as attr_error: print("Attibute error: {}".format(attr_error)) print("") # Start the EPICS server if epics_prefix: print("Starting EPICS server using prefix \"{}\"".format( epics_prefix)) # Choose the appropiate epics module: if use_pcas: self.epics = pyrogue.epics.EpicsCaServer(base=epics_prefix, root=self) else: self.epics = pyrogue.protocols.epics.EpicsCaServer( base=epics_prefix, root=self) # PVs for stream data, used on GDD-based EPICS server if stream_pv_size: print("Enabling stream data on PVs (buffer size = {} points, data type = {})"\ .format(stream_pv_size,stream_pv_type)) for i in range(8): stream_slave = self.epics.createSlave( name="AMCc:Stream{}".format(i), maxSize=stream_pv_size, type=stream_pv_type) # Calculate number of bytes needed on the fifo if '16' in stream_pv_type: fifo_size = stream_pv_size * 2 else: fifo_size = stream_pv_size * 4 stream_fifo = rogue.interfaces.stream.Fifo( 0, fifo_size, 0) # chnages stream_fifo._setSlave(stream_slave) pyrogue.streamTap(fpga.stream.application(0x80 + i), stream_fifo) self.epics.start() # Dump the PV list to the especified file if pv_dump_file: try: # Try to open the output file f = open(pv_dump_file, "w") except IOError: print("Could not open the PV dump file \"{}\"".format( pv_dump_file)) else: with f: print("Dumping PV list to \"{}\"...".format( pv_dump_file)) try: try: # Redirect the stdout to the output file momentarily original_stdout, sys.stdout = sys.stdout, f self.epics.dump() finally: sys.stdout = original_stdout print("Done!") except: # Capture error from epics.dump() if any print("Errors were found during epics.dump()") # If no in server Mode, start the GUI if not server_mode: create_gui(self) else: # Stop the server when Crtl+C is pressed print("") print("Running in server mode now. Press Ctrl+C to stop...") try: # Wait for Ctrl+C while True: time.sleep(1) except KeyboardInterrupt: pass
def __init__(self, cameraType = 'ePix100a'): super(Window, self).__init__() # window init self.mainWdGeom = [50, 50, 1100, 600] # x, y, width, height self.setGeometry(self.mainWdGeom[0], self.mainWdGeom[1], self.mainWdGeom[2],self.mainWdGeom[3]) self.setWindowTitle("ePix image viewer") # creates a camera object self.currentCam = cameras.Camera(cameraType = cameraType) # add actions for menu item extractAction = QAction("&Quit", self) extractAction.setShortcut("Ctrl+Q") extractAction.setStatusTip('Leave The App') extractAction.triggered.connect(self.close_viewer) openFile = QAction("&Open File", self) openFile.setShortcut("Ctrl+O") openFile.setStatusTip('Open a new set of images') openFile.setStatusTip('Open file') openFile.triggered.connect(self.file_open) # display status tips for all menu items (or actions) self.statusBar() # Creates the main menu, mainMenu = self.menuBar() # adds items and subitems fileMenu = mainMenu.addMenu('&File') fileMenu.addAction(openFile) fileMenu.addAction(extractAction) # Create widget self.prepairWindow() # add all buttons to the screen self.def_bttns() # rogue interconection # # Create the objects self.fileReader = rogue.utilities.fileio.StreamReader() self.eventReader = EventReader(self) self.eventReaderScope = EventReader(self) self.eventReaderMonitoring = EventReader(self) self.dilplayFramesFromAsics = -1 # 0 for asic 0, 1 for asic 1, -1 for all # Connect the fileReader to our event processor pyrogue.streamConnect(self.fileReader,self.eventReader) # Connect the trigger signal to a slot. # the different threads send messages to synchronize their tasks self.imageTrigger.connect(self.buildImageFrame) self.pseudoScopeTrigger.connect(self.displayPseudoScopeFromReader) self.monitoringDataTrigger.connect(self.displayMonitoringDataFromReader) self.processFrameTrigger.connect(self.eventReader._processFrame) self.processPseudoScopeFrameTrigger.connect(self.eventReaderScope._processFrame) self.processMonitoringFrameTrigger.connect(self.eventReaderMonitoring._processFrame) # weak way to sync frame reader and display self.readFileDelay = 0.1 # initialize image processing objects self.rawImgFrame = [] self.imgDesc = [] self.imgTool = imgPr.ImageProcessing(self) #init mouse variables self.mouseX = 0 self.mouseY = 0 self.image = QImage() self.pixelTimeSeries = np.array([]) #initialize data monitoring self.monitoringDataTraces = np.zeros((8,1), dtype='int32') self.monitoringDataIndex = 0 self.monitoringDataLength = 100 #init bit mask self.pixelBitMask.setText(str(hex(np.uint16(self.currentCam.bitMask)))) # display the window on the screen after all items have been added self.show()
# Load the default YAML file print(f'Loading {Configuration_LOAD_file} Configuration File...') top.LoadConfig(arg = Configuration_LOAD_file) if DebugPrint: # Tap the streaming data interface (same interface that writes to file) debugStream = feb.PrintEventReader() pyrogue.streamTap(top.dataStream[0], debugStream) # Assuming only 1 FPGA # Create the data reader streaming interface dataReader = top.dataStream[0] # Create the Event reader streaming interface dataStream = feb.MyPixelReader() # Connect the file reader ---> event reader pr.streamConnect(dataReader, dataStream) LSB_estimate_array = np.zeros(Number_of_pixels) range_list = [0]*Number_of_pixels for pixel_number in range(Pixel_range_low, Pixel_range_high, Pixel_iteration): LSB_est, optimal_range = run_pixel_calibration(top, dataStream, pixel_number) LSB_estimate_array[pixel_number] = LSB_est range_list[pixel_number] = optimal_range #print results print('\n\n\n') print('#################') print('# Final Results #') print('#################') print('Pixel | LSB_est | Range')