hallucination.cpp

Sometimes you'd like to create a packet without immediately sending it off-board, but the basic printing functions don't provide a mechanism for that. As an advanced feature, the makePacketPrinter function can be used to create a packet in a (sufficiently large) memory buffer of your choosing, allowing you to do whatever you want with the resulting packet.

Using the makePacketPrinter mechanism is a little bit involved, but typically boils down to the following steps:

  1. Create a RAM buffer big enough to hold the packet-to-be-printed.
  2. Create variables to hold the pointer to the resulting packet, and the assigned virtual face number.
  3. Make the call on makePacketPrinter(), and store the packet pointer and virtual face number into the previously-created variables. This is commonly, though not necessarily, done in the setup() method.
  4. Print using the virtual face number.
  5. (Either during the printing or) After the packet is terminated, access the printed packet via the stored packet pointer.

As an illustration, this sketch 'hallucinates' that it's receiving 'd' packets at irregular intervals, when it actually is generating them itself. The keys to this sketch are the makePacketPrinter mechanism to generate an in-memory packet, and the SBFReactor::trigger() function (see trigger::cpp).

When run, this sketch generates output along the lines of:

Ln 8.404 Got 'd1' from N
Ln 9.566 Got 'd2' from N
Ln 9.952 Got 'd3' from N
Ln 17.704 Got 'd4' from N

which shows the handleD packet handler is being invoked, even though (or when) no actual input packets have been received.

// Demonstrate makePacketPrinter

u8 myBuffer[PACKET_PRINTER_PACKET_BUFFER_SIZE];    // Let's make room for a max-size packet..
u8 * myPacket;                                     // Location of printed packet
u8 myFace;                                         // My virtual face number

void handleD(u8 * packet) {
  logNormal("Got '%#p' from %c\n",packet,FACE_CODE(packetSource(packet)));  // Just log 'd' packets
}
void setup() {
  myPacket = makePacketPrinter(myFace,myBuffer,sizeof(myBuffer),NORTH); // Create the packet printer
  if (myPacket == 0) POISON(0);                    // Really can't happen at this point; die if it does
  Body.reflex('d',handleD);                        // Create our reflex
}
void loop() {
  static u32 loops = 0;
  delay(random(10000));                            // Wait about five seconds.
  facePrintf(myFace,"d%d\n",++loops);              // Make a 'd' packet in myPacket
  Body.trigger(myPacket,packetSource(myPacket));   // React as though it arrived from the north
}

Generated on Fri Apr 22 06:54:10 2011 for SFB by doxygen 1.5.9