User manual

5. SNAPpy Applicaon Development
This secon outlines some of the basic issues to be considered when developing SNAP-based applicaons.
Event-Driven Programming
Applicaons in SNAPpy oen have several acvies going on concurrently. How is this possible, with only one
CPU on the SNAP Engine? In SNAPpy, the illusion of concurrency is achieved through event-driven programming.
This means that most built-in SNAPpy funcons run quickly to compleon, and almost never “block” or “loop”
waing for something. External events will trigger SNAPpy funcons.
Noce the word “almost” in that last paragraph. As a quick counter-example, if you call the pulsePin() funcon
with a negave duraon, then by using that parameter you have requested a blocking pulse the call to
pulsePin() will not return unl the requested pulse has been generated.
This means it is very important that your SNAPpy funcons also run quickly to compleon!
As an example of what not to do, consider the following code snippet:
while readPin(BUTTON_PIN) != BUTTON_PRESSED:
pass
print "Button is now pressed"
Instead of monopolizing the CPU like this, your script should use SNAPpy’s monitorPin() and HOOK_GPIO
funconality.
To understand why “hard loops” like the one shown above are so bad, take a look at the flowchart on the
following page.
NOTE the flowchart is not exhausve, and only shows high-level processing!
If you focus your aenon on the le side of the flowchart, you will recognize that SNAP itself uses a soware
architecture commonly referred to as “one big loop”. The SNAP OS is wrien in C, and is quickly able to monitor
the radio, check for GPIO transions, perform Mesh Roung, etc.
Now focus your aenon on the highlighted blocks on the right side of the flowchart. These show some of the
mes when the SNAPpy virtual machine might be busy execung porons of your SNAPpy script (those
associated with HOOK_xxx handlers, as well as user-defined RPC calls).
While the node is busy interpreng the SNAPpy script, the other funcons (the ones not highlighted) are not
geng a chance to run. The SNAP OS cannot be checking mers or watching for input signals while it is busy
running one of your SNAPpy funcons.
To give a specific example, if one of your RPC handlers takes too long to run, then the HOOK_1MS handler will
not be running at the correct me, because it had to wait. If your script hogs the CPU enough, you won’t even
get the correct quanty of mer hooks SNAP sets a flag indicang that a mer hook needs to be invoked, it
does not “queue them up.” So, if you have a funcon that takes several milliseconds to run to compleon, upon
compleon SNAP will only see that the flag is set and will only advance its internal millisecond “ck” counter by
one ck.
SNAP® Network Operang System 17