Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Core Library Proposal: Watchdog-safe iterators #346

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

jordansissel
Copy link

@jordansissel jordansissel commented Sep 4, 2017

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;
}

This adds mgos_iterator and mgos_iterator_count.

These iterators are useful when you want to iterate without blocking the
main rest of the system.
@cpq cpq assigned rojer Sep 4, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants