def get_cw_type(sn=None): """ Gets the scope type of the connected ChipWhisperer If multiple connected, sn must be specified """ from chipwhisperer.hardware.naeusb.naeusb import NAEUSB from chipwhisperer.capture import scopes possible_ids = [0xace0, 0xace2, 0xace3] cwusb = NAEUSB() possible_sn = cwusb.get_possible_devices(idProduct=possible_ids) name = "" if len(possible_sn) == 0: raise OSError("USB Device not found. Did you connect it first?") if (len(possible_sn) > 1): if sn is None: serial_numbers = [] for d in possible_sn: serial_numbers.append("sn = {} ({})".format(str(d['sn']), str(d['product']))) raise Warning("Multiple chipwhisperers connected, but device and/or serial number not specified.\nDevices:\n{}".format(serial_numbers)) else: for d in possible_sn: if d['sn'] == sn: name = d['product'] else: name = possible_sn[0]['product'] #print(name) if (name == "ChipWhisperer Lite") or (name == "ChipWhisperer CW1200"): return scopes.OpenADC elif name == "ChipWhisperer Nano": return scopes.CWNano
class CWLiteUSB(object): _name = "ChipWisperer-Lite USB" def __init__(self): self._cwusb = NAEUSB() # Connect required modules up here self.fpga = FPGA(self._cwusb) self.xmega = XMEGAPDI(self._cwusb) self.avr = AVRISP(self._cwusb) self.usart = USART(self._cwusb) self.serialstm32f = STM32FSerial(cwserial=self.usart, cwapi=None) def get_possible_devices(self, idProduct): return self._cwusb.get_possible_devices(idProduct=idProduct) def con(self, *args, **kwargs): return self._cwusb.con(*args, **kwargs) def dis(self): pass def usbdev(self): return self._cwusb
class CWNano(ScopeTemplate, util.DisableNewAttr): """CWNano scope object. This class contains the public API for the CWNano hardware. It includes specific settings for each of these devices. To connect to one of these devices, the easiest method is:: import chipwhisperer as cw scope = cw.scope(type=scopes.CWNano) Some sane default settings can be set using:: scope.default_setup() For more help about scope settings, try help() on each of the ChipWhisperer scope submodules (scope.adc, scope.io, scope.glitch): * :attr:`scope.adc <.CWNano.adc>` * :attr:`scope.io <.CWNano.io>` * :attr:`scope.glitch <.CWNano.glitch>` * :meth:`scope.default_setup <.CWNano.default_setup>` * :meth:`scope.con <.CWNano.con>` * :meth:`scope.dis <.CWNano.dis>` * :meth:`scope.get_last_trace <.CWNano.get_last_trace>` * :meth:`scope.arm <.CWNano.arm>` * :meth:`scope.capture <.CWNano.capture>` """ _name = "ChipWhisperer Nano" REQ_ARM = 0x29 REQ_SAMPLES = 0x2A def __init__(self): ScopeTemplate.__init__(self) self._is_connected = False self._cwusb = NAEUSB() self.ser = self._cwusb self.scopetype = self self.dev = self self.xmega = XMEGAPDI(self._cwusb) self.avr = AVRISP(self._cwusb) self.usart = USART(self._cwusb) self.serialstm32f = STM32FSerial(cwserial=self.usart) self.serialstm32f.scope = self self.io = GPIOSettings(self._cwusb) self.adc = ADCSettings(self._cwusb) self.glitch = GlitchSettings(self._cwusb) self._timeout = 2 self._lasttrace = None self.disable_newattr() def default_setup(self): """ Sets up sane capture defaults for this scope * 7.5MHz ADC clock * 7.5MHz output clock * 5000 capture samples * tio1 = serial rx * tio2 = serial tx * glitch module off .. versionadded:: 5.1 Added default setup for CWNano """ self.adc.clk_freq = 7.5E6 self.io.clkout = 7.5E6 self.adc.samples = 5000 self.io.tio1 = "serial_rx" self.io.tio2 = "serial_tx" self.glitch.repeat = 0 def getCurrentScope(self): return self def _getNAEUSB(self): return self._cwusb @property def sn(self): return self._cwusb.snum @property def latest_fw(self): from chipwhisperer.hardware.firmware.cwnano import fwver return {"major": fwver[0], "minor": fwver[1]} @property def fw_version(self): a = self._cwusb.readFwVersion() return {"major": a[0], "minor": a[1], "debug": a[2]} def _con(self, sn=None): try: possible_sn = self._cwusb.get_possible_devices(idProduct=[0xACE0]) serial_numbers = [] if len(possible_sn) > 1: if sn is None: for d in possible_sn: serial_numbers.append("sn = {} ({})".format(str(d['sn']), str(d['product']))) raise Warning("Multiple ChipWhisperers detected. Please specify device from the following list using cw.scope(sn=<SN>): \n{}".format(serial_numbers)) else: sn = None found_id = self._cwusb.con(idProduct=[0xACE0], serial_number=sn) except (IOError, ValueError): raise Warning("Could not connect to cwnano. It may have been disconnected, is in an error state, or is being used by another tool.") self.disable_newattr() self._is_connected = True return True def _dis(self): self.enable_newattr() self.usbdev().close() self._is_connected = False return True def arm(self): """Arm the ADC, the trigger will be GPIO4 rising edge (fixed trigger).""" with DelayedKeyboardInterrupt(): if self.connectStatus is False: raise Warning("Scope \"" + self.getName() + "\" is not connected. Connect it first...") self._cwusb.sendCtrl(self.REQ_ARM, 1) def capture(self): """Raises IOError if unknown failure, returns 'True' if timeout, 'False' if no timeout""" with DelayedKeyboardInterrupt(): starttime = datetime.datetime.now() while self._cwusb.readCtrl(self.REQ_ARM, dlen=1)[0] == 0: # Wait for a moment before re-running the loop time.sleep(0.001) diff = datetime.datetime.now() - starttime # If we've timed out, don't wait any longer for a trigger if (diff.total_seconds() > self._timeout): logging.warning('Timeout in cwnano capture()') return True self._lasttrace = self._cwusb.cmdReadMem(0, self.adc.samples) # can just keep rerunning this until it works I think i = 0 while len(self._lasttrace) < self.adc.samples: logging.debug("couldn't read ADC data from Nano, retrying...") self._lasttrace = self._cwusb.cmdReadMem(0, self.adc.samples) i+= 1 if i > 20: logging.warning("Couldn't read trace data back from Nano") return True self._lasttrace = np.array(self._lasttrace) / 256.0 - 0.5 #self.newDataReceived(0, self._lasttrace, 0, self.adc.clk_freq) return False def get_last_trace(self): """Return the last trace captured with this scope. """ return self._lasttrace getLastTrace = camel_case_deprecated(get_last_trace) def _dict_repr(self): dict = OrderedDict() dict['fw_version'] = self.fw_version dict['io'] = self.io._dict_repr() dict['adc'] = self.adc._dict_repr() dict['glitch'] = self.glitch._dict_repr() return dict def __repr__(self): # Add some extra information about ChipWhisperer type here if self._is_connected: ret = "ChipWhisperer Nano Device\n" return ret + dict_to_str(self._dict_repr()) else: ret = "ChipWhisperer Nano device (disconnected)" return ret def __str__(self): return self.__repr__() def get_possible_devices(self, idProduct): return self._cwusb.get_possible_devices(idProduct=idProduct) def usbdev(self): return self._cwusb
class CWLiteUSB(Parameterized): _name = "ChipWisperer-Lite USB" def __init__(self): self._cwusb = NAEUSB() # Connect required modules up here self.fpga = FPGA(self._cwusb) self.xmega = XMEGAPDI(self._cwusb) self.avr = AVRISP(self._cwusb) self.usart = USART(self._cwusb) self.serialstm32f = STM32FSerial(cwserial=self.usart, cwapi=CWCoreAPI.getInstance()) self.getParams().addChildren([{ 'name': "CW-Lite XMEGA Programmer", 'tip': "Open XMEGA Programmer (ChipWhisperer-Lite Only)", 'type': "menu", "action": lambda _: self.getCwliteXMEGA().show() }, { 'name': "CW-Lite AVR Programmer", 'tip': "Open AVR Programmer (ChipWhisperer-Lite Only)", 'type': "menu", "action": lambda _: self.getCwliteAVR().show() }, { 'name': 'Serial STM32F Programmer', 'tip': "Open STM32F Programmer (Serial/ChipWhisperer)", 'type': "menu", "action": lambda _: self.getSerialSTM32F().show() }]) def get_possible_devices(self, idProduct): return self._cwusb.get_possible_devices(idProduct=idProduct) def con(self, *args, **kwargs): return self._cwusb.con(*args, **kwargs) # def __del__(self): # print "here" def dis(self): if self.params is not None: self.getParams().delete() self.params = None # gc.collect() # print sys.getrefcount(self) # print gc.get_referrers(self) def usbdev(self): return self._cwusb def getCwliteXMEGA(self): if not hasattr(self, 'cwliteXMEGA'): self.cwliteXMEGA = XMEGAProgrammerDialog() return self.cwliteXMEGA def getCwliteAVR(self): if not hasattr(self, 'cwliteAVR'): self.cwliteAVR = AVRProgrammerDialog() return self.cwliteAVR def getSerialSTM32F(self): if not hasattr(self, 'serialSTM32F'): self.serialSTM32F = STM32FProgrammerDialog() return self.serialSTM32F
class CWNano(ScopeTemplate, Plugin, util.DisableNewAttr): """CWNano scope object. This class contains the public API for the CWNano hardware. It includes specific settings for each of these devices. To connect to one of these devices, the easiest method is This code will automatically detect an attached ChipWhisperer device and connect to it. For more help about scope settings, try help() on each of the ChipWhisperer scope submodules: scope.adc scope.io scope.glitch """ _name = "ChipWhisperer Nano" REQ_ARM = 0x29 REQ_SAMPLES = 0x2A def __init__(self): ScopeTemplate.__init__(self) self._is_connected = False self.params.init() self._cwusb = NAEUSB() self.ser = self._cwusb self.scopetype = self self.dev = self self.xmega = XMEGAPDI(self._cwusb) self.avr = AVRISP(self._cwusb) self.usart = USART(self._cwusb) self.serialstm32f = STM32FSerial(cwserial=self.usart) self.serialstm32f.scope = self self.io = GPIOSettings(self._cwusb) self.adc = ADCSettings(self._cwusb) self.glitch = GlitchSettings(self._cwusb) self._timeout = 2 self._lasttrace = None self.getParams().addChildren([ {'name':"CW-Lite XMEGA Programmer", 'tip':"Open XMEGA Programmer (ChipWhisperer-Lite Only)", 'type':"menu", "action":lambda _:self.getCwliteXMEGA().show()}, {'name':"CW-Lite AVR Programmer", 'tip':"Open AVR Programmer (ChipWhisperer-Lite Only)", 'type':"menu", "action":lambda _:self.getCwliteAVR().show()}, {'name':'Serial STM32F Programmer', 'tip':"Open STM32F Programmer (Serial/ChipWhisperer)", 'type':"menu", "action":lambda _:self.getSerialSTM32F().show()} ]) self.disable_newattr() def getCurrentScope(self): return self def _con(self): self._cwusb.con(idProduct=[0xACE0]) self.disable_newattr() self._is_connected = True return True def _dis(self): self.enable_newattr() self._is_connected = False return True def arm(self): """Arm the ADC, the trigger will be GPIO4 rising edge (fixed trigger).""" if self.connectStatus.value() is False: raise Warning("Scope \"" + self.getName() + "\" is not connected. Connect it first...") self._cwusb.sendCtrl(self.REQ_ARM, 1) def capture(self): """Raises IOError if unknown failure, returns 'True' if timeout, 'False' if no timeout""" starttime = datetime.datetime.now() while self._cwusb.readCtrl(self.REQ_ARM, dlen=1)[0] == 0: # Wait for a moment before re-running the loop time.sleep(0.05) diff = datetime.datetime.now() - starttime # If we've timed out, don't wait any longer for a trigger if (diff.total_seconds() > self._timeout): logging.warning('Timeout in cwnano capture()') return True self._lasttrace = self._cwusb.cmdReadMem(0, self.adc.samples) self._lasttrace = np.array(self._lasttrace) / 256.0 - 0.5 self.newDataReceived(0, self._lasttrace, 0, self.adc.clk_freq) return False def getLastTrace(self): """Return the last trace captured with this scope. """ return self._lasttrace def _dict_repr(self): dict = OrderedDict() dict['io'] = self.io._dict_repr() dict['adc'] = self.adc._dict_repr() dict['glitch'] = self.glitch._dict_repr() return dict def __repr__(self): # Add some extra information about ChipWhisperer type here if self._is_connected: ret = "ChipWhisperer Nano Device\n" return ret + dict_to_str(self._dict_repr()) else: ret = "ChipWhisperer Nano device (disconnected)" return ret def __str__(self): return self.__repr__() def get_possible_devices(self, idProduct): return self._cwusb.get_possible_devices(idProduct=idProduct) def usbdev(self): return self._cwusb def getCwliteXMEGA(self): if not hasattr(self, 'cwliteXMEGA'): self.enable_newattr() self.cwliteXMEGA = XMEGAProgrammerDialog() self.disable_newattr() return self.cwliteXMEGA def getCwliteAVR(self): if not hasattr(self, 'cwliteAVR'): self.enable_newattr() self.cwliteAVR = AVRProgrammerDialog() self.disable_newattr() return self.cwliteAVR def getSerialSTM32F(self): if not hasattr(self, 'serialSTM32F'): self.enable_newattr() self.serialSTM32F = STM32FProgrammerDialog() self.disable_newattr() return self.serialSTM32F