def check_pt_file(file, addr): if len(file) > 0: i = 0 L = [] while i < len(file): L.append([file[i].replace('\\', '/'), int(addr[i], 16)]) i += 1 L.sort(key=takeSecond) i = 0 try: while i < len(L) - 1: address = L[i][1] address_next = L[(i + 1)][1] file_size = os.path.getsize(os.path.join(app_path, L[i][0])) if address_next < address + file_size: printf('pt check fail, %s is overlayed with %s in flash layout, please check your partition table to fix this issue' % (L[i][0], L[(i + 1)][0])) return False else: i += 1 except Exception as err: try: printf(err) return False finally: err = None del err return True
def create_shared_key(self, peer_pk): self.ecdh.load_received_public_key_bytes(binascii.unhexlify(peer_pk)) self.sharedsecret = self.ecdh.generate_sharedsecret_bytes() ret = binascii.hexlify(self.sharedsecret).decode('utf-8') bflb_utils.printf('secret key:') bflb_utils.printf(ret) return ret
def _duty_set(self, uart_dev, duty): self._duty = duty idx = self._duty.find('%') int_duty = int(self._duty[:idx]) proto_frame = pt.cli_proto_tx_duty_setting(int_duty) bflb_utils.printf(proto_frame) itf_send(uart_dev, proto_frame)
def btn_11b_start(uart_dev, rate, pre_type): bflb_utils.printf('btn_11b_start: (%s), (%s)' % (rate, pre_type)) rate_idx = mac80211b_drop_ctn.index(rate) short_type = mac80211b_g_pre_type.index(pre_type) proto_frame = pt.cli_proto_tx_11b(rate_idx, short_type) bflb_utils.printf(proto_frame) itf_send(uart_dev, proto_frame)
def program_read_reg(values, callback=None): global eflash_loader_bin eflash_loader_bin = os.path.join(app_path, chip_name, 'eflash_loader/' + get_eflash_loader(values['dl_xtal'])) try: update_cfg(values) cmd = '-n -t flash -c %s' % eflash_loader_cfg_tmp eflash_loader_t = bflb_eflash_loader.BFLB_Eflash_Loader(chip_type) eflash_loader_t.efuse_flash_loader(cmd.split(' '), None, eflash_loader_bin) cmd = values['cmd'] length = int(values['len']) ret, data = eflash_loader_t.flash_read_status_reg_process(cmd, length) if ret: data = binascii.hexlify(data).decode('utf-8') eflash_loader_t.close_if() return ( ret, data) except Exception as err: try: ret = str(err) bflb_utils.printf('error:' + ret) return ( False, ret) finally: err = None del err
def _channel_set(self, uart_dev, ch): self._ch = ch idx = self._ch.find('(') int_channel = int(self._ch[:idx]) proto_frame = pt.cli_proto_channel_setting(int_channel) bflb_utils.printf(proto_frame) itf_send(uart_dev, proto_frame)
def btn_11n_start(uart_dev, mcs, gi, mod, bw): bflb_utils.printf('btn_11n_start: (%s), (%s), (%s), (%s)' % (mcs, gi, mod, bw)) mcs_idx = mac80211n_drop_ctn.index(mcs) proto_frame = pt.cli_proto_tx_11n(mcs_idx, gi, mod, bw) bflb_utils.printf(proto_frame) itf_send(uart_dev, proto_frame)
def update_flash_cfg_do(chipname, chiptype, flash_id, file=None, create=False, section=None): cfg_dir = app_path + '/common/flash_config/' + chiptype + '/' conf_name = get_suitable_file_name(cfg_dir, flash_id) value_key = [] if os.path.isfile(cfg_dir + conf_name) == False: return False fp = open(cfg_dir + conf_name, 'r') for line in fp.readlines(): value = line.split('=')[0].strip() if value == '[FLASH_CFG]': continue else: value_key.append(value) cfg1 = bflb_utils.BFConfigParser() cfg1.read(cfg_dir + conf_name) cfg2 = bflb_utils.BFConfigParser() cfg2.read(file) for i in range(len(value_key)): if cfg1.has_option('FLASH_CFG', value_key[i]): if cfg2.has_option(section, value_key[i]): tmp_value = cfg1.get('FLASH_CFG', value_key[i]) bflb_utils.Update_Cfg(cfg2, section, value_key[i], tmp_value) cfg2.write(file, 'w+') bflb_utils.printf('Update flash cfg finished')
def halt_cpu(self): if self._jlink.halted() == False: self._jlink.halt() if self._jlink.halted(): return True bflb_utils.printf("couldn't halt cpu") return False
def run(self): p = subprocess.Popen('openocd.exe -f openocd/openocd-usb-sipeed.cfg', shell=True, stdin=(subprocess.PIPE), stdout=(subprocess.PIPE), stderr=(subprocess.PIPE)) out, err = p.communicate() bflb_utils.printf(out)
def create_public_key(self): self.ecdh.generate_private_key() self.local_public_key = self.ecdh.get_public_key() ret = binascii.hexlify( self.local_public_key.to_string()).decode('utf-8') bflb_utils.printf('local public key:') bflb_utils.printf(ret) return ret
def btn_ble_tx_start(uart_dev, hex_tx_channel, hex_length_of_test_data, hex_packet_payload): bflb_utils.printf( 'ble tx start: (0x%s), (0x%s), (0x%s)' % (hex_tx_channel, hex_length_of_test_data, hex_packet_payload)) proto_frame = pt.cli_ble_tx_start(hex_tx_channel, hex_length_of_test_data, hex_packet_payload) bflb_utils.printf(proto_frame) itf_send(uart_dev, proto_frame)
def pds_enter_rtc(uart_dev, wakeup_tim, dtim, dtim_cnt): int_wakeup_tim = int(wakeup_tim) proto_frm = pt.cli_proto_wakeup_keep_time_setting(int_wakeup_tim) bflb_utils.printf(proto_frm) itf_send(uart_dev, proto_frm) int_dtim = int(dtim) int_dtim_cnt = int(dtim_cnt) proto_frm = pt.cli_proto_pds(int_dtim, int_dtim_cnt) bflb_utils.printf(proto_frm) itf_send(uart_dev, proto_frm)
def bl_dts2dtb(src_addr='', dest_addr=''): if '' == src_addr or ('' == dest_addr): bflb_utils.printf('bl_dts2dtb please check arg.') return bflb_utils.printf('=========', src_addr, dest_addr, '=========') with open(src_addr, 'r') as f: tmp1_dts = f.read() tmp2_dtb = fdt.parse_dts(tmp1_dts) dest_addr = os.path.join(app_path, dest_addr) with open(dest_addr, 'wb') as f: f.write(tmp2_dtb.to_dtb(version=17))
def if_shakehand(self, do_reset=False, reset_hold_time=100, shake_hand_delay=100, reset_revert=True): self.if_write(bytearray(1)) success, ack = self.if_read(2) bflb_utils.printf(binascii.hexlify(ack)) if ack.find(b'O') != -1 or (ack.find(b'K') != -1): time.sleep(0.03) return 'OK' return 'FL'
def _power_set(self, uart_dev, pwr): self._pwr = pwr if self._pwr == 'Auto': proto_frame = pt.cli_proto_tx_power_setting('-1') bflb_utils.printf(proto_frame) itf_send(uart_dev, proto_frame) else: idx = self._pwr.find('dbm') int_pwr = int(self._pwr[:idx]) proto_frame = pt.cli_proto_tx_power_setting(int_pwr) bflb_utils.printf(proto_frame) itf_send(uart_dev, proto_frame)
def sign_process(data_tohash, file, privatekey_file_uecc, publickey_file, signer): fp = open_file(file, 'rb') header = bytearray(fp.read()) header = header + bytearray(0) fp.close() pk_data, pk_hash, signature_field = img_create_sign_data(data_tohash, privatekey_file_uecc, publickey_file) pk_data = pk_data + bflb_utils.get_crc32_bytearray(pk_data) pk_pos = 244 header[pk_pos:pk_pos + 64 + 4] = pk_data sign_pos = 384 header[sign_pos:sign_pos + 4 + 64 + 4] = signature_field fp = open_file(file, 'wb+') fp.write(header) fp.close() mask_4bytes = bytearray.fromhex('FFFFFFFF') if signer == 'cpu0': bflb_utils.printf("CPU0 is signer, add signature for CPU1's image") fp = open_file(cfg.get('Img_CPU0_Cfg', 'efuse_file'), 'rb') efuse_data = bytearray(fp.read()) + bytearray(0) fp.close() fp = open_file(cfg.get('Img_CPU0_Cfg', 'efuse_mask_file'), 'rb') efuse_mask_data = bytearray(fp.read()) + bytearray(0) fp.close() efuse_data[keyslot0:keyslot2] = pk_hash efuse_mask_data[keyslot0:keyslot2] = mask_4bytes * 8 fp = open_file(cfg.get('Img_CPU0_Cfg', 'efuse_file'), 'wb+') fp.write(efuse_data) fp.close() fp = open_file(cfg.get('Img_CPU0_Cfg', 'efuse_mask_file'), 'wb+') fp.write(efuse_mask_data) fp.close() else: bflb_utils.printf("CPU1 is signer, add signature for CPU0's image") fp = open_file(cfg.get('Img_CPU1_Cfg', 'efuse_file'), 'rb') efuse_data = bytearray(fp.read()) + bytearray(0) fp.close() fp = open_file(cfg.get('Img_CPU1_Cfg', 'efuse_mask_file'), 'rb') efuse_mask_data = bytearray(fp.read()) + bytearray(0) fp.close() efuse_data[keyslot5:keyslot5 + 16] = pk_hash[0:16] efuse_mask_data[keyslot5:keyslot5 + 16] = mask_4bytes * 4 efuse_data[keyslot6:keyslot7] = pk_hash[16:32] efuse_mask_data[keyslot6:keyslot7] = mask_4bytes * 4 fp = open_file(cfg.get('Img_CPU1_Cfg', 'efuse_file'), 'wb+') fp.write(efuse_data) fp.close() fp = open_file(cfg.get('Img_CPU1_Cfg', 'efuse_mask_file'), 'wb+') fp.write(efuse_mask_data) fp.close()
def _power_save(self, uart_dev, channel, pwr): self._pwr = pwr self._ch = channel if self._pwr == 'Auto': proto_frame = pt.cli_proto_save_power_setting('', '-1') bflb_utils.printf(proto_frame) itf_send(uart_dev, proto_frame) else: idc = self._ch.find('(') str_channel = int(self._ch[:idc]) idx = self._pwr.find('dbm') int_pwr = int(self._pwr[:idx]) proto_frame = pt.cli_proto_save_power_setting(str_channel, int_pwr) bflb_utils.printf(proto_frame) itf_send(uart_dev, proto_frame)
def obs_handle(self, data): val = [] if data[0:4] == '#*#*': bflb_utils.printf('obs_handle [%s]' % data) cmd = data[4:] val = cmd.split(':') if val[0] == 'channel': self._update_chan_ui(val[1]) elif val[0] == 'power': self._update_pwr_ui(val[1]) elif val[0] == 'duty': self._update_duty_ui(val[1]) elif val[0] == 'capcode': self._update_capcode_ui(val[1]) elif val[0] == 'mfgmode': self._update_mfgmode_ui(val[1])
def _read(self): data = '' while self._rx_thread_running: try: byte_msg = self._ser.read(1) except serial.SerialException: try: self._ser.close() except: pass self._ser = None self._rx_thread_running = False self._tx_thread_running = False self._tx_thread.join() self._tx_queue = None except Exception: pass else: try: str_msg = bytes.decode(byte_msg) except Exception as err: try: continue finally: err = None del err if str(str_msg) == '\r': if data != '': bflb_utils.printf(data) if self._check_boot_cond(data) == True: if self._recv_cb_objs != None: if len(self._recv_cb_objs) != 0: for cb in self._recv_cb_objs: time.sleep(1) cb.on_boot(self.uart) if self._recv_cb_objs != None: if len(self._recv_cb_objs) != 0: for cb in self._recv_cb_objs: cb.obs_handle(data) data = '' else: if str(str_msg) != '\n': data += str_msg
def efuse_create_process(chipname, chiptype, config_file, output_file=None): efuse_bootheader_path = os.path.join(app_path, chipname, 'efuse_bootheader') bflb_utils.printf('Create efuse using ', config_file) sub_module = __import__(('lib.' + chiptype), fromlist=[chiptype]) efuse_data, mask = update_data_from_cfg(sub_module.efuse_cfg_keys.efuse_cfg_keys, config_file, 'EFUSE_CFG') if output_file == None: fp = open(efuse_bootheader_path + '/efusedata.bin', 'wb+') else: fp = open(output_file, 'wb+') fp.write(efuse_data) fp.close() if output_file == None: fp = open(efuse_bootheader_path + '/efusedata_mask.bin', 'wb+') else: fp = open(output_file.replace('.bin', '_mask.bin'), 'wb+') fp.write(mask) fp.close()
def __create_pt_table_do(self, lists, file): entry_table = bytearray(36 * self.entry_max) entry_cnt = 0 for item in lists: entry_type = item['type'] entry_name = item['name'] entry_device = item['device'] entry_addr0 = item['address0'] entry_addr1 = item['address1'] entry_maxlen0 = item['size0'] entry_maxlen1 = item['size1'] entry_len = item['len'] entry_table[36 * entry_cnt + 0] = bflb_utils.int_to_2bytearray_l(entry_type)[0] if len(entry_name) >= 8: bflb_utils.printf('Entry name is too long!') return False else: entry_table[36 * entry_cnt + 3:36 * entry_cnt + 3 + len(entry_name)] = bytearray( entry_name, 'utf-8') + bytearray(0) entry_table[36 * entry_cnt + 12:36 * entry_cnt + 16] = bflb_utils.int_to_4bytearray_l(entry_addr0) entry_table[36 * entry_cnt + 16:36 * entry_cnt + 20] = bflb_utils.int_to_4bytearray_l(entry_addr1) entry_table[36 * entry_cnt + 20:36 * entry_cnt + 24] = bflb_utils.int_to_4bytearray_l(entry_maxlen0) entry_table[36 * entry_cnt + 24:36 * entry_cnt + 28] = bflb_utils.int_to_4bytearray_l(entry_maxlen1) entry_cnt += 1 pt_table = bytearray(16) pt_table[0] = 66 pt_table[1] = 70 pt_table[2] = 80 pt_table[3] = 84 pt_table[6:8] = bflb_utils.int_to_2bytearray_l(int(entry_cnt)) pt_table[12:16] = bflb_utils.get_crc32_bytearray(pt_table[0:12]) entry_table[36 * entry_cnt:36 * entry_cnt + 4] = bflb_utils.get_crc32_bytearray(entry_table[0:36 * entry_cnt]) data = pt_table + entry_table[0:36 * entry_cnt + 4] fp = open(file, 'wb+') fp.write(data) fp.close() return True
def get_suitable_file_name(cfg_dir, flash_id): conf_files = [] for home, dirs, files in os.walk(cfg_dir): for filename in files: if filename.split('_')[(-1)] == flash_id + '.conf': conf_files.append(filename) if len(conf_files) > 1: bflb_utils.printf('Flash id duplicate and alternative is:') for i in range(len(conf_files)): tmp = conf_files[i].split('.')[0] bflb_utils.printf('%d:%s' % (i + 1, tmp)) return conf_files[i] if len(conf_files) == 1: return conf_files[0] return ''
def flash_partition_thread(values, action): global eflash_loader_bin eflash_loader_bin = os.path.join( app_path, chip_name, 'eflash_loader/' + get_eflash_loader(values['dl_xtal'])) ret = None if action == 'erase partition1': start_addr = values['p1_start_addr'] end_addr = hex(int(start_addr, 16) + 4096 - 1).replace('0x', '') update_cfg(values) cmd = '-e -t flash -c %s --start=%s --end=%s' % (eflash_loader_cfg_tmp, start_addr, end_addr) elif action == 'erase partition2': start_addr = values['p2_start_addr'] end_addr = hex(int(start_addr, 16) + 4096 - 1).replace('0x', '') update_cfg(values) cmd = '-e -t flash -c %s --start=%s --end=%s' % (eflash_loader_cfg_tmp, start_addr, end_addr) elif action == 'program': if create_partition_table(values) == False: return start_addr = values['p1_start_addr'] end_addr = hex(int(start_addr, 16) + 4096 - 1).replace('0x', '') update_cfg(values) cmd = '-p -t flash -c %s --file=%s --addr=%s' % ( eflash_loader_cfg_tmp, partition_path, start_addr) elif action == 'create': create_partition_table(values) return True try: try: bflb_utils.printf(cmd) eflash_loader_t = bflb_eflash_loader.BFLB_Eflash_Loader(chip_type) ret = eflash_loader_t.efuse_flash_loader(cmd.split(' '), None, eflash_loader_bin) except Exception as e: try: ret = str(e) traceback.print_exc(limit=5, file=(sys.stdout)) finally: e = None del e finally: return ret
def if_deal_response(self): ack = self.if_deal_ack() if ack == 'OK': success, len_bytes = self.if_read(2) if success == 0: bflb_utils.printf('Get length error') bflb_utils.printf('len error is ', binascii.hexlify(len_bytes)) return ('Get length error', len_bytes) tmp = bflb_utils.bytearray_reverse(len_bytes) data_len = bflb_utils.bytearray_to_int(tmp) success, data_bytes = self.if_read(data_len) if success == 0 or (len(data_bytes) != data_len): bflb_utils.printf( 'Read data error,maybe not get excepted length') return ('Read data error,maybe not get excepted length', data_bytes) return (ack, data_bytes) bflb_utils.printf('Not ack OK') bflb_utils.printf(ack) return (ack, None)
def set_pc_msp(self, pc, msp): if self._jlink.halted() == False: self._jlink.halt() if self._jlink.halted(): if self._chiptype == 'bl602': jlink_script = 'jlink.cmd' fp = open(jlink_script, 'w+') cmd = 'h\r\nSetPC ' + str(self._jlink_run_addr) + '\r\nexit' bflb_utils.printf(cmd) fp.write(cmd) fp.close() jlink_cmd = 'JLink.exe -device RISC-V -Speed ' + str( self._speed ) + ' -IF JTAG -jtagconf -1,-1 -autoconnect 1 -CommanderScript jlink.cmd' p = subprocess.Popen(jlink_cmd, shell=True, stdin=(subprocess.PIPE), stdout=(subprocess.PIPE), stderr=(subprocess.PIPE)) out, err = p.communicate() bflb_utils.printf(out, err) os.remove(jlink_script) else: self._jlink.register_write(15, int(pc, 16)) self._jlink.register_write(13, int(msp, 16)) self._jlink.restart() else: bflb_utils.printf("couldn't halt cpu")
def img_create_sign_data(data_bytearray, privatekey_file_uecc, publickey_file): sk = ecdsa.SigningKey.from_pem(open(privatekey_file_uecc).read()) vk = ecdsa.VerifyingKey.from_pem(open(publickey_file).read()) pk_data = vk.to_string() bflb_utils.printf('Private key: ', binascii.hexlify(sk.to_string())) bflb_utils.printf('Public key: ', binascii.hexlify(pk_data)) pk_hash = img_create_sha256_data(pk_data) bflb_utils.printf('Public key hash=', binascii.hexlify(pk_hash)) signature = sk.sign(data_bytearray, hashfunc=(hashlib.sha256), sigencode=(ecdsa.util.sigencode_string)) bflb_utils.printf('Signature=', binascii.hexlify(signature)) len_array = bflb_utils.int_to_4bytearray_l(len(signature)) sig_field = len_array + signature crcarray = bflb_utils.get_crc32_bytearray(sig_field) return ( pk_data, pk_hash, sig_field + crcarray)
def if_init(self, device, rate, chiptype='bl60x'): if self._inited == False: sub_module = __import__(('lib.' + chiptype), fromlist=[chiptype]) self._openocd_shake_hand_addr = sub_module.openocd_load_cfg.openocd_shake_hand_addr self._openocd_data_addr = sub_module.openocd_load_cfg.openocd_data_addr self._openocd_run_addr = sub_module.openocd_load_cfg.openocd_run_addr self._speed = rate self._inited = True self._chiptype = chiptype self._openocd_th = ThreadOpenocdServer(chiptype) self._openocd_th.setDaemon(True) self._openocd_th.start() try: self.tn.open('127.0.0.1', port=4444, timeout=10) self.tn.write(('adapter_khz ' + str(rate)).encode('ascii') + b'\n') self.tn.write('WaitCmd\n'.encode('ascii')) self.tn.read_until(('"WaitCmd"'.encode('ascii')), timeout=10) except: bflb_utils.printf('Failed to connect openocd server') bflb_utils.set_error_code('0009') return False
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 _read_listen(self): data = '' self._ser.timeout = 0.1 while self._rx_thread_running: try: byte_msg = self._ser.read(50000) except serial.SerialException as e: try: try: self._ser.close() except: pass self._ser = None self._rx_thread_running = False finally: e = None del e except Exception as e: try: pass finally: e = None del e else: try: if byte_msg: new_mess = str(bytes.decode(byte_msg)) bflb_utils.printf(new_mess) byte_msg = '' except: byte_msg = byte_msg.replace(b'\x00', b' ') bflb_utils.printf(byte_msg.decode('GB18030', 'replace')) byte_msg = ''