def check_partition(self, hash, updatesize): h = hashlib.sha256() buf_sz = int( (updatesize / self.CHUNK_SIZE - updatesize // self.CHUNK_SIZE) * self.CHUNK_SIZE) log.debug('First buf_sz {}'.format(buf_sz)) if buf_sz == 0: buf = bytearray(self.CHUNK_SIZE) else: buf = bytearray(buf_sz) position = self.partitions[self.next_boot_partition][2] pieces = int( updatesize / self.CHUNK_SIZE) + (updatesize % self.CHUNK_SIZE > 0) for i in range(0, pieces): # log.debug('id {}, P: {}'.format(i, position)) esp.flash_read(position, buf) # log.debug('{}'.format(buf)) h.update(buf) position += len(buf) buf = bytearray(self.CHUNK_SIZE) parthash = (ubinascii.hexlify(h.digest()).decode()) log.info('partition hash is "{}", should be "{}"'.format( parthash, hash)) return parthash == hash
def copy_partition(self): buf = bytearray(self.CHUNK_SIZE) for i in range( 0, self.partitions[self.cur_boot_partition][3] / self.CHUNK_SIZE): esp.flash_read( self.partitions[self.cur_boot_partition][2] + self.CHUNK_SIZE * i, buf) self.write_partition_chunk(buf, i)
def __init__(self, font_address=0x300000): self.font_address = font_address buffer = bytearray(18) esp.flash_read(self.font_address, buffer) self.header, \ self.height, \ self.width, \ self.baseline, \ self.x_height, \ self.Y_height, \ self.first_char,\ self.last_char = ustruct.unpack('4sHHHHHHH', buffer) self.first_char_info_address = self.font_address + 18
def GetCharacterData(self,c): uni=ord(c) if uni not in range(self.first_char,self.last_char): return None char_info_address=self.first_char_info_address+(uni-self.first_char)*6 buffer=bytearray(6) esp.flash_read(char_info_address,buffer) ptr_char_data,len=ustruct.unpack('IH',buffer) if(ptr_char_data)==0 or(len==0): return None buffer=bytearray(len) esp.flash_read(ptr_char_data+self.font_address,buffer) return buffer
def __init__(self, font_address=0x200000): self.font_address = font_address buffer = bytearray(18) esp.flash_read(self.font_address, buffer) self.header, \ self.height, \ self.width, \ self.baseline, \ self.x_height, \ self.Y_height, \ self.first_char,\ self.last_char = ustruct.unpack('4sHHHHHHH', buffer) self.first_char_info_address = self.font_address + 18
def search(offset, text): print('search for %r start with offset 0x%x' % (text, offset)) offset_step = CHUNK_SIZE - len(text) if offset_step <= 0: raise AssertionError('Search text too large: increase CHUNK_SIZE!') def print_throughput(): duration = utime.time() - start_time if duration == 0: throughput = -1 else: throughput = (offset - start_offset) / duration / 1024 print( '(Search duration: %i sec. - %i KBytes/sec' % (duration, throughput) ) flash_size = esp.flash_size() start_offset = offset end_researched = False start_time = utime.time() next_update = start_time + 1 while True: if offset + CHUNK_SIZE > flash_size: # Search to esp.flash_size(), but don't go beyond. offset = flash_size - CHUNK_SIZE end_researched = True try: esp.flash_read(offset, BUFFER) except OSError as e: print('Read flash error: %s at 0x%x - 0x%x' % (e, offset, offset + CHUNK_SIZE)) return -1 if text in BUFFER: print('Found in 0x%x !' % offset, end=' ') print_throughput() return offset if utime.time() >= next_update: print('Search: 0x%x ...' % offset, end=' ') print_throughput() next_update = utime.time() + 1 if end_researched: print('Memory end researched, searched up to 0x%x' % (offset + CHUNK_SIZE)) print_throughput() return -1 offset += offset_step
def hex_dump(offset=0): for line_num in range(LINE_COUNT): current_offset = offset + (line_num * CHUNK_SIZE) esp.flash_read(current_offset, BUFFER) print('%08x - %08x' % (current_offset, current_offset + CHUNK_SIZE - 1), end=' ') print(' '.join('%02x' % char for char in BUFFER), end=' ') print( ''.join( chr(char) if 32 <= char <= 126 and char not in (60, 62) else '.' for char in BUFFER ) ) gc.collect()
def set_adc_vcc(): sector_size = bdev.SEC_SIZE flash_size = esp.flash_size() init_sector = int(flash_size / sector_size - 4) data = bytearray(esp.flash_read(init_sector * sector_size, sector_size)) data[107] = 255 esp.flash_erase(init_sector) esp.flash_write(init_sector * sector_size, data) machine.reset()
def set_bl_flash_size(real_size): if real_size == 256*1024: code = 1 elif real_size == 512*1024: code = 0 elif real_size == 1024*1024: code = 2 elif real_size == 2048*1024: code = 3 elif real_size == 4096*1024: code = 4 else: code = 2 buf = bytearray(4096) esp.flash_read(0, buf) buf[3] = (buf[3] & 0xf) | (code << 4) esp.flash_erase(0) esp.flash_write(0, buf)
def set_bl_flash_size(real_size): if real_size == 256 * 1024: code = 1 elif real_size == 512 * 1024: code = 0 elif real_size == 1024 * 1024: code = 2 elif real_size == 2048 * 1024: code = 3 elif real_size == 4096 * 1024: code = 4 else: code = 2 buf = bytearray(4096) esp.flash_read(0, buf) buf[3] = (buf[3] & 0xf) | (code << 4) esp.flash_erase(0) esp.flash_write(0, buf)
async def hex_dump(writer, offset=0): for line_num in range(LINE_COUNT): current_offset = offset + (line_num * CHUNK_SIZE) try: esp.flash_read(current_offset, BUFFER) except OSError as e: await writer.awrite(b'Error: %s' % e) break await writer.awrite(TABLE_LINE.format( address='%08x - %08x' % (current_offset, current_offset + CHUNK_SIZE - 1), hex=' '.join('%02x' % char for char in BUFFER), chars=''.join( chr(char) if 32 <= char <= 126 and char not in (60, 62) else '.' for char in BUFFER ), )) gc.collect()
async def search(writer, offset, text): print('search for', repr(text)) next_update = utime.time() + 1 while True: try: esp.flash_read(offset, BUFFER) except OSError as e: await writer.awrite(b'Error: %s' % e) break if text in BUFFER: print('Found in block:', offset) await writer.awrite(b'Found in block: %i\n' % offset) return offset offset += CHUNK_SIZE if utime.time() >= next_update: print('Search:', offset) await writer.awrite(b'Search %i\n' % offset) next_update = utime.time() + 1
def set_adc_mode(mode): sector_size = bdev.SEC_SIZE flash_size = esp.flash_size() # device dependent init_sector = int(flash_size / sector_size - 4) data = bytearray(esp.flash_read(init_sector * sector_size, sector_size)) if data[107] == mode: return # flash is already correct; nothing to do else: data[107] = mode # re-write flash esp.flash_erase(init_sector) esp.flash_write(init_sector * sector_size, data) print("ADC mode changed in flash; restart to use it!") return
def set_adc_mode(mode): sector_size = bdev.SEC_SIZE flash_size = esp.flash_size() # device dependent init_sector = int(flash_size / sector_size - 4) data = bytearray(esp.flash_read(init_sector * sector_size, sector_size)) if data[107] == mode: return # flash is already correct; nothing to do else: print( "*** Going to adjust the ADC type in the flashed memory" ); print( "*** You will need to hit the 'RST' button, near the USB port" ); print( "*** when it's done" ); data[107] = mode # re-write flash esp.flash_erase(init_sector) esp.flash_write(init_sector * sector_size, data) print("*** ADC mode changed in flash; restart to use it!") return
def set_adc_mode(adc=0): ADC_MODE_ADC = 0 ADC_MODE_VCC = 255 mode = {0: ADC_MODE_ADC, 1: ADC_MODE_VCC} sector_size = bdev.SEC_SIZE flash_size = esp.flash_size() # device dependent init_sector = int(flash_size / sector_size - 4) data = bytearray(esp.flash_read(init_sector * sector_size, sector_size)) if data[107] == mode[adc]: print("ADC mode is already set in flash!") return else: data[107] = mode[adc] # re-write flash esp.flash_erase(init_sector) esp.flash_write(init_sector * sector_size, data) print("ADC mode has been changed in flash; restart to use it!") return
def adc_mode(mode=None): import flashbdev sector_size = flashbdev.bdev.SEC_SIZE flash_size = esp.flash_size() # device dependent init_sector = int(flash_size / sector_size - 4) data = bytearray(esp.flash_read(init_sector * sector_size, sector_size)) current_mode = data[107] if mode is None: # Read adc mode return current_mode if current_mode == mode: print("ADC mode already {}.".format(mode)) else: data[107] = mode # re-write flash esp.flash_erase(init_sector) esp.flash_write(init_sector * sector_size, data) print("ADC mode is now {}. Reset to apply.".format(mode)) return mode
def set_adc_mode(mode): sector_size = bdev.SEC_SIZE flash_size = esp.flash_size() # device dependent init_sector = int(flash_size / sector_size - 4) try: data = bytearray( esp.flash_read(init_sector * sector_size, sector_size)) if data[107] == mode: return True # flash is already correct; nothing to do else: data[107] = mode # re-write flash esp.flash_erase(init_sector) esp.flash_write(init_sector * sector_size, data) return False except MemoryError: log = logger.get_logger() log.log_msg( logger.ERROR, "Could not allocate memory for setting adc mode, assuming it's {}" .format(_num_to_mode[mode])) return True
import esp esp.osdebug(None) # turn off vendor O/S debugging messages esp.osdebug(0) # redirect vendor O/S debugging messages to UART(0) sector_no = 1 # Placeholders byte_offset = 0 buffer = [0] # low level methods to interact with flash storage esp.flash_size() esp.flash_user_start() esp.flash_erase(sector_no) esp.flash_write(byte_offset, buffer) esp.flash_read(byte_offset, buffer) # The esp32 module: import esp32 esp32.hall_sensor() # read the internal hall sensor esp32.raw_temperature( ) # read the internal temperature of the MCU, in Fahrenheit esp32.ULP() # access to the Ultra-Low-Power Co-processor # RMT import esp32 from machine import Pin r = esp32.RMT(0, pin=Pin(18), clock_div=8)
def readblocks(self, n, buf): #print("readblocks(%s, %x(%d))" % (n, id(buf), len(buf))) esp.flash_read((n + self.START_SEC) * self.SEC_SIZE, buf)
def readblocks(self, n, buf): #print("readblocks(%s, %x(%d))" % (n, id(buf), len(buf))) esp.flash_read((n + self.START_SEC) * self.SEC_SIZE, buf)
return self.blocks if op == 5: # BP_IOCTL_SEC_SIZE return SEC_SIZE # Set up UART uos.dupterm(machine.UART(0, 115200), 1) # Disable OS debug messages # esp.osdebug(None) # Read FS metadata meta_off = META_SECTOR * SEC_SIZE while True: # Read FS params buf = bytearray(28) # name / start sector / lenght / flags esp.flash_read(meta_off, buf) meta_off += 28 if buf[0] == 0xff: # no more entries break mpoint = bytes(buf[:16]).decode().rstrip() fs_start = int.from_bytes(buf[16:20], 'big') fs_len = int.from_bytes(buf[20:24], 'big') readonly = bool(buf[25]) # Mount filesystem flash = FlashBlockDev(fs_start, fs_len) uos.mount(flash, mpoint, readonly=readonly) # Set up garbage collector gc.threshold((gc.mem_free() + gc.mem_alloc()) // 4)
def load(self): """Load config (all sections) from file""" offset = CONFIG_BLOCK * BLOCK_SIZE # metadata, bytes: # 0: name len # 1: type # 2: chksum (sum of name + type) meta = bytearray(3) while True: esp.flash_read(offset, meta) offset += 3 # All 0xff indicates end of list if meta == b'\xff\xff\xff': break if sum(meta[:2]) != meta[2]: raise ConfigError('Malformed config') # read param name buf = bytearray(meta[0]) esp.flash_read(offset, buf) offset += meta[0] name = bytes(buf).decode() # read value if meta[1] == 1: # type int buf = bytearray(4) esp.flash_read(offset, buf) offset += 4 value = int.from_bytes(buf, 'big') # Respect sign if value > 0x7FFFFFFF: value -= 0x100000000 elif meta[1] == 2: # type string # read len buf = bytearray(1) esp.flash_read(offset, buf) offset += 1 # read value if buf[0] > 0: val = bytearray(buf[0]) esp.flash_read(offset, val) value = bytes(val).decode() else: value = '' offset += buf[0] elif meta[1] == 3: # type bool buf = bytearray(1) esp.flash_read(offset, buf) value = bool(buf[0]) offset += 1 elif meta[1] == 4: # None value = None else: raise ConfigError('Unknown {} value type'.format(meta[2])) validate_name(name) validate_value_type(value) self.validate_value(name, value) setattr(self, name, value) gc.collect() # Run callbacks self.run_callbacks( [x for x in self.__dict__.keys() if not x.startswith('_')]) gc.collect()
def readblocks(self, n, buf): esp.flash_read((n + self.start) * SEC_SIZE, buf)
import esp import machine from flashbdev import bdev sector_size = bdev.SEC_SIZE flash_size = esp.flash_size() # device dependent init_sector = int(flash_size / sector_size - 4) data = bytearray(esp.flash_read(init_sector * sector_size, sector_size)) data[107] = 255 esp.flash_erase(init_sector) esp.flash_write(init_sector * sector_size, data) machine.reset() # from machine import ADC # ADC(1).read()
def readblocks(self, n, buf, off=0): #print("readblocks(%s, %x(%d), %d)" % (n, id(buf), len(buf), off)) esp.flash_read((n + self.START_SEC) * self.SEC_SIZE + off, buf)