contiki-os/contiki — pull request #83 by darconeous (2013-01-15 04:52:35+00:00)
Title: sys/clock: Autosleep: added `clock_sleep_with_max_duration()` and example AVR implementation.

Contiki support for "automatic" sleep (autosleep) can be easily
implemented with the addition of the CPU-specific function
`clock_sleep_with_max_duration()`. This function must be implemented
in such a way that any interrupts that occur will cause it to exit
immediately after the interrupt is handled. This is normally
implemented by setting a timer to generate an interrupt at the
requested expiration and then putting the microcontroller into
one of its built-in sleep modes. In the main run loop, you then
call then method when you have nothing to do, passing as an
argument the point in time at which you know you will have something
to do. If you are familiar with asynchronous socket IO design
patterns, then you can think of `click_sleep_with_max_duration()`
as a more simple verison of `select()` or `poll()`---except that
the interrupts pretty much handle themselves.

This pattern allows the system to sleep implicitly when it has
nothing to do, while still being responsive to timed events. For the
most part, after you implement it you can forget about it.

The key is, of course, having a reasonable implementation of
`clock_sleep_with_max_duration()` for the platform you are
interested in. I've included some example code for the avr-raven
and avr-ravenusb platforms to show how to use this function
in your main loops, but I don't yet have a reasonable implementation
of this function yet for the AVR CPU---it is just a stub.

This technique is not limited to AVR microcontrollers. Any
microcontroller which implements a sleep mode which can be awoken from
interrupts is a prime candidate for autosleep.