当前位置: 首页>>代码示例>>Python>>正文


Python Parameter.addChildren方法代码示例

本文整理汇总了Python中chipwhisperer.common.utils.parameter.Parameter.addChildren方法的典型用法代码示例。如果您正苦于以下问题:Python Parameter.addChildren方法的具体用法?Python Parameter.addChildren怎么用?Python Parameter.addChildren使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在chipwhisperer.common.utils.parameter.Parameter的用法示例。


在下文中一共展示了Parameter.addChildren方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: OpenADCInterface_FTDI

# 需要导入模块: from chipwhisperer.common.utils.parameter import Parameter [as 别名]
# 或者: from chipwhisperer.common.utils.parameter.Parameter import addChildren [as 别名]
class OpenADCInterface_FTDI(Parameterized, Plugin):
    _name = "FTDI (SASEBO-W/SAKURA-G)"

    def __init__(self, oadcInstance):
        self.serialNumber = ''
        self._serialnumbers = ['']

        self.params = Parameter(name=self.getName(), type='group')
        self.params.addChildren([
            {'name':'Refresh Device List', 'type':'action', 'action':self.serialRefresh},
            {'name':'Device Serial Number', 'key':'snum', 'type':'list', 'values':[''], 'get':self.getSerialNumber, 'set':self.setSelectedDevice},
        ])
        self.ser = None

        if (openadc_qt is None) or (ft is None):
            raise ImportError("Needed imports for FTDI missing")
        else:
            self.scope = oadcInstance

    def getSerialNumber(self):
        return self.serialNumber

    @setupSetParam("Device Serial Number")
    def setSelectedDevice(self, snum):
        self.serialNumber = snum

    def __del__(self):
        if self.ser != None:
            self.ser.close()

    def con(self):
        if self.ser == None:
            try:
                self.dev = ft.openEx(str(self.serialNumber), ft.ftd2xx.OPEN_BY_SERIAL_NUMBER)
                self.dev.setBitMode(0x00, 0x40)
                self.dev.setTimeouts(500, 500)
                self.dev.setLatencyTimer(2)
                self.ser = self
            except ft.ftd2xx.DeviceError, e:
                self.ser = None
                raise IOError("Could not open %s: %s" % (self.serialNumber, e))

        try:
            self.scope.con(self.ser)
            print("OpenADC Found, Connecting")
        except IOError,e:
            exctype, value = sys.exc_info()[:2]
            raise IOError("OpenADC Error: %s"%(str(exctype) + str(value)) + " - " + e.message)
开发者ID:phonchi,项目名称:chipwhisperer,代码行数:50,代码来源:ftdi.py

示例2: OpenADCInterface_Serial

# 需要导入模块: from chipwhisperer.common.utils.parameter import Parameter [as 别名]
# 或者: from chipwhisperer.common.utils.parameter.Parameter import addChildren [as 别名]
class OpenADCInterface_Serial(Parameterized, Plugin):
    _name = "Serial Port (LX9)"

    def __init__(self, parentParam, oadcInstance):
        self.portName = ''
        self.ser = None

        self.params = Parameter(name=self.getName(), type='group')
        self.params.addChildren([
            {'name':'Refresh List', 'type':'action', 'action':lambda _: self.serialRefresh()},
            {'name':'Selected Port', 'type':'list', 'values':[''], 'get':self.getPortName, 'set':self.setPortName},
        ])

        if (openadc_qt is None) or (serial is None):
            raise ImportError("Needed imports for serial missing")
        else:
            self.scope = oadcInstance

    def getPortName(self):
        return self.portName

    @setupSetParam("Selected Port")
    def setPortName(self, snum):
        self.portName = snum

    def __del__(self):
        if self.ser != None:
            self.ser.close()

    def con(self):
        if self.ser == None:
            self.ser = serial.Serial()
            self.ser.port     = self.portName
            self.ser.baudrate = 512000
            self.ser.timeout  = 2     # 2 second timeout

            attempts = 4
            while attempts > 0:
                try:
                    self.ser.open()
                    attempts = 0
                except serial.SerialException as e:
                    attempts = attempts - 1
                    self.ser = None
                    if attempts == 0:
                        raise IOError("Could not open %s" % self.ser.name)

        try:
            self.scope.con(self.ser)
            print("OpenADC Found, Connecting")
        except IOError as e:
            exctype, value = sys.exc_info()[:2]
            raise IOError("OpenADC Error (Serial Port): %s" % (str(exctype) + str(value)))

    def dis(self):
        if self.ser != None:
            self.ser.close()
            self.ser = None

    def serialRefresh(self):
        serialnames = scan.scan()
        if serialnames == None or len(serialnames) == 0:
            serialnames = [" "]

        p = self.params.getChild('Selected Port')
        p.setLimits(serialnames)
        p.setValue(serialnames[0])

    def getTextName(self):
        try:
            return self.ser.name
        except:
            return "None?"
开发者ID:FrankMuenzner,项目名称:chipwhisperer,代码行数:75,代码来源:oadc_serial.py

示例3: CWCoreAPI

# 需要导入模块: from chipwhisperer.common.utils.parameter import Parameter [as 别名]
# 或者: from chipwhisperer.common.utils.parameter.Parameter import addChildren [as 别名]
class CWCoreAPI(Parameterized):
    """
    ChipWisperer API Class.
    Provides access to the most important parts of the tool.
    It has a singleton method called CWCoreAPI.getInstance() that returns a reference to the API instance.
    """

    __name__ = "ChipWhisperer"
    __organization__ = "NewAE Technology Inc."
    __version__ = "V3.1.9"
    _name = 'Generic Settings'
    instance = None

    def __init__(self):
        CWCoreAPI.instance = self
        self.sigNewProject = util.Signal()
        self.sigNewScopeData = util.Signal()
        self.sigConnectStatus = util.Signal()
        self.sigAttackChanged = util.Signal()
        self.sigNewInputData = util.Signal()
        self.sigNewTextResponse = util.Signal()
        self.sigTraceDone = util.Signal()
        self.sigCampaignStart = util.Signal()
        self.sigCampaignDone = util.Signal()
        self.sigTracesChanged = util.Signal()
        self.executingScripts = util.Observable(False)

        self.valid_scopes = pluginmanager.getPluginsInDictFromPackage("chipwhisperer.capture.scopes", True, True)
        self.valid_targets =  pluginmanager.getPluginsInDictFromPackage("chipwhisperer.capture.targets", True, True)
        self.valid_traces = pluginmanager.getPluginsInDictFromPackage("chipwhisperer.common.traces", True, True)
        self.valid_aux = pluginmanager.getPluginsInDictFromPackage("chipwhisperer.capture.auxiliary", True, True)
        self.valid_acqPatterns =  pluginmanager.getPluginsInDictFromPackage("chipwhisperer.capture.acq_patterns", True, False)
        self.valid_attacks = pluginmanager.getPluginsInDictFromPackage("chipwhisperer.analyzer.attacks", True, False)
        self.valid_preprocessingModules = pluginmanager.getPluginsInDictFromPackage("chipwhisperer.analyzer.preprocessing", False, True)

        self.settings = Settings()

        # Initialize default values
        self._project = self._scope = self._target = self._attack =  self._traceFormat = self._acqPattern = None
        self._attack = self.valid_attacks.get("CPA", None)
        self._acqPattern = self.valid_acqPatterns["Basic"]
        self._auxList = [None]  # TODO: implement it as a list in the whole class
        self._numTraces = 50
        self._numTraceSets = 1

        self.params = Parameter(name='Generic Settings', type='group', addLoadSave=True).register()
        self.params.addChildren([
            {'name':'Scope Module', 'key':'scopeMod', 'type':'list', 'values':self.valid_scopes, 'get':self.getScope, 'set':self.setScope},
            {'name':'Target Module', 'key':'targetMod', 'type':'list', 'values':self.valid_targets, 'get':self.getTarget, 'set':self.setTarget},
            {'name':'Trace Format', 'type':'list', 'values':self.valid_traces, 'get':self.getTraceFormat, 'set':self.setTraceFormat},
            {'name':'Auxiliary Module', 'type':'list', 'values':self.valid_aux, 'get':self.getAuxModule, 'set':self.setAux},
            {'name':'Acquisition Settings', 'type':'group', 'children':[
                    {'name':'Number of Traces', 'type':'int', 'limits':(1, 1E9), 'get':self.getNumTraces, 'set':self.setNumTraces, 'linked':['Traces per Set']},
                    {'name':'Number of Sets', 'type':'int', 'limits':(1, 1E6), 'get':self.getNumTraceSets, 'set':self.setNumTraceSets, 'linked':['Traces per Set'], 'tip': 'Break acquisition into N sets, '
                     'which may cause data to be saved more frequently. The default capture driver requires that NTraces/NSets is small enough to avoid running out of system memory '
                     'as each segment is buffered into RAM before being written to disk.'},
                    {'name':'Traces per Set', 'type':'int', 'readonly':True, 'get':self.tracesPerSet},
                    {'name':'Key/Text Pattern', 'type':'list', 'values':self.valid_acqPatterns, 'get':self.getAcqPattern, 'set':self.setAcqPattern},
            ]},
        ])
        self.scopeParam = Parameter(name="Scope Settings", type='group', addLoadSave=True).register()
        self.params.getChild('Scope Module').stealDynamicParameters(self.scopeParam)

        self.targetParam = Parameter(name="Target Settings", type='group', addLoadSave=True).register()
        self.params.getChild('Target Module').stealDynamicParameters(self.targetParam)

        self.traceParam = Parameter(name="Trace Settings", type='group', addLoadSave=True).register()
        self.params.getChild('Trace Format').stealDynamicParameters(self.traceParam)

        self.auxParam = Parameter(name="Aux Settings", type='group', addLoadSave=True).register()
        self.params.getChild('Auxiliary Module').stealDynamicParameters(self.auxParam)

        # self.attackParam = Parameter(name="Attack Settings", type='group')
        # self.params.getChild('Attack Module').getDynamicParameters(self.attackParam)

        self.newProject()

    def getResults(self, name):
        """Return the requested result widget. It should be registered."""
        return ResultsBase.registeredObjects[name]

    def getScope(self):
        """Return the current scope module object."""
        return self._scope

    @setupSetParam("Scope Module")
    def setScope(self, driver):
        """Set the current scope module object."""
        if self.getScope():
            self.getScope().dis()
        self._scope = driver
        if self.getScope():
            self.getScope().dataUpdated.connect(self.sigNewScopeData.emit)
            self.getScope().connectStatus.connect(self.sigConnectStatus.emit)

    def getTarget(self):
        """Return the current target module object."""
        return self._target

    @setupSetParam("Target Module")
#.........这里部分代码省略.........
开发者ID:phonchi,项目名称:chipwhisperer,代码行数:103,代码来源:CWCoreAPI.py

示例4: ChipWhispererSAD

# 需要导入模块: from chipwhisperer.common.utils.parameter import Parameter [as 别名]
# 或者: from chipwhisperer.common.utils.parameter.Parameter import addChildren [as 别名]
class ChipWhispererSAD(Parameterized):
    """
    Communicates and drives with the Sum of Absolute Differences (SAD) Module inside the ChipWhisperer System. You
    need to configure the trigger module as active & set the trigger polarity to "high" for this to work.    
    """
    _name = 'SAD Trigger Module'
    STATUS_RUNNING_MASK = 1 << 3
    STATUS_RESET_MASK = 1 << 0
    STATUS_START_MASK = 1 << 1
             
    def __init__(self, oa):

        self.oldlow = None
        self.oldhigh = None
        self.oa = oa
        self.sadref = [0]

        try:
            # Update SAD calculation when data changes
            ResultsBase.registeredObjects["Trace Output Plot"].dataChanged.connect(self.dataChanged)
            outwid = ResultsBase.registeredObjects["Trace Output Plot"]
            rangewidget = {'name':'Point Range', 'key':'pointrng', 'type':'rangegraph', 'limits':(0, 0), 'value':(0, 0), 'default':(0, 0),
                                       'graphwidget':outwid, 'action':self.updateSADTraceRef, 'fixedsize':128}
        except KeyError:
            rangewidget = {'name':'Point Range', 'key':'pointrng', 'type':'range', 'limits':(0, 0), 'value':(0, 0), 'default':(0, 0),
                                       'action':self.updateSADTraceRef, 'fixedsize':128}

        self.params = Parameter(name=self.getName(), type='group')
        self.params.addChildren([
            # {'name':'Open SAD Viewer', 'type':'action'},
            {'name':'SAD Ref From Captured', 'key':'sad', 'type':'group', 'children':[
                rangewidget,
                {'name':'Set SAD Reference from Current Trace', 'key':'docopyfromcapture', 'type':'action', 'action':self.copyFromCaptureTrace},
                {'name':'SAD Reference vs. Cursor', 'key':'sadrefcur', 'type':'int', 'value':0, 'limits':(-1, 100E6), 'readonly':True},
            ]},
            {'name':'SAD Threshold', 'type':'int', 'limits':(0, 100000), 'default':0, 'set':self.setThreshold, 'get':self.getThreshold}
        ])

    def dataChanged(self, data, offset):
        """ Called when data in the trace window has changed. Used to update the limits for the point selection dialog. """

        low = offset
        up = offset + len(data) - 1

        if self.oldlow != low or self.oldup != up:
            self.oldlow = low
            self.oldup = up
            self.findParam(['sad', 'pointrng']).setLimits((low, up))
            self.findParam(['sad', 'pointrng']).setValue((low, min(up, low + 128)))

        self.updateSADTraceRef()

    def getCaptueTraceRef(self):
        """ Get the reference data for SAD algorithm from the api trace window """

        try:
            waveformWidget = ResultsBase.registeredObjects["Trace Output Plot"]
        except KeyError:
            print "SAD Trigger: Not running in GUI mode, no data source"
            return [0.0]*128
        pstart = self.findParam(['sad', 'pointrng']).getValue()[0] - waveformWidget.lastStartOffset
        pend = self.findParam(['sad', 'pointrng']).getValue()[1] - waveformWidget.lastStartOffset
        data = waveformWidget.lastTraceData[pstart:pend]
        data = np.array(data)
        data = (data + 0.5) * 1024
        return data

    def copyFromCaptureTrace(self, _=None):
        """ Send reference data to hardware from the trace window """

        data = self.getCaptueTraceRef()

        if len(data) != 128:
            print "WARNING: Reference IS NOT 128 samples long, got %d"%len(data)

        self.sadref = data.copy()
        self.setRefWaveform(data)
        
    def updateSADTraceRef(self, ignored=None):
        """ Update the calculated SAD value parameter """

        data = self.getCaptueTraceRef()
        diff = data - self.sadref
        diff = sum(abs(diff))
        self.findParam(['sad','sadrefcur']).setValue(diff, ignoreReadonly=True)

    def reset(self):
        """ Reset the SAD hardware block. The ADC clock must be running! """

        data = self.oa.sendMessage(CODE_READ, sadcfgaddr, maxResp=4)
        data[0] = 0x01
        self.oa.sendMessage(CODE_WRITE, sadcfgaddr, data)

        if self.checkStatus():
            raise IOError("SAD Reset in progress, but SAD reports still running. Is ADC Clock stopped?")

        data[0] = 0x00
        self.oa.sendMessage(CODE_WRITE, sadcfgaddr, data)

    def start(self):
#.........这里部分代码省略.........
开发者ID:phonchi,项目名称:chipwhisperer,代码行数:103,代码来源:ChipWhispererSAD.py

示例5: HWInformation

# 需要导入模块: from chipwhisperer.common.utils.parameter import Parameter [as 别名]
# 或者: from chipwhisperer.common.utils.parameter.Parameter import addChildren [as 别名]
class HWInformation(Parameterized):
    _name = 'HW Information'

    def __init__(self, oaiface):
        self.oa = oaiface
        self.oa.hwInfo = self
        self.sysFreq = 0
        self.params = Parameter(name=self.getName(), type='group')
        self.params.addChildren([
            {'name': 'Version', 'type': 'str', 'get':self.versions, 'readonly':True},
            {'name': 'Synth Date', 'type': 'str', 'get':self.synthDate, 'readonly':True},
            {'name': 'System Freq', 'type': 'int', 'siPrefix':True, 'suffix': 'Hz', 'get':self.sysFrequency, 'readonly':True},
            {'name': 'Max Samples', 'type': 'int', 'get':self.maxSamples, 'readonly':True}
        ])

        self.vers = None

    def versions(self):
        result = self.oa.sendMessage(CODE_READ, ADDR_VERSIONS, maxResp=6)

        regver = result[0] & 0xff
        hwtype = result[1] >> 3
        hwver = result[1] & 0x07
        hwList = ["Default/Unknown", "LX9 MicroBoard", "SASEBO-W", "ChipWhisperer Rev2 LX25",
                  "Reserved?", "ZedBoard", "Papilio Pro", "SAKURA-G", "ChipWhisperer-Lite"]

        try:
            textType = hwList[hwtype]
        except:
            textType = "Invalid/Unknown"

        self.vers = (regver, hwtype, textType, hwver)

        #TODO: Temp fix for wrong HW reporting
        if hwtype == 1:
            self.sysFreq = 40E6

        return self.vers

    def synthDate(self):
        return "unknown"

    def maxSamples(self):
        return self.oa.hwMaxSamples

    def sysFrequency(self, force=False):
        if (self.sysFreq > 0) & (force == False):
            return self.sysFreq

        '''Return the system clock frequency in specific firmware version'''
        freq = 0x00000000

        temp = self.oa.sendMessage(CODE_READ, ADDR_SYSFREQ, maxResp=4)
        freq = freq | (temp[0] << 0)
        freq = freq | (temp[1] << 8)
        freq = freq | (temp[2] << 16)
        freq = freq | (temp[3] << 24)

        self.sysFreq = long(freq)
        return self.sysFreq

    def __del__(self):
        self.oa.hwInfo = None
开发者ID:FrankMuenzner,项目名称:chipwhisperer,代码行数:65,代码来源:_OpenADCInterface.py

示例6: ClockSettings

# 需要导入模块: from chipwhisperer.common.utils.parameter import Parameter [as 别名]
# 或者: from chipwhisperer.common.utils.parameter.Parameter import addChildren [as 别名]
class ClockSettings(Parameterized):
    _name = 'Clock Setup'
    readMask = [0x1f, 0xff, 0xff, 0xfd]

    def __init__(self, oaiface, hwinfo=None):
        self.oa = oaiface
        self._hwinfo = hwinfo
        self.params = Parameter(name=self.getName(), type='group')
        self.params.addChildren([
            {'name':'Refresh Status', 'type':'action', 'linked':[('ADC Clock', 'DCM Locked'), ('ADC Clock', 'ADC Freq'), ('CLKGEN Settings', 'DCM Locked'), 'Freq Counter'],
                     'help':'%namehdr%' +
                            'Update if the Digital Clock Manager (DCM) are "locked" and their operating frequency.'},
            {'name':'Reset DCMs', 'type':'action', 'action':self.resetDcms, 'linked':[('CLKGEN Settings', 'Multiply'), ('CLKGEN Settings', 'Divide')],
                      'help':'%namehdr%' +
                            'When the input frequency to the DCM blocks changes, it can cause them to become "unlocked". When they are "unlocked" they are NOT ' +
                            'generating a reliable output frequency. You must press the "Reset" button to cause them to re-lock. This is currently not automatically ' +
                            'done as during regular operation they shouldn\'t become unlocked.\n\nHowever every time you change the DCM block source, it will cause ' +
                            'the blocks to lose lock.'},

            {'name': 'ADC Clock', 'type':'group', 'children': [
                {'name': 'Source', 'type':'list', 'values':{"EXTCLK Direct":("extclk", 4, "clkgen"),
                                                            "EXTCLK x4 via DCM":("dcm", 4, "extclk"),
                                                            "EXTCLK x1 via DCM":("dcm", 1, "extclk"),
                                                            "CLKGEN x4 via DCM":("dcm", 4, "clkgen"),
                                                            "CLKGEN x1 via DCM":("dcm", 1, "clkgen")},
                          'set':self.setAdcSource, 'get':self.adcSource,
                          'help':'%namehdr%' +
                                'The ADC sample clock is generated from this source. Options are either an external input (which input set elsewhere) or an internal clock generator. Details of each option:\n\n' +
                                '=================== ====================== =================== ===============\n' +
                                ' Name                Description            Input Freq Range   Fine Phase Adj.\n' +
                                '=================== ====================== =================== ===============\n' +
                                ' EXCLK Direct       Connects sample clock     1-105 MHz            NO\n' +
                                '                    external pin directly.\n' +
                                ' EXTCLK xN via DCM  Takes external pin,       5-105 MHz (x1)       YES\n\n' +
                                '                    multiplies frequency      5-26.25 MHz (x4)        \n\n' +
                                '                    xN and feeds to ADC.  \n' + 
                                ' CLKGEN xN via DCM  Multiples CLKGEN by       5-105 MHz (x1)       YES\n\n' +
                                '                    xN and feeds to ADC.      5-26.25 MHz (x4)        \n\n' +
                                '=================== ====================== =================== ===============\n'},
                {'name': 'Phase Adjust', 'type':'int', 'limits':(-255, 255), 'set':self.setPhase, 'get':self.phase, 'help':'%namehdr%' +
                         'Makes small amount of adjustment to sampling point compared to the clock source. This can be used to improve the stability ' +
                         'of the measurement. Total phase adjustment range is < 5nS regardless of input frequency.'},
                {'name': 'ADC Freq', 'type': 'int', 'siPrefix':True, 'suffix': 'Hz', 'readonly':True, 'get':self.adcFrequency},
                {'name': 'DCM Locked', 'type':'bool', 'get':self.dcmADCLocked, 'readonly':True},
                {'name':'Reset ADC DCM', 'type':'action', 'action':lambda _ : self.resetDcms(True, False), 'linked':['Phase Adjust']},
            ]},
            {'name': 'Freq Counter', 'type': 'str', 'readonly':True, 'get':lambda: str(self.extFrequency()) + " Hz"},
            {'name': 'Freq Counter Src', 'type':'list', 'values':{'EXTCLK Input':0, 'CLKGEN Output':1}, 'set':self.setFreqSrc, 'get':self.freqSrc},
            {'name': 'CLKGEN Settings', 'type':'group', 'children': [
                {'name':'Input Source', 'type':'list', 'values':["system", "extclk"], 'set':self.setClkgenSrc, 'get':self.clkgenSrc},
                {'name':'Multiply', 'type':'int', 'limits':(2, 256), "default":2, 'set':self.setClkgenMul, 'get':self.clkgenMul, 'linked':['Current Frequency']},
                {'name':'Divide', 'type':'int', 'limits':(1, 256), 'set':self.setClkgenDiv, 'get':self.clkgenDiv, 'linked':['Current Frequency']},
                {'name':'Desired Frequency', 'type':'float', 'limits':(3.3E6, 200E6), 'default':0, 'step':1E6, 'siPrefix':True, 'suffix':'Hz',
                                            'set':self.autoMulDiv, 'get':self.getClkgen, 'linked':['Multiply', 'Divide']},
                {'name':'Current Frequency', 'type':'str', 'default':0, 'readonly':True,
                                            'get':lambda: str(self.getClkgen()) + " Hz"},
                {'name':'DCM Locked', 'type':'bool', 'default':False, 'get':self.clkgenLocked, 'readonly':True},
                {'name':'Reset CLKGEN DCM', 'type':'action', 'action':lambda _ : self.resetDcms(False, True), 'linked':['Multiply', 'Divide']},
            ]}
        ])
        self.params.refreshAllParameters()

    @setupSetParam("Freq Counter Src")
    def setFreqSrc(self, src):
        result = self.oa.sendMessage(CODE_READ, ADDR_ADVCLK, maxResp=4)
        result[3] = result[3] & ~(0x08)
        result[3] |= src << 3
        #print "%x"%result[3]
        self.oa.sendMessage(CODE_WRITE, ADDR_ADVCLK, result, readMask=self.readMask)

    def freqSrc(self):
        if self.oa is None:
            return 0
        result = self.oa.sendMessage(CODE_READ, ADDR_ADVCLK, maxResp=4)
        return ((result[3] & 0x08) >> 3)

    def getClkgen(self):
        return (self._hwinfo.sysFrequency() * self.clkgenMul()) / self.clkgenDiv()

    @setupSetParam(['CLKGEN Settings', 'Desired Frequency'])
    def autoMulDiv(self, freq):
        inpfreq = self._hwinfo.sysFrequency()
        sets = self.calculateClkGenMulDiv(freq, inpfreq)
        self.setClkgenMul(sets[0])
        self.setClkgenDiv(sets[1])
        self.resetDcms(False, True)

    def calculateClkGenMulDiv(self, freq, inpfreq=30E6):
        """Calculate Multiply & Divide settings based on input frequency"""

        #Max setting for divide is 60 (see datasheet)
        #Multiply is 2-256

        lowerror = 1E99
        best = (0, 0)

        # From datasheet, if input freq is < 52MHz limit max divide
        if inpfreq < 52E6:
            maxdiv = int(inpfreq / 0.5E6)
        else:
#.........这里部分代码省略.........
开发者ID:FrankMuenzner,项目名称:chipwhisperer,代码行数:103,代码来源:_OpenADCInterface.py

示例7: TriggerSettings

# 需要导入模块: from chipwhisperer.common.utils.parameter import Parameter [as 别名]
# 或者: from chipwhisperer.common.utils.parameter.Parameter import addChildren [as 别名]
class TriggerSettings(Parameterized):
    _name = 'Trigger Setup'

    def __init__(self, oaiface):
        self.oa = oaiface
        self.maxsamples = 0
        self.presamples_desired = 0
        self.presamples_actual = 0
        self.presampleTempMargin = 24
        self._timeout = 2

        self.params = Parameter(name=self.getName(), type='group')
        self.params.addChildren([
            {'name': 'Refresh Status', 'type':'action', 'linked':['Digital Pin State'], 'visible':False,
                     'help':'%namehdr%'+
                            'Refreshes the "Digital Pin State" status.'},
            {'name': 'Source', 'type': 'list', 'values':["digital", "analog"], 'set':self.setSource, 'get':self.source,
                     'help':'%namehdr%'+
                            'Selects if trigger system is based on digital signal (including internally generated), or an ADC level. Currently ' +
                            'only the digital trigger system is supported.'},
            {'name': 'Digital Pin State', 'type':'bool', 'readonly':True, 'get':self.extTriggerPin,
                     'help':'%namehdr%'+
                            'Gives the status of the digital signal being used as the trigger signal, either high or low.'},
            {'name': 'Mode', 'type':'list', 'values':["rising edge", "falling edge", "low", "high"], 'default':"low", 'set':self.setMode, 'get':self.mode,
                     'help':'%namehdr%'+
                            'When using a digital system, sets the trigger mode:\n\n'
                            '  =============== ==============================\n' +
                            '  Mode            Description\n' +
                            '  =============== ==============================\n' +
                            '  Rising Edge     Trigger on rising edge only.\n' +
                            '  Falling Edge    Trigger on falling edge only.\n' +
                            '  Low             Trigger when line is "low".\n' +
                            '  High            Trigger when line is "high".\n' +
                            '  =============== ==============================\n\n' +
                            'Note the "Trigger Mode" should be set to "Rising Edge" if using either the "SAD Trigger" or "IO Trigger" modes.'
            },
            {'name': 'Timeout (secs)', 'type':'float', 'step':1, 'limits':(0, 1E99), 'set':self.setTimeout, 'get':self.timeout,
                     'help':'%namehdr%'+
                            'If no trigger occurs in this many seconds, force the trigger.'},
            {'name': 'Offset', 'type':'int', 'limits':(0, 4294967294), 'set':self.setOffset, 'get':self.offset,
                     'help':'%namehdr%'+
                            'Delays this many samples after the trigger event before recording samples. Based on the ADC clock cycles. ' +
                            'If using a 4x mode for example, an offset of "1000" would mean we skip 250 cycles of the target device.'},
            {'name': 'Pre-Trigger Samples', 'type':'int', 'limits':(0, 1000000), 'set':self.setPresamples, 'get':self.presamples,
                     'help':'%namehdr%'+
                            'Record a certain number of samples before the main samples are captured. If "offset" is set to 0, this means ' +
                            'recording samples BEFORE the trigger event.'},
            {'name': 'Total Samples', 'type':'int', 'limits':(0, 1000000), 'set':self.setMaxSamples, 'get':self.maxSamples,
                     'help':'%namehdr%'+
                            'Total number of samples to record. Note the api system has an upper limit, and may have a practical lower limit (i.e.,' +
                            ' if this value is set too low the system may not api samples. Suggest to always set > 256 samples.'},
        ])

    @setupSetParam("Total Samples")
    def setMaxSamples(self, samples):
        self.maxsamples = samples
        self.oa.setMaxSamples(samples)

    def maxSamples(self,  cached=False):
        if self.oa is None:
            return 0

        if cached:
            return self.maxsamples
        else:
            return self.oa.maxSamples()

    @setupSetParam("Timeout (secs)")
    def setTimeout(self, timeout):
        self._timeout = timeout
        if self.oa:
            self.oa.setTimeout(timeout)

    def timeout(self):
        return self._timeout

    @setupSetParam("Offset")
    def setOffset(self,  offset):
        cmd = bytearray(4)
        cmd[0] = ((offset >> 0) & 0xFF)
        cmd[1] = ((offset >> 8) & 0xFF)
        cmd[2] = ((offset >> 16) & 0xFF)
        cmd[3] = ((offset >> 24) & 0xFF)
        self.oa.sendMessage(CODE_WRITE, ADDR_OFFSET, cmd)

    def offset(self):
        if self.oa is None:
            return 0

        cmd = self.oa.sendMessage(CODE_READ, ADDR_OFFSET, maxResp=4)
        offset = cmd[0]
        offset |= cmd[1] << 8
        offset |= cmd[2] << 16
        offset |= cmd[3] << 24
        return offset

    @setupSetParam("Pre-Trigger Samples")
    def setPresamples(self, samples):
        #enforce samples is multiple of 3
        samplesact = int(samples / 3)
#.........这里部分代码省略.........
开发者ID:FrankMuenzner,项目名称:chipwhisperer,代码行数:103,代码来源:_OpenADCInterface.py

示例8: GainSettings

# 需要导入模块: from chipwhisperer.common.utils.parameter import Parameter [as 别名]
# 或者: from chipwhisperer.common.utils.parameter.Parameter import addChildren [as 别名]
class GainSettings(Parameterized):
    _name = 'Gain Setting'

    def __init__(self, oaiface):
        self.oa = oaiface
        self.gainlow_cached = False
        self.gain_cached = 0
        self.params = Parameter(name=self.getName(), type='group')
        self.params.addChildren([
            {'name': 'Mode', 'type': 'list', 'values': {"high", "low"}, 'default': 'low', 'set':self.setMode, 'get':self.mode,
                     'help': '%namehdr%'+
                             'Sets the AD8331 Low Noise Amplifier into to "High" or "Low" gain mode. Low mode ranges from ' +
                             '-4.5dB to +43.5dB, and High mode ranges from +7.5dB to +55.5dB. Better performance is found ' +
                             'using the "High" gain mode typically.'},
            {'name': 'Setting', 'type': 'int', 'limits': (0, 78), 'default': 0, 'set':self.setGain, 'get':self.gain, 'linked':['Result'],
                     'help':'%namehdr%'+
                            'Sets the AD8331 gain value. This is a unitless number which ranges from 0 (minimum) to 78 (maximum).' +
                            ' The resulting gain in dB is given in the "calculated" output.'},
            {'name': 'Result', 'type': 'float', 'suffix':'dB', 'readonly':True, 'get':self.gainDB,
                     'help':'%namehdr%'+
                            'Gives the gain the AD8331 should have, based on the "High/Low" setting and the "gain setting".'},
        ])

    @setupSetParam("Mode")
    def setMode(self, gainmode):
        '''Set the gain Mode'''
        if gainmode == "high":
            self.oa.setSettings(self.oa.settings() | SETTINGS_GAIN_HIGH)
            self.gainlow_cached = False
        elif gainmode == "low":
            self.oa.setSettings(self.oa.settings() & ~SETTINGS_GAIN_HIGH)
            self.gainlow_cached = True
        else:
            raise ValueError, "Invalid Gain Mode, only 'low' or 'high' allowed"

    def mode(self):
        return "low" #TODO: Read it from hardware!

    @setupSetParam("Setting")
    def setGain(self, gain):
        '''Set the Gain range 0-78'''
        if (gain < 0) | (gain > 78):
            raise ValueError,  "Invalid Gain, range 0-78 Only"

        self.gain_cached = gain

        cmd = bytearray(1)
        cmd[0] = gain
        self.oa.sendMessage(CODE_WRITE, ADDR_GAIN, cmd)

    def gain(self, cached=False):
        if cached == False:
            self.gain_cached = self.oa.sendMessage(CODE_READ, ADDR_GAIN)[0]

        return self.gain_cached

    def gainDB(self):
        #GAIN (dB) = 50 (dB/V) * VGAIN - 6.5 dB, (HILO = LO)
        # GAIN (dB) = 50 (dB/V) * VGAIN + 5.5 dB, (HILO = HI)

        gainV = (float(self.gain_cached) / 256.0) * 3.3

        if self.gainlow_cached:
            gaindb = 50.0 * gainV - 6.5
        else:
            gaindb = 50.0 * gainV + 5.5

        return gaindb
开发者ID:FrankMuenzner,项目名称:chipwhisperer,代码行数:70,代码来源:_OpenADCInterface.py

示例9: ChipWhispererGlitch

# 需要导入模块: from chipwhisperer.common.utils.parameter import Parameter [as 别名]
# 或者: from chipwhisperer.common.utils.parameter.Parameter import addChildren [as 别名]
class ChipWhispererGlitch(Parameterized):
    """
    Drives the Glitch Module inside the ChipWhisperer Capture Hardware Rev2, or can be used to drive this FPGA
     module inserted into other systems.
    """
    CLKSOURCE0_BIT = 0b00000000
    CLKSOURCE1_BIT = 0b00000001
    CLKSOURCE_MASK = 0b00000011
    _name= 'Glitch Module'

    def __init__(self, cwtype, scope, oa):

        # Setup FPGA partial configuration dataZ
        self.prCon = pr.PartialReconfigConnection()
        self.oa = oa

        self.params = Parameter(name=self.getName(), type='group').register()
        self.params.addChildren([
            {'name':'Clock Source', 'type':'list', 'values':{'Target IO-IN':self.CLKSOURCE0_BIT, 'CLKGEN':self.CLKSOURCE1_BIT},'set':self.setGlitchClkSource, 'get':self.glitchClkSource},
            {'name':'Glitch Width (as % of period)', 'key':'width', 'type':'float', 'limits':(0, 100), 'step':0.39062, 'readonly':True, 'value':10, 'action':self.updatePartialReconfig},
            {'name':'Glitch Width (fine adjust)', 'key':'widthfine', 'type':'int', 'limits':(-255, 255), 'set':self.setGlitchWidthFine, 'get':self.getGlitchWidthFine},
            {'name':'Glitch Offset (as % of period)', 'key':'offset', 'type':'float', 'limits':(0, 100), 'step':0.39062, 'readonly':True, 'value':10, 'action':self.updatePartialReconfig},
            {'name':'Glitch Offset (fine adjust)', 'key':'offsetfine', 'type':'int', 'limits':(-255, 255), 'set':self.setGlitchOffsetFine, 'get':self.getGlitchOffsetFine},
            {'name':'Glitch Trigger', 'type':'list', 'values':{'Ext Trigger:Continous':1, 'Manual':0, 'Continuous':2, 'Ext Trigger:Single-Shot':3}, 'set':self.setGlitchTrigger, 'get':self.glitchTrigger},
            {'name':'Single-Shot Arm', 'type':'list', 'key':'ssarm', 'values':{'Before Scope Arm':1, 'After Scope Arm':2}, 'value':2},
            {'name':'Ext Trigger Offset', 'type':'int', 'range':(0, 50000000), 'set':self.setTriggerOffset, 'get':self.triggerOffset},
            {'name':'Repeat', 'type':'int', 'limits':(1,255), 'set':self.setNumGlitches, 'get':self.numGlitches},
            {'name':'Manual Trigger / Single-Shot Arm', 'type':'action', 'action': self.glitchManual},
            {'name':'Output Mode', 'type':'list', 'values':{'Clock XORd':0, 'Clock ORd':1, 'Glitch Only':2, 'Clock Only':3, 'Enable Only':4}, 'set':self.setGlitchType, 'get':self.glitchType},
            {'name':'Read Status', 'type':'action', 'action':self.checkLocked},
            {'name':'Reset DCM', 'type':'action', 'action':self.actionResetDCMs},
        ])

        # Check if we've got partial reconfiguration stuff for this scope
        try:
            if cwtype == "cwrev2" or cwtype == "cwcrev2":
                settingprefix = "cwcrev2"
                partialbasename = "s6lx25"
                self.glitchPR = pr.PartialReconfigDataMulti()
            elif cwtype == "cwlite":
                settingprefix = "cwlite"
                partialbasename = "cwlite"
                self.glitchPR = pr.PartialReconfigDataMulti()
            elif cwtype == "cw1200":
                settingprefix = "cw1200"
                partialbasename = "cw1200"
                self.glitchPR = pr.PartialReconfigDataMulti()
            else:
                raise ValueError("Invalid ChipWhisperer Mode: %s" % cwtype)

            if scope.cwFirmwareConfig.loader._release_mode != "debug":

                if scope.cwFirmwareConfig.loader._release_mode == "builtin":
                    filelike = scope.cwFirmwareConfig.loader._bsBuiltinData
                    zfile = zipfile.ZipFile(filelike)
                elif scope.cwFirmwareConfig.loader._release_mode == "zipfile":
                    fileloc = scope.cwFirmwareConfig.loader._bsZipLoc
                    if zipfile.is_zipfile(fileloc):
                        zfile = zipfile.ZipFile(fileloc, "r")
                    else:
                        logging.warning('Partial Reconfiguration DISABLED: no zip-file for FPGA')
                        zfile = None
                else:
                    logging.warning('Partial Reconfiguration DISABLED: no PR data for FPGA')
                    zfile = None
                    raise ValueError("Unknown FPGA mode: %s"%scope.cwFirmwareConfig.loader._release_mode)

                if zfile:
                    self.glitchPR.load(zfile.open("%s-glitchwidth.p" % partialbasename))
                    self.glitchPR.load(zfile.open("%s-glitchoffset.p" % partialbasename))
                    self.prEnabled = True
                else:
                    self.prEnabled = False
            else:
                logging.warning('Partial Reconfiguration DISABLED: Debug bitstream mode')
                self.prEnabled = False

        except IOError as e:
            logging.error(str(e))
            self.prEnabled = False
        except ValueError as e:
            logging.error(str(e))
            self.prEnabled = False
        except OSError as e:  # Also catches WindowsError
            logging.error(str(e))
            self.prEnabled = False

        if self.prEnabled:
            # Enable glitch width, check what we've got access to
            self.findParam('width').setReadonly(False)
            lim = (self.glitchPR.limitList[0][0] / 2.55, self.glitchPR.limitList[0][1] / 2.55)
            self.findParam('width').setLimits(lim)

            self.findParam('offset').setReadonly(False)
            lim = (self.glitchPR.limitList[1][0] / 2.55, self.glitchPR.limitList[1][1] / 2.55)
            self.findParam('offset').setLimits(lim)

        self.setOpenADC(oa)

    def setOpenADC(self, oa):
#.........这里部分代码省略.........
开发者ID:,项目名称:,代码行数:103,代码来源:

示例10: TraceContainer

# 需要导入模块: from chipwhisperer.common.utils.parameter import Parameter [as 别名]
# 或者: from chipwhisperer.common.utils.parameter.Parameter import addChildren [as 别名]
class TraceContainer(Parameterized, Plugin):
    """
    TraceContainer holds traces for the system to operate on. This can include both reading in traces for analysis, and
    writing traces to disk.
    
    This class is normally used as a base class for some specific format. For example the 'TraceFormatNative' class
    adds functions for reading/storing data in the 'native' ChipWhisperer format.
    """
    _name = "Trace Configuration"
    
    def __init__(self, parentParam=None, configfile=None):
        self.configfile = configfile
        self.fmt = None
        self.params = Parameter(name=self._name, type='group').register()
        self.params.addChildren([
                {'name':'Config File', 'key':'cfgfile', 'type':'str', 'readonly':True, 'value':''},
                {'name':'Format', 'key':'format', 'type':'str', 'readonly':True, 'value':''},
        ])
        self.clear()

    def clear(self):
        self.config = _cfgfile.TraceContainerConfig(configfile=self.configfile)
        self.textins = []
        self.textouts = []
        self.keylist = []
        self.knownkey = None
        self.dirty = False
        self.tracedtype = np.double
        self.traces = None
        self.tracehint = 1
        self.pointhint = 0
        self._numTraces = 0
        self._isloaded = False

    def setDirty(self, dirty):
        self.dirty = dirty
        
    def updateConfigData(self):
        return

    def numPoints(self):
        try:        
            return self.traces.shape[1]
        except:
            return 0
        
    def setTraceBuffer(self, tracebuffer):
        """Reuse a trace buffer allocated elsewhere"""
        self.traces = tracebuffer

    def setTraceHint(self, traces):
        self.tracehint = traces
        
    def setPointHint(self, points):
        self.pointhint = points

    def numTraces(self):
        cfint = int(self.config.attr("numTraces"))
        if cfint != self._numTraces:
            self._numTraces = max(cfint, self._numTraces)
        return self._numTraces

    def addTrace(self, trace, textin, textout, key, dtype=np.double):
        self.addWave(trace, dtype)
        self.addTextin(textin)
        self.addTextout(textout)
        self.addKey(key)

    def writeDataToConfig(self):
        self.config.setAttr("numTraces", self._numTraces)
        self.config.setAttr("numPoints", self.numPoints())      

    def addWave(self, trace, dtype=None):
        try:
            if self.traces is None:
                if dtype is None:
                    dtype = np.double
                self.tracedtype = dtype
                self.traces = np.zeros((self.tracehint, len(trace)), dtype=dtype)
                self.traces[self._numTraces][:] = trace
            else:
                # Check can fit this
                if self.traces.shape[0] <= self._numTraces:
                    if self._numTraces >= self.tracehint:
                        # Tracehint wrong - increase by 25
                        self.tracehint += 25

                    # Do a resize now to allocate more memory
                    self.traces.resize((self.tracehint, self.traces.shape[1]))

                #Validate traces fit - if too short warn & pad (prevents aborting long captures)
                pad = self.traces.shape[1] - len(trace)
                if pad > 0:
                    print "WARNING: Trace too short - length = %d"%len(trace)
                    print "         Padding with %d zero points"%pad
                    print " ***** This MAY SUGGEST DATA CORRUPTION *****"
                    trace.extend([0]*pad)

                self.traces[self._numTraces][:] = trace
        except MemoryError:
#.........这里部分代码省略.........
开发者ID:FrankMuenzner,项目名称:chipwhisperer,代码行数:103,代码来源:_base.py


注:本文中的chipwhisperer.common.utils.parameter.Parameter.addChildren方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。