micropython/micropython — pull request #818 by dpgeorge (2014-08-22 21:06:28+00:00)
Title: Generic modselect

This is an implementation of the select module which tries to be as generic as possible. The idea is that you can select/poll any streamable object that provides a way of checking if it can be read/written.

This patch introduces the `ioctl` method to the stream protocol. Some ioctl requests like seek and flush (not implemented) would be applicable to all ports, but most requests will be port specific. In the case for select/poll, the stmhal port defines the MP_IOCTL_POLL request, and implements select/poll by iterating through all objects and checking (by calling ioctl) if they have anything to read/write. If not it waits for an interrupt, then checks again in an infinite loop, with an optional timeout.

On the unix port, the select behaviour would be implemented by a MP_IOCTL_FD request which gets the file descriptor for a given object, and then calls the system select/poll functions (this is not implemented in this patch).

On stmhal, it is envisaged to be able to select/poll on, eg, UART, I2C, SPI, wifi and Ethernet all at once. It would be as simple as:

import select
result = select.select([uart, i2c, spi, wifi, eth], [], [], 10.0)

or with poll (which is more efficient, due to the registration process of objects):

import select
poll = select.poll()
poll.register(uart, select.RD)
poll.register(i2c, select.RD)
poll.register(spi, select.RD)
poll.register(wifi, select.RD)
poll.register(eth, select.RD)
poll.poll(10000)

(Note that the poll timeout is an integer in milliseconds, as per CPython.)

Comments/suggestions/etc are most welcome.