micropython/micropython — pull request #1005 by dpgeorge (2014-12-13 15:49:03+00:00)
Title: stmhal: Add ability to mount custom block device.

This relatively simple patch allows the user to mount a custom block device (written in Python), and have it accessible as a regular filesystem. It defines a new "block protocol" (defined at the Python level), which requires you to provide the 4 methods: readblocks, writeblocks, sync and count. For example, you can make a RAMFS as follows:
```python
class RAMFS:
def __init__(self, blocks):
self.data = bytearray(blocks * 512)

def readblocks(self, n, buf):
for i in range(len(buf)):
buf[i] = self.data[n*512+i]

def writeblocks(self, n, buf):
for i in range(len(buf)):
self.data[n*512+i] = buf[i]

def sync(self):
pass

def count(self):
return len(self.data) // 512
```
Then use it like this:
```python
import pyb, os
pyb.mount(RAMFS(40), '/ramfs')
print(os.listdir('/'))
print(os.listdir('/ramfs'))
f=open('/ramfs/test.txt', 'w')
f.write('ramfs\nwritten in python\n')
f.close()
print(os.listdir('/ramfs'))
os.chdir('/ramfs')
with open('test.txt') as f:
print(f.readlines())
pyb.mount(None, '/ramfs') # unmount
os.listdir('/')
```
This feature would be useful if users want to add their own mass storage, such as an I2C EEPROM or external flash, or an additional SD card over an SPI bus. Drivers for these block devices can be written in pure Python, or for efficiency we can implement common ones (eg SPI SD card driver) in C.

Comments welcome on the utility of this, and its implementation. In particular, should the `mount` method be in the pyb or os module?