def __init__(self, device, serial=None, interface='swd', speed='auto', verbose=False): self._device = device self._serial = serial self._interface = interface self._speed = speed self._verbose = verbose jlink_path = os.path.realpath( os.path.join(jlink_plugin_path, "jlink", "libjlinkarm.so")) print(jlink_path) if os.path.exists(jlink_path) == False: raise JLinkException(message=f"{jlink_path}: file not found") lib = pylink.library.Library(jlink_path) if verbose == True: self._jlink = pylink.JLink(lib, log=sys.stdout.write, detailed_log=sys.stdout.write) else: self._jlink = pylink.JLink(lib) self._jlink.disable_dialog_boxes()
def initAll(): print("Configuring ChipWhisperer") global scope, target,cs,jlink scope = cw.scope() target = cw.target(scope) scope.adc.samples = 5000 scope.adc.offset = 0 scope.adc.basic_mode = "rising_edge" scope.clock.clkgen_freq = 8000000 # 120000000 # 737060 scope.clock.adc_src = "clkgen_x1" scope.trigger.triggers = "tio4" scope.io.hs2 = "glitch" scope.glitch.clk_src = "clkgen" scope.glitch.output = "glitch_only" scope.io.glitch_lp = False scope.io.glitch_hp = True scope.glitch.trigger_src = 'ext_single' print("Configuring JLink") if len(sys.argv) > 1: lib = pylink.library.Library(sys.argv[1]) jlink = pylink.JLink(lib) else: jlink = pylink.JLink() jlink.open() print("Configuring ChipShouter") cs = chipshouter.ChipSHOUTER("/dev/ttyUSB0") if cs.armed == True: cs.armed = False cs.reset_config = True cs.voltage = 250 cs.clr_armed = True
def jl_test(): logging.basicConfig() time.sleep(1) jlink = pylink.JLink() #jlink.reset() jlink.open('59401308') SetTif = jlink.set_tif(pylink.enums.JLinkInterfaces.SWD) if SetTif: print('Connecting CPU...') jlink.connect('STM32F103ZE') jlink.reset() FlashReuslt = jlink.flash_file(r'D:\1\JP6_CPU_TEST.hex', 0) if FlashReuslt == 0: print('Flash Success') IO.IOExtInit(0x27) IO.IOExtChAWrite(0x27, 0x00) else: print('Flash Failed') else: print('Connecting Failed...') jlink.close() jlink.close()
def main(jlink_serial, device): """Main function. Args: jlink_serial (str): the J-Link serial number device (str): the target CPU Returns: ``None`` Raises: JLinkException: on error """ buf = StringIO.StringIO() jlink = pylink.JLink(log=buf.write, detailed_log=buf.write) jlink.open(serial_no=jlink_serial) jlink.set_tif(pylink.enums.JLinkInterfaces.SWD) jlink.connect(device, verbose=True) # Figure out our original endianess first. big_endian = jlink.set_little_endian() if big_endian: jlink.set_big_endian() print('Target Endian Mode: %s Endian' % ('Big' if big_endian else 'Little'))
def __init__(self, device, port=None, baudrate=115200, interface=pylink.enums.JLinkInterfaces.SWD, speed=12000): # 目标芯片名字 self.device = device # 调试口 self._interface = interface # 连接速率 self._speed = speed # segger rtt上下通道缓存大小 self.upbuffer_size = 1024 self.downbuffer_size = 512 # 串口参数 self.port = port self.baudrate = baudrate # 线程 self.rtt2uart = None self.uart2rtt = None self.thread_switch = False try: self.jlink = pylink.JLink() except: logger.error('Find jlink dll failed', exc_info=True) raise try: self.serial = serial.Serial() except: logger.error('Creat serial object failed', exc_info=True) raise
def _try_connect(self, connection_string): """If the connecton string settings are different, try and connect to an attached device""" if self._parse_conn_string(connection_string): self._trigger_callback('on_disconnect', self.id, self._connection_id) self.stop_sync() if self._mux_func is not None: self._mux_func(self._channel) if self._device_info is None: raise ArgumentError("Missing device name or alias, specify using device=name in port string or -c device=name in connect_direct or debug command", known_devices=[x for x in viewkeys(DEVICE_ALIASES)]) try: self.jlink = pylink.JLink() self.jlink.open(serial_no=self._jlink_serial) self.jlink.set_tif(pylink.enums.JLinkInterfaces.SWD) self.jlink.connect(self._device_info.jlink_name) self.jlink.set_little_endian() except pylink.errors.JLinkException as exc: if exc.code == exc.VCC_FAILURE: raise HardwareError("No target power detected", code=exc.code, suggestion="Check jlink connection and power wiring") raise except: raise self._control_thread = JLinkControlThread(self.jlink) self._control_thread.start() self.set_config('probe_required', True) self.set_config('probe_supported', True)
def main(jlink_serial, device): """Prints the core's information. Args: jlink_serial (str): the J-Link serial number device (str): the target CPU Returns: Always returns ``0``. Raises: JLinkException: on error """ buf = StringIO.StringIO() jlink = pylink.JLink(log=buf.write, detailed_log=buf.write) jlink.open(serial_no=jlink_serial) # Use Serial Wire Debug as the target interface. jlink.set_tif(pylink.enums.JLinkInterfaces.SWD) jlink.connect(device, verbose=True) sys.stdout.write('ARM Id: %d\n' % jlink.core_id()) sys.stdout.write('CPU Id: %d\n' % jlink.core_cpu()) sys.stdout.write('Core Name: %s\n' % jlink.core_name()) sys.stdout.write('Device Family: %d\n' % jlink.device_family())
def slot_btn_connect_jlink(self): try: self.jlink = pylink.JLink() jid = '69661582' self.jlink.open() self.jlink.set_tif(pylink.enums.JLinkInterfaces.SWD) except Exception as ext: QMessageBox.warning(self, "连接jlink错误", str(ext), QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes) return try: self.jlink.connect('STM32F429II') if self.jlink.target_connected() is True: self.ui.pushButton_down_firm.setEnabled(True) self.ui.pushButton_connect_ap.setText('已连接') else: QMessageBox.warning(self, "连接目标板错误0", 'jlink 已经链接成功,但是目标板连接失败:', QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes) return except Exception as ext: QMessageBox.warning(self, "连接目标板错误1", 'jlink 已经链接成功,但是目标板连接失败,\nExcept:' + str(ext), QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes) return
def main(target_device, block_address=None): """Creates an interactive terminal to the target via RTT. The main loop opens a connection to the JLink, and then connects to the target device. RTT is started, the number of buffers is presented, and then two worker threads are spawned: one for read, and one for write. The main loops sleeps until the JLink is either disconnected or the user hits ctrl-c. Args: target_device (string): The target CPU to connect to. block_address (int): optional address pointing to start of RTT block. Returns: Always returns ``0`` or a JLinkException. Raises: JLinkException on error. """ jlink = pylink.JLink() print("connecting to JLink...") jlink.open() print("connecting to %s..." % target_device) jlink.set_tif(pylink.enums.JLinkInterfaces.SWD) jlink.connect(target_device) print("connected, starting RTT...") jlink.rtt_start(block_address) while True: try: num_up = jlink.rtt_get_num_up_buffers() num_down = jlink.rtt_get_num_down_buffers() print("RTT started, %d up bufs, %d down bufs." % (num_up, num_down)) break except pylink.errors.JLinkRTTException: time.sleep(0.1) print("up channels:") for buf_index in range(jlink.rtt_get_num_up_buffers()): buf = jlink.rtt_get_buf_descriptor(buf_index, True) print(" %d: name = %r, size = %d bytes, flags = %d" % (buf.BufferIndex, buf.name, buf.SizeOfBuffer, buf.Flags)) print("down channels:") for buf_index in range(jlink.rtt_get_num_down_buffers()): buf = jlink.rtt_get_buf_descriptor(buf_index, False) print(" %d: name = %r, size = %d bytes, flags = %d" % (buf.BufferIndex, buf.name, buf.SizeOfBuffer, buf.Flags)) try: thread.start_new_thread(read_rtt, (jlink, )) thread.start_new_thread(write_rtt, (jlink, )) while jlink.connected(): time.sleep(1) print("JLink disconnected, exiting...") except KeyboardInterrupt: print("ctrl-c detected, exiting...") pass
def jl_product(): global flash_result_product logging.basicConfig() time.sleep(1) jlink = pylink.JLink() #jlink.reset() jlink.open('59401308') SetTif = jlink.set_tif(pylink.enums.JLinkInterfaces.SWD) if SetTif: print('Connecting CPU...') jlink.connect('STM32F103ZE') jlink.reset() FlashReuslt = jlink.flash_file(r'D:\1\JP6_CPU_TEST.hex', 0) if FlashReuslt == 0: flash_result_product = 1 print('Flash Success') else: flash_result_product = -1 print('Flash Failed') else: print('Connecting Failed...') jlink.close() jlink.close()
def jlink_f(): jlink = pylink.JLink() jlink.open('69661582') jlink.set_tif(pylink.enums.JLinkInterfaces.SWD) print(jlink.connect('STM32F429II')) print(jlink.core_id()) #print(jlink.device_family()) print(jlink.target_connected()) #print(jlink.erase()) print( jlink.flash_file('C:\work\etc_project_new_board_v2\MDK-ARM\etc_n1.bin', 0X08004000)) # jlink.reset() # jlink.close() firm_data = open('C:\work\etc_project_new_board_v2\MDK-ARM\etc_n1.bin', 'rb').read() read_firm = jlink.code_memory_read(0X08004000, len(firm_data)) print(operator.eq(firm_data, bytes(read_firm))) jlink.reset() jlink.close()
def run(self, args): """Runs the emulator command. Args: self (EmulatorCommand): the ``EmulatorCommand`` instance args (Namespace): arguments to parse Returns: ``None`` """ jlink = pylink.JLink() if args.test: if jlink.test(): print('Self-test succeeded.') else: print('Self-test failed.') elif args.list is None or args.list in ['usb', 'ip']: host = pylink.JLinkHost.USB_OR_IP if args.list == 'usb': host = pylink.JLinkHost.USB elif args.list == 'ip': host = pylink.JLinkHost.IP emulators = jlink.connected_emulators(host) for (index, emulator) in enumerate(emulators): if index > 0: print('') print('Product Name: %s' % emulator.acProduct.decode()) print('Serial Number: %s' % emulator.SerialNumber) usb = bool(emulator.Connection) if not usb: print('Nickname: %s' % emulator.acNickname.decode()) print('Firmware: %s' % emulator.acFWString.decode()) print('Connection: %s' % ('USB' if usb else 'IP')) if not usb: print('IP Address: %s' % emulator.aIPAddr) elif args.supported is not None: device = args.supported[0] try: index = jlink.get_device_index(device) except pylink.errors.JLinkException: print('%s is not supported :(' % device) return None found_device = jlink.supported_device(index) print('Device Name: %s' % device) print('Core ID: %s' % found_device.CoreId) print('Flash Address: %s' % found_device.FlashAddr) print('Flash Size: %s bytes' % found_device.FlashSize) print('RAM Address: %s' % found_device.RAMAddr) print('RAM Size: %s bytes' % found_device.RAMSize) print('Manufacturer: %s' % found_device.manufacturer) return None
def _connect_jlink_blocking(jlink_serial, jlink_name): jlink = pylink.JLink() jlink.open(jlink_serial) jlink.set_tif(pylink.enums.JLinkInterfaces.SWD) jlink.connect(jlink_name) jlink.set_little_endian() return jlink
def scan(self): jlink = [] info = pylink.JLink(lib=pylink.library.Library( dllpath=self.jlink_dll_path)).connected_emulators( host=pylink.enums.JLinkHost.USB) for item in info: logging.info(item) jlink.extend(re.findall(r'\d+\.?\d*', str(item))) return jlink
def connect(self): if pylink is None: raise NotImplementedError( "pylink module did not import - try installing it") jlink = pylink.JLink() jlink.open() jlink.set_tif(pylink.enums.JLinkInterfaces.SWD) jlink.connect('STM32F405VG', speed=4000) self.jlink = jlink
def _get_jlink(cls): # TypeError is raised by pylink if the JLink DLL cannot be found. try: return pylink.JLink( log=TRACE.info, detailed_log=TRACE.debug, error=TRACE.error, warn=TRACE.warn, ) except TypeError: return None
def get_jlink_lib(cls) -> pylink.JLink: """Get J-Link object. :return: The J-Link Object :raises DebugProbeError: The J-Link object get function failed. """ try: return pylink.JLink(log=JLINK_LOGGER.info, detailed_log=JLINK_LOGGER.debug, error=JLINK_LOGGER.error, warn=JLINK_LOGGER.warn) except TypeError: raise DebugProbeError("Cannot open Jlink DLL")
def __init__(self, device, jlink_serial=None, jlink_logfile=None, printer=None, prompt=""): """device: The JLink device to connect""" self.device = device self.serial = jlink_serial self.jlink = pylink.JLink() self.jlink_logfile = jlink_logfile self.printer = printer self.prompt = prompt self.print_read_time = time.time() self.buffer = bytearray()
def start_seggr_log(running, folder, target_device): max_lines_csv = 100000 jlink = pylink.JLink() line_count = 0 while (running.is_set()): logging.info("connecting to JLink...") jlink.open() logging.info("connecting to %s..." % target_device) jlink.set_tif(pylink.enums.JLinkInterfaces.SWD) jlink.connect(target_device) logging.info("connected, starting RTT...") jlink.rtt_start() while True: try: num_up = jlink.rtt_get_num_up_buffers() num_down = jlink.rtt_get_num_down_buffers() logging.info("RTT started, %d up bufs, %d down bufs." % (num_up, num_down)) break except pylink.errors.JLinkRTTException: time.sleep(0.1) try: character_buffer = deque() while jlink.connected() and running.is_set(): terminal_bytes = jlink.rtt_read(0, 1024) if terminal_bytes: characters = map(chr, terminal_bytes) character_buffer.extend(characters) while(1): try: end_line = character_buffer.index('\n') line_count += 1 minutes_per_csv = 10 csv_timestamp = int(int(time.time() / (60 * minutes_per_csv)) * 60 * minutes_per_csv * 1000) file = os.path.join(folder, "stream-{}.csv".format(csv_timestamp)) with open(file, "a") as stream_file: stream_file.write("{}, ".format(str(int(time.time() * 1000)))) for char_index in range(0,end_line+1): stream_file.write(character_buffer.popleft()) except ValueError as error: # No newlines found yet break # sys.stdout.flush() pass # sys.stdout.write("".join(map(chr, terminal_bytes))) # sys.stdout.flush() time.sleep(0.01) logging.info("JLink disconnected, exiting...") except Exception: logging.error("something with warp went wrong :'(")
def __init__(self, device_name: str, serial_number: int, platform_name: str): """Initializes an instance of the FlashBuildJLink capability. Args: device_name: Device name used for logging. serial_number: Device serial number. platform_name: The target device's platform name. """ super().__init__(device_name=device_name) self._serial_number = serial_number self._platform_name = platform_name self._jlink = pylink.JLink()
def strace(device, trace_address, breakpoint_address): """Implements simple trace using the STrace API. Args: device (str): the device to connect to trace_address (int): address to begin tracing from breakpoint_address (int): address to breakpoint at Returns: ``None`` """ jlink = pylink.JLink() jlink.open() # Do the initial connection sequence. jlink.power_on() jlink.set_tif(pylink.JLinkInterfaces.SWD) jlink.connect(device) jlink.reset() # Clear any breakpoints that may exist as of now. jlink.breakpoint_clear_all() # Start the simple trace. op = pylink.JLinkStraceOperation.TRACE_START jlink.strace_clear_all() jlink.strace_start() # Set the breakpoint and trace events, then restart the CPU so that it # will execute. bphandle = jlink.breakpoint_set(breakpoint_address, thumb=True) trhandle = jlink.strace_code_fetch_event(op, address=trace_address) jlink.restart() time.sleep(1) # Run until the CPU halts due to the breakpoint being hit. while True: if jlink.halted(): break # Print out all instructions that were captured by the trace. while True: instructions = jlink.strace_read(1) if len(instructions) == 0: break instruction = instructions[0] print(jlink.disassemble_instruction(instruction)) jlink.power_off() jlink.close()
def flash(): jlink = pylink.JLink() #连接JLINK jlink.open(59400743) #设置接口 jlink.set_tif(pylink.enums.JLinkInterfaces.SWD) #连接芯片 jlink.connect('GD32F107RC', 'auto') #刷写文件 jlink.flash_file(file, 0x8000000) # jlink.restart() #关闭连接 jlink.close()
def open(self): """ initialize the flasher """ lib = self.lib if lib is not None: lib = pathlib(self.lib).resolve() if lib.exists(): lib = pylink.Library(lib=lib) else: logging.warn( f"No library file found at {lib}, using system default") lib = None self.jlink = pylink.JLink(lib=lib) self.jlink.connect(self.chip_name, self.speed, self.verbose) logging.debug(f"JLink connected to device")
def main(): serial_no = "158001796" chip_name = "STM32F103RE" path = "test.txt" sampleData = readData(path) print("data transferred") jlink = pylink.JLink() jlink.open(serial_no) print("jlink open") jlink.connect(chip_name, verbose=True) print("connected") wroteBytes = jlink.memory_write(addr=0x08060000, data=sampleData, nbits=32) #0x0807FFFF print(str(wroteBytes) + " of data written") jlink.reset()
def __init__(self): Hub.__init__(self, "JlinkHub") try: import pylink self.link = pylink.JLink() self.pylink = pylink emulators = self.link.connected_emulators() portlist = [str(d.SerialNumber) for d in emulators] for serialno in portlist: name = 'jlink-' + serialno if not self.get_port(name): port = JlinkPort(serialno, name, self) self.add_port(port) except: print('J-Link is not available')
def if_init(self, device, rate, chiptype='bl60x'): if self._inited == False: sub_module = __import__(('lib.' + chiptype), fromlist=[chiptype]) self._jlink_shake_hand_addr = sub_module.jlink_load_cfg.jlink_shake_hand_addr self._jlink_data_addr = sub_module.jlink_load_cfg.jlink_data_addr if sys.platform == 'win32': obj_dll = pylink.Library(dllpath=path_dll) self._jlink = pylink.JLink(lib=obj_dll) else: self._jlink = pylink.JLink() if device is not None and device.lower().find( 'com') == -1 and device.lower().find('tty') == -1: bflb_utils.printf(device) self._jlink.open(serial_no=(int(device))) else: self._jlink.open() tif_set = sub_module.jlink_load_cfg.jlink_set_tif self._jlink.set_tif(tif_set) self._speed = rate core_type = sub_module.jlink_load_cfg.jlink_core_type self._jlink.connect(core_type, rate) self._inited = True self._chiptype = chiptype self._jlink_run_addr = sub_module.jlink_load_cfg.jlink_run_addr
def __init__(self, serial="12345678", device="ARM7", avatar=None, origin=None): self._shutdown = Event() self.avatar = avatar self.origin = origin self.jlink = pylink.JLink() self.jlink.open(serial) self.log = logging.getLogger('%s.%s' % (origin.log.name, self.__class__.__name__) ) if origin else \ logging.getLogger(self.__class__.__name__) Thread.__init__(self) self.connect(device=device)
def main(target_device): """Creates an interactive terminal to the target via RTT. The main loop opens a connection to the JLink, and then connects to the target device. RTT is started, the number of buffers is presented, and then two worker threads are spawned: one for read, and one for write. The main loops sleeps until the JLink is either disconnected or the user hits ctrl-c. Args: target_device (string): The target CPU to connect to. Returns: Always returns ``0`` or a JLinkException. Raises: JLinkException on error. """ jlink = pylink.JLink() print("connecting to JLink...") jlink.open() print("connecting to %s..." % target_device) jlink.set_tif(pylink.enums.JLinkInterfaces.SWD) jlink.connect(target_device) print("connected, starting RTT...") jlink.rtt_start() while True: try: num_up = jlink.rtt_get_num_up_buffers() num_down = jlink.rtt_get_num_down_buffers() print("RTT started, %d up bufs, %d down bufs." % (num_up, num_down)) break except pylink.errors.JLinkRTTException: time.sleep(0.1) try: thread.start_new_thread(read_rtt, (jlink, )) thread.start_new_thread(write_rtt, (jlink, )) while jlink.connected(): time.sleep(1) print("JLink disconnected, exiting...") except KeyboardInterrupt: print("ctrl-c detected, exiting...") pass
def connect(self, sn, chip='Cortex-M4', interface='SWD'): self.__jlink = pylink.JLink(lib=pylink.library.Library( dllpath=self.jlink_dll_path)) self.__jlink.exec_command('DisableAutoUpdateFW') self.__jlink.disable_dialog_boxes() self.__jlink.open(sn) logging.debug('JLink S/N {}'.format(sn)) if interface == 'JTAG': self.__jlink.set_tif(pylink.enums.JLinkInterfaces.JTAG) else: self.__jlink.set_tif(pylink.enums.JLinkInterfaces.SWD) self.__jlink.connect(chip, speed=4000, verbose=True) self.__jlink.set_reset_strategy( pylink.enums.JLinkResetStrategyCortexM3.RESETPIN) return True
def start(self, buffer_name, log_filename, debugger_snr=None): log("%s.%s", self.__class__, self.start.__name__) self.log_filename = log_filename target_device = "NRF52840_XXAA" self.jlink = pylink.JLink() self.jlink.open(serial_no=debugger_snr) self.jlink.set_tif(pylink.enums.JLinkInterfaces.SWD) self.jlink.connect(target_device) self.jlink.rtt_start() buffer_index = self._get_buffer_index(buffer_name) self.stop_thread.clear() self.log_file = open(self.log_filename, 'ab') self.read_thread = threading.Thread(target=self._read_from_buffer, args=(self.jlink, buffer_index, self.stop_thread, self.log_file)) self.read_thread.start()