1
0

flashbdev.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import esp
  2. class FlashBdev:
  3. SEC_SIZE = 4096
  4. START_SEC = esp.flash_user_start() // SEC_SIZE
  5. NUM_BLK = 0x6b
  6. def __init__(self, blocks=NUM_BLK):
  7. self.blocks = blocks
  8. def readblocks(self, n, buf):
  9. #print("readblocks(%s, %x(%d))" % (n, id(buf), len(buf)))
  10. esp.flash_read((n + self.START_SEC) * self.SEC_SIZE, buf)
  11. def writeblocks(self, n, buf):
  12. #print("writeblocks(%s, %x(%d))" % (n, id(buf), len(buf)))
  13. #assert len(buf) <= self.SEC_SIZE, len(buf)
  14. esp.flash_erase(n + self.START_SEC)
  15. esp.flash_write((n + self.START_SEC) * self.SEC_SIZE, buf)
  16. def ioctl(self, op, arg):
  17. #print("ioctl(%d, %r)" % (op, arg))
  18. if op == 4: # BP_IOCTL_SEC_COUNT
  19. return self.blocks
  20. if op == 5: # BP_IOCTL_SEC_SIZE
  21. return self.SEC_SIZE
  22. def set_bl_flash_size(real_size):
  23. if real_size == 256*1024:
  24. code = 1
  25. elif real_size == 512*1024:
  26. code = 0
  27. elif real_size == 1024*1024:
  28. code = 2
  29. elif real_size == 2048*1024:
  30. code = 3
  31. elif real_size == 4096*1024:
  32. code = 4
  33. else:
  34. code = 2
  35. buf = bytearray(4096)
  36. esp.flash_read(0, buf)
  37. buf[3] = (buf[3] & 0xf) | (code << 4)
  38. esp.flash_erase(0)
  39. esp.flash_write(0, buf)
  40. # If bootloader size ID doesn't correspond to real Flash size,
  41. # fix bootloader value and reboot.
  42. size = esp.flash_id() >> 16
  43. # Check that it looks like realistic power of 2 for flash sizes
  44. # commonly used with esp8266
  45. if 22 >= size >= 18:
  46. size = 1 << size
  47. if size != esp.flash_size():
  48. import machine
  49. import time
  50. print("Bootloader Flash size appear to have been set incorrectly, trying to fix")
  51. set_bl_flash_size(size)
  52. machine.reset()
  53. while 1: time.sleep(1)
  54. size = esp.flash_size()
  55. if size < 1024*1024:
  56. bdev = None
  57. else:
  58. # 20K at the flash end is reserved for SDK params storage
  59. bdev = FlashBdev((size - 20480) // FlashBdev.SEC_SIZE - FlashBdev.START_SEC)