A State-Based Programming Model for Wireless Sensor Networks
A State-Based Programming Model for Wireless Sensor Networks
A State-Based Programming Model for Wireless Sensor Networks
Create successful ePaper yourself
Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.
66 Chapter 4. Event-driven <strong>Programming</strong> in Practice<br />
Program 4.2: General pattern to implement context sensitive actions.<br />
1 typedef enum {INIT, A, B, ... } state_t;<br />
2 state_t state = INIT; // initial state<br />
3<br />
4 void event_handler_x {<br />
5 switch( state ) {<br />
6 case INIT:<br />
7 // handle event_x in state INIT<br />
8 state = ...; // set new state<br />
9 break;<br />
10 case A:<br />
11 // handle event_x in state A<br />
12 state = ...; // set new state<br />
13 break;<br />
14 case B:<br />
15 // handle event_x in state B<br />
16 state = ...; // set new state<br />
17 break;<br />
18 default:<br />
19 // ...<br />
20 }<br />
21 }<br />
22 void event_handler_y {<br />
23 // ...<br />
24 }<br />
when the programmer was not expecting them (e.g., duplicated network messages<br />
or events generated by another action), however, will trigger their associated<br />
operation regardless. To en<strong>for</strong>ce the correct behavior, programmers need to<br />
manage contex in<strong>for</strong>mation and need to code the program’s flow control explicitly.<br />
In the event-driven model the reaction to an event cannot be specified with<br />
respect to such context in<strong>for</strong>mation. Instead an event always triggers its single<br />
associated action. The event model does not provide any means against restarting<br />
of such phases anew. (In fact, there is not even an abstraction to indicate<br />
which parts of the code implement a single logical operation.) Special care must<br />
be taken by programmers not to accidentally restart a cascade of actions. In oder<br />
to be able to detect such errors, a defensive programmer would set a flag at the<br />
beginning of the logical operation and check it in every action to trigger exception<br />
handling. For the example Program 4.1, this could be achieved by checking<br />
whether every invocation of init_remote_average()) has been followed by<br />
a call to timeout_hdl() or otherwise ignore the invocation. The following additional<br />
code implements a possible solution when inserted after line 5 of the<br />
example:<br />
if( sampling_active == TRUE ) {<br />
return; // error, ignore<br />
}