User manual
5. SNAPpy Applicaon Development
This secon outlines some of the basic issues to be considered when developing SNAP-based applicaons.
Event-Driven Programming
Applicaons in SNAPpy oen have several acvies 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 funcons run quickly to compleon, and almost never “block” or “loop”
waing for something. External events will trigger SNAPpy funcons.
Noce the word “almost” in that last paragraph. As a quick counter-example, if you call the pulsePin() funcon
with a negave duraon, then by using that parameter you have requested a blocking pulse – the call to
pulsePin() will not return unl the requested pulse has been generated.
This means it is very important that your SNAPpy funcons also run quickly to compleon!
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
funconality.
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 exhausve, and only shows high-level processing!
If you focus your aenon on the le side of the flowchart, you will recognize that SNAP itself uses a soware
architecture commonly referred to as “one big loop”. The SNAP OS is wrien in C, and is quickly able to monitor
the radio, check for GPIO transions, perform Mesh Roung, etc.
Now focus your aenon 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 execung porons of your SNAPpy script (those
associated with HOOK_xxx handlers, as well as user-defined RPC calls).
While the node is busy interpreng the SNAPpy script, the other funcons (the ones not highlighted) are not
geng 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 funcons.
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 quanty of mer hooks – SNAP sets a flag indicang that a mer hook needs to be invoked, it
does not “queue them up.” So, if you have a funcon that takes several milliseconds to run to compleon, upon
compleon SNAP will only see that the flag is set and will only advance its internal millisecond “ck” counter by
one ck.
SNAP® Network Operang System 17