mongoose-os icon indicating copy to clipboard operation
mongoose-os copied to clipboard

Core Library Proposal: Watchdog-safe iterators

Open jordansissel opened this issue 6 years ago • 0 comments

This PR adds mgos_iterator and mgos_iterator_count.

First, I'm not assuming this feature is necessary or desired in mongoose-os itself. It could be in the library repo, or perhaps nowhere at all. I'm OK if this is rejected -- I will keep using it locally ;)


These iterators are useful when you want to iterate without blocking the main rest of the system.

Background: I am using mongoose os for a toy projects (rgb lighting) and wanted a way to animate. Typical animation (with a for loop and delay(...)) will cause two problems: First, it trips the watchdog, and second, it otherwise blocks the rest of the program.

History: This implementation is partially influenced by my success (many years ago) using EventMachine::Iterator for similar purposes, although similar constructs are often needed in other event reactor systems like nodejs, libevent, etc.

This patch provides a general iterator concept modeled off of existing Iterator interfaces (Java, for example) having two required functions: "has next" and "next".

I am open to any modifications. I have thought maybe consolidating has next and next into a single next where next returns a boolean "is done" or similar, which might be simpler and less coding for folks using it API.

Sample code using Adafruit's Neopixel library to animate a rainbow looks like this:

void rainbow(void *arg, int round) {
  Adafruit_NeoPixel *strip = static_cast<Adafruit_NeoPixel*>(arg);
  int i;
  for(i=0; i<=strip->numPixels(); i++) {
      strip->setPixelColor(i, Wheel((byte)(8 * (i + round))));
  }
  strip->show();
}

enum mgos_app_init_result mgos_app_init(void) {
  const int count = 33;
  Adafruit_NeoPixel *strip = new Adafruit_NeoPixel(count, 5, NEO_GRBW);
  strip->begin();
  strip->clear();
  strip->show();

  // for 1000 steps, do one step every 16ms
  // (16ms is a nice number giving roughly 60 updates per second)
  mgos_iterator_count(16, 1000, rainbow, strip);

  return MGOS_APP_INIT_SUCCESS;
}

jordansissel avatar Sep 04 '17 06:09 jordansissel