// Use Memory.remember(u8*) to reorder out-of-sequence packets

u32 lastSequence = 0;           // Last sequence# received in order
void handleS(u8 * packet) {
  u32 sequence;
  if (packetScanf(packet,"s%d\n",&sequence) != 3) return; // Analyze input, ignore bad packets

  if (lastSequence == 0 || sequence-lastSequence > 5) {   // If just starting, or we're way off
    lastSequence = sequence-1;                            // Reset
    logNormal("(Re)starting at %d\n",sequence);           // and announce that
  }

  if (lastSequence+1 < sequence)     // If packet is out of order,
    Memory.remember(packet);         // just remember it for later..
  else {                             // Else it's what we want..
    lastSequence = sequence;         // So advance
    logNormal("Sequence %d\n",lastSequence); // and report it
  }
}

void setup() {
  Body.reflex('s',handleS);     // Set up reflex
}

u32 loops = 0;            // Last sequence# we sent out
void loop() {
  if (random(10)!=0)      // 90% of the time, just issue next sequence #
    pprintf("s%d\n",++loops);
  else {                  // but 10% of the time, issue a few backwards..
    u32 incr = random(4)+2;     // incr=2..5
    loops += incr;
    for (u32 i = 0; i < incr; ++i)
      pprintf("s%d\n",loops-i);
  }
  ledToggle(BODY_RGB_RED_PIN);  // Show a heartbeat.
  delay(1000);            // Wait a second
}
