Chapter10 Pseudocodebibing.us.es/proyectos/abreproy/11364/fichero/memoria%2F10_Pseu… ·...

23

Transcript of Chapter10 Pseudocodebibing.us.es/proyectos/abreproy/11364/fichero/memoria%2F10_Pseu… ·...

Page 1: Chapter10 Pseudocodebibing.us.es/proyectos/abreproy/11364/fichero/memoria%2F10_Pseu… · CHAPTER10. PSEUDOCODE 64 Algorithm3Pseudocodeforgroupmembershipcheck foreachi ∈ GROUP_TYPES

Chapter 10

Pseudocode

10.1 Component GroupMngThis component performs all the operations necessary to manage group mem-bership. It also maintains an array with information about group status andanother array which contains updated values for all the attributes. GroupMngis to update both arrays. In order to do so, it needs to obtain new attributevalues by using TinySchema. Pointers to both arrays described in this para-graph are given to component ChannelMng (see algorithm 2). Given the factthat allowing several TinyOS components write access to a shared variableis strongly discouraged [5], component ChannelMng accesses these arrays inread-only mode.

After component initialization, GroupMng schedules a timer for periodicexecution of algorithm 5, which generates leader beacons when necessary (i.e.:when node is leader of any group). GroupMng also waits for noti�cationfrom TinySchema that attributes have been initialized (alg. 2) and thenstarts periodic execution of algorithm to update attribute values and performgroup membership checks. At this moment, GroupMng passes pointers toarrays described in last paragraph to ChannelMng, so that the latter canstart checking for active channels and publishing data on the channels ifnecessary.

Group membership check is perform always after an attribute array update,so once GroupMng is able to access attribute values (i.e.: once attributes havebeen initialized), periodic execution of attribute array update is scheduled.This attribute update function then schedules a group membership checkwhen the array has been updated with new attribute values.

62

Page 2: Chapter10 Pseudocodebibing.us.es/proyectos/abreproy/11364/fichero/memoria%2F10_Pseu… · CHAPTER10. PSEUDOCODE 64 Algorithm3Pseudocodeforgroupmembershipcheck foreachi ∈ GROUP_TYPES

CHAPTER 10. PSEUDOCODE 63

Algorithm 1 Global pseudocode for GroupMngInitialize GroupMng component variablesInitialize Group Drip instancesSchedule Leader beacon generation {see algorithm 5}

10.1.1 Attributes initialized noti�cationFunction that implements next algorithm is executed when attribute initial-ization is �nished, and attribute values can be obtained through TinySchema.From that moment on, it is possible to update the attribute values array andcheck form group membership, so GroupMng can start performing its maintask. This algorithm schedules periodic execution of attribute array updateand passes pointers to arrays described in section 10.1.

Algorithm 2 Pseudocode for attributes initialized noti�cationSchedule periodic execution of Attribute update (algorithm 8)Provide ChannelMng with way of accessing attribute values and group info

10.1.2 Group membership checkThis algorithm is implemented by a TinyOS task, which is schedule for ex-ecution by the event that updates the attribute array values (alg. 9). Thistask checks, for every possible group type, whether there is a group of thattype de�ned. If this is the case, the task then checks whether node's attributevalues satisfy the conditions for that group. If so, it sets that group as can-didate. When this process has �nished, the task schedules another task forexecution, which is described in section 10.1.3.

10.1.3 Group membership updateThis algorithm is implemented by a TinyOS task which is always scheduledfor execution after task described in section 10.1.2. This algorithm makesuse of the result of alg. 3. All group types are check. Whenever the nodeis candidate for a group type, it is checked whether some group of that typeexists in the vicinity. If so, the node status for that group is set to member.If a node is candidate for a group and no group of that type exist in thevicinity then the node is set to leader of that group.

Page 3: Chapter10 Pseudocodebibing.us.es/proyectos/abreproy/11364/fichero/memoria%2F10_Pseu… · CHAPTER10. PSEUDOCODE 64 Algorithm3Pseudocodeforgroupmembershipcheck foreachi ∈ GROUP_TYPES

CHAPTER 10. PSEUDOCODE 64

Algorithm 3 Pseudocode for group membership checkfor each i ∈ GROUP_TY PES doif group[i] is active (i.e.: it has some sensor associated) thenfor each j ∈ SENSORS doif group[i] requires sensor[j] then

check whether sensor[j] meets condition for group[i] {Conditionsfor each sensor are given by < or ≥ plus a threshold}

end ifend forif all conditions for the group are satis�ed then

group[i]← CANDIDATEelse

group[i]← NO_CANDIDATEend if

elsegroup[i]← DEACTIVATED

end ifend forschedule Membership Update (see Algorithm 4) for execution

This algorithm also manages the situation in which the node stops belong-ing to a group while it is a leader of that group. It is necessary to set a specialstate for that group so that a handover signal is sent to another member ofthe group. This handover signal allows maintaining group information suchas group ID and leader weight as the leader node changes.

10.1.4 Leader beacon generationThis algorithm is implemented in a event signaled by a timer. This timeris set for �ring once at component startup. When the timer is �red, thealgorithm searches the group membership table for a group the node is leaderof. If some group is found, the algorithm sets a leader beacon to be sent forthat group (i.e.: is schedules the execution of the algorithm 7).

At the end of the algorithm, a new �ring for the timer is scheduled to occurin a time that depends on the amount of groups the node is leader of. Inorder to set this execution time, the algorithm counts the number of groupsthe node is leader of. The objective is to achieve a constant beacon rate for agroup, independently of the number of beacons the node has to send. So, themore groups the node is leader of, the higher the frequency of the beacons

Page 4: Chapter10 Pseudocodebibing.us.es/proyectos/abreproy/11364/fichero/memoria%2F10_Pseu… · CHAPTER10. PSEUDOCODE 64 Algorithm3Pseudocodeforgroupmembershipcheck foreachi ∈ GROUP_TYPES

CHAPTER 10. PSEUDOCODE 65

Algorithm 4 Pseudocode for group membership updatefor each i ∈ GROUP_TY PES doif node is CANDIDATE for groups[i] thenif no leader for groups[i] heard in FORGET_TIME then

groups[i]← LEADERreset groups[i] group state info

elsegroups[i]← MEMBER

end ifelseif node is NO_CANDIDATE for groups[i] thenif node was LEADER for groups[i] then

groups[i] ← HANDOVER {Hand over signal is repeated untilanother leader is heard or timer expires}

elseif no leader for groups[i] heard in FORGET_TIME then

groups[i]← UNKNOWNelse

groups[i]← KNOWNend if

elsegroups[i] ← UNKNOWN {If we get here then the group is notactive}reset groups[i] group state info

end ifend if

end ifend for

Page 5: Chapter10 Pseudocodebibing.us.es/proyectos/abreproy/11364/fichero/memoria%2F10_Pseu… · CHAPTER10. PSEUDOCODE 64 Algorithm3Pseudocodeforgroupmembershipcheck foreachi ∈ GROUP_TYPES

CHAPTER 10. PSEUDOCODE 66

sent by the node, so the frequency for the beacons of speci�c group remainsthe same.

Algorithm 5 Pseudocode for leader beacon generationRequire: beaconIndex = value from last execution of the algorithm (= 0 in

�rst execution)beaconIndexAux⇐ beaconIndexbeaconIndex⇐ beaconIndex + 1while beaconIndexAux 6= beaconIndex and mote is not leaderfor groups[beaconIndex] and mote is not in handover for groups[beaconIndex] do

beaconIndex⇐ beaconIndex + 1if beaconIndex /∈ GROUP_TY PES then

beaconIndex⇐ 0if activeGroupsCounter 6= 0 then

nextShot⇐ DEFAULT_TIME/activeGroupsCounterelse

nextShot⇐ DEFAULT_TIMEend ifactiveGroupsCounter ⇐ 0

end ifend whileif mote is leader for groups[beaconIndex] ormote is in handover for groups[beaconIndex] then

update groups[beaconIndex] state infoactiveGroupsCounter ⇐ activeGroupsCounter + 1schedule leader beacon transmission

end ifschedule next execution of leader beacon generation in nextShot ms

10.1.5 Leader beacon forwardingThis algorithm is executed whenever a leader beacon is received. In or-der to achieve this execution scheme, the algorithm is implemented in thereceive associated with the TinyOS component that handles the transmis-sion/reception of the packets with the ID associated with leader beacons.

The algorithm checks whether the leader beacon is to be forwarder, accord-ing to the criteria described in section 4.4.1. If so, the algorithm updates the

Page 6: Chapter10 Pseudocodebibing.us.es/proyectos/abreproy/11364/fichero/memoria%2F10_Pseu… · CHAPTER10. PSEUDOCODE 64 Algorithm3Pseudocodeforgroupmembershipcheck foreachi ∈ GROUP_TYPES

CHAPTER 10. PSEUDOCODE 67

information about the last received beacon for that group ID schedules a newbeacon transmission (alg. 7). In case the node is a member of the group,and the received beacon has the handover �ag set, the node automaticallybecomes leader of that group. Note that when the previous leader sends ahandover message, its destination address is not a broadcast address, but theaddress of some member of the group.

10.1.6 Leader beacon transmissionThis algorithm, implemented by using a TinyOS task, sends a leader beacon,by request of either algorithm 5 or 6. Since it is implemented in a task,it cannot received parameters. Thus, information about which group thebeacon belongs to must be passed by component variables.

10.1.7 Attribute updatingThis algorithm is scheduled for periodic execution by alg. 2 once the at-tributes have been correctly initialized. Algorithm is implemented as the�red event for a timer used for this purpose. The mission of this algorithmis to update the attribute values array.

Most attributes come from a sensor reading. Many sensors in the motemight share the same ADC. Thus, an attempt to update several sensor read-ings at the same time might end up with only one sensor reading correctlyupdated and the rest not updated because the ADC was busy obtaining thereading for the �rst sensor. One solution to this problem is to update theattributes in a sequence, establishing a time between readings that allows theADC to get reading for the next conversion. That solution is implementedin this algorithm. The index of the next algorithm to be read is stored in acomponent variable so it can be accessed next time the timer is �red.

It must be taken into account that the attribute update in TinySchema isa split-phase operation [4] (see also A). In consequence, this algorithm justasks TinySchema for updated attribute values, and then TinySchema signalsan event through which it returns the updated value. This event is describedin section 10.1.8.

10.1.8 New attribute value readyAs stated before, attribute updating in TinySchema is a split-phase op-eration. Thus, it is necessary to implement a function to be invoked by

Page 7: Chapter10 Pseudocodebibing.us.es/proyectos/abreproy/11364/fichero/memoria%2F10_Pseu… · CHAPTER10. PSEUDOCODE 64 Algorithm3Pseudocodeforgroupmembershipcheck foreachi ∈ GROUP_TYPES

CHAPTER 10. PSEUDOCODE 68

Algorithm 6 Pseudocode for leader beacon forwarding (Executed on beaconreception)Require: beaconIndex as global variableif receivedBeacon.destination = BROADCAST_ADDRESS‖ receivedBeacon.destination = LOCAL_ADDRESS then

i← receivedBeacon.groupTypereceivedWeight← receivedBeacon.weightknownWeight← groups[i].weightreceivedGroupID ← receivedBeacon.groupIDknownGroupID ← groups[i].groupIDreceivedDepth← receivedBeacon.depthknownDepth← groups[i].depthseqNo← receivedBeacon.seqNolastSeqNo← groups[i].seqNoif groups[i] is KNOWN ‖ receivedWeight >knownWeight ‖ (receivedWeight =knownWeight && receivedGroupID > knownGroupID) ‖(receivedWeight = knownWeight && receivedGroupID =knownGroupID && knownDepth − 1 > receivedDepth) ‖(receivedWeight = knownWeight && receivedGroupID =knownGroupID && knownDepth − 1 = receivedDepth && seqNo 6=lastSeqNo) then

update groups[i] group info with beacon dataupdate time for last received beacon for groups[i]if groups[i] is UNKOWN ‖ groups[i] is in handover then

groups[i]← KNOWNelseif node is LEADER of groups[i] ‖ node is MEMBER of groups[i]thenif receivedBeacon.handOver = true then

groups[i]← LEADERupdate groups[i] group info

elsegroups[i]← MEMBER

end ifbeaconIndex← receivedBeacon.groupTypeschedule beacon transmission 7

end ifend if

end ifend if

Page 8: Chapter10 Pseudocodebibing.us.es/proyectos/abreproy/11364/fichero/memoria%2F10_Pseu… · CHAPTER10. PSEUDOCODE 64 Algorithm3Pseudocodeforgroupmembershipcheck foreachi ∈ GROUP_TYPES

CHAPTER 10. PSEUDOCODE 69

Algorithm 7 Pseudocode for leader beacon transmissionRequire: beaconIndex updated from algorithm 5 or 6Require: beaconBuffer beacon that is to be sentRequire: sendTo address of the node(s) to which the beacon is to be sent

sendTo← BROADCAST_ADDRESSif beaconMsgBusy = false then

beaconMsgBusy = trueif node is LEADER of groups[beaconIndex] ‖ node is in handover then

groups[beaconIndex].seqNo + +if node is in handover then

beaconBuffer.handOver ← truesendTo← groups[beaconIndex].parentNode

end ifend if�ll beaconBuffer with groups[beaconIndex] state infoif send(beaconBuffer) = ERROR then

beaconMsgBusy = false {Send is a split-phase operation. If there isno error beaconMsgBusy is set to false when transmission �nishes}

end ifend if

Algorithm 8 Pseudocode for Attribute updating (scheduled for periodicexecution)Require: nextAttribute = index of next attribute to be updatedif getAttribute(nextAttribute) = ERROR then

attribute[nextAttribute] ← 0 {getAttribute(nextAttribute) either ini-tiates a split-phase operation (for return function see algorithm 9) orreturns an error code}

end ifnextAttribute← nextAttribute + 1if nextAttribute ≥ NUM_ATTRIBUTES then

nextAttribute← 0end if

Page 9: Chapter10 Pseudocodebibing.us.es/proyectos/abreproy/11364/fichero/memoria%2F10_Pseu… · CHAPTER10. PSEUDOCODE 64 Algorithm3Pseudocodeforgroupmembershipcheck foreachi ∈ GROUP_TYPES

CHAPTER 10. PSEUDOCODE 70

TinySchema when the new value for the attribute is ready. This algorithmdescribes how that function updates the attribute values array with the newvalue for an attribute.

Algorithm 9 Pseudocode for new attribute value readyRequire: attributeV alue[] global table for attribute valuesRequire: attributeData attribute value provided by TinySchema {for infor-

mation about TinySchema, see [4]}if error = false then

i← getAttributeIndex()attributeV alue[i]← attributeDataSchedule group membership check (algorithm 3)

elseattributeV alue[i]← 0

end if

10.1.9 Leader weight update upon data receptionThis section describes the algorithm that carries out the increase in leader'sweight to allow subsequent suboptimal leader election and contention resolu-tion distributed algorithms (see section 4.4.1). This algorithm is invoked fromChannelMng when new channel data is received from other nodes. Channeldata is used to increased the weight of the leader of the group that is associ-ated with that channel. Weight is proportionally increased with the numberof measurements that were taken into account to

Algorithm 10 Pseudocode for weight update upon data receptionRequire: i group index for data receivedRequire: sender sender node's IDRequire: deltaWeight value to be add to current weight {It is related to

the number of nodes that added information to the received packet (seealgorithm 19)}groups[i].parentNode← senderif groups[i].weight < MAX_WEIGHT − deltaWeight then

groups[i].weight← groups[i].weight + deltaWeightelse

groups[i].weight←MAX_WEIGHTend if

Page 10: Chapter10 Pseudocodebibing.us.es/proyectos/abreproy/11364/fichero/memoria%2F10_Pseu… · CHAPTER10. PSEUDOCODE 64 Algorithm3Pseudocodeforgroupmembershipcheck foreachi ∈ GROUP_TYPES

CHAPTER 10. PSEUDOCODE 71

10.1.10 New group Drip packet received through serialport

Whenever a new Drip packet related to group de�nitions is received throughthe serial port, component PacketInjector handles it and then noti�esGroupMngabout the newly received packet. Noti�cation is carried out by using inter-face NewDrip. NewDrip's GroupMng implementation consists in one onlycommand. Implemented algorithm is described here.

Algorithm 11 Pseudocode for new group Drip packet received through serialport

bu�er new packetnotify Drip instance about new packet

10.2 Component ChannelMngThis component starts all its variables and then waits for GroupMng toprovide it with information about established groups. This information ispassed in an event-based manner, so component is set to sleep after variableinitialization and the wakes up when GroupMng delivers the information.

Algorithm 12 Global pseudocode for ChannelMngInitialize all components variables

10.2.1 Algorithm for group membership and attributeinformation received from GroupMng

As soon as GroupMng is able to provide information about group state andattributes this algorithm is invoked from algorithm 2, allowing ChannelMngto access that information and begin managing channels.

Once ChannelMng has received this pointers, it can start to monitor groupsand channels to determine whether it is necessary to publish data on anychannel. Channel activity check is performed in algorithm 15. Thus, thisalgorithm schedules algorithm 15 for periodic execution.

Page 11: Chapter10 Pseudocodebibing.us.es/proyectos/abreproy/11364/fichero/memoria%2F10_Pseu… · CHAPTER10. PSEUDOCODE 64 Algorithm3Pseudocodeforgroupmembershipcheck foreachi ∈ GROUP_TYPES

CHAPTER 10. PSEUDOCODE 72

Algorithm 13 Pseudocode for group information and attributes access en-abled by GroupMngRequire: attributes[] = component array to store updated attributes dataRequire: attributesP tr = pointer to attribute updated data received fromGroupMng

Require: groups[] = component array containing information about groupmembership

Require: groupsPtr = pointer to group membership information receivedfrom GroupMngattributes← attributeP trgroups← groupsPtrSchedule periodic execution of channel activity check algorithm (alg. 15)

10.2.2 New channel de�nition receivedThis algorithm is executed every time there is a change in channel de�nitions.New channel de�nitions are received through Drip. Packets containing thisde�nition information are passed to ChannelMng through the Receive inter-face wired to the corresponding Drip instance.

Both active and idle channels are include in the message received. Idlechannels are identi�ed by their `attribute' �eld, which contains a specialvalue indicating that the channel is not active.

Algorithm 14 Pseudocode for new channel de�nition receivedRequire: newChannelDefinition = message received containing all chan-

nel de�nitionsRequire: channels[] = array containing information about the active chan-

nelsfor each i ∈ CHANNELS doif channels[i].rate 6= newChannelDefinition.channel[i].rate then

Stop periodic execution of data publishing for channel iSchedule periodic execution of data publishing for channel i with pe-riod channels[i].period ms {this schedules execution of algorithm 17}

end ifchannels[i]← newChannelDefinition.channel[i]

end for

Page 12: Chapter10 Pseudocodebibing.us.es/proyectos/abreproy/11364/fichero/memoria%2F10_Pseu… · CHAPTER10. PSEUDOCODE 64 Algorithm3Pseudocodeforgroupmembershipcheck foreachi ∈ GROUP_TYPES

CHAPTER 10. PSEUDOCODE 73

10.2.3 Channel activity checkThis algorithm is implemented as the �red event for a timer. This timeris con�gured to periodically signal the �red event. Timer con�guration iscarried out by algorithm 13.

For every channel, the algorithm checks whether the channel is active.If that is the case, the algorithm checks whether mote's group membershipsatis�es group-channel association, that is, it checks that the mote belongs toany group associated to the channel. In this phase, it must take into accountthat the channel might be associated with all the groups of a certain type,or even to all the groups in general. This group membership check is carriedout by algorithm 16.

If algorithm 16 determines that group membership conditions are satis�ed,then a timer is scheduled to publish data on the channel at the speci�ed rate,unless it was already set by a previous execution of the algorithm, in whichcase it is not necessary to do anything for that channel. Were the conditionsnot satis�ed, or the group not de�ned, the algorithm would stop the timerassociated with that channel.

Note: it has been said that if the mote must publish on a channel and thetimer for that channel is already set, there is nothing to do for that channel.In fact, it is possible to handle it that way because changes in the publishrate once the channel has been established are managed by channel de�nitionupdate algorithm (see section 10.2.2).

10.2.4 Check group membership for a speci�c channelThis algorithm checks whether the node meets the conditions to publishon a certain channel. This is determined by examining group membership.The algorithm receives as parameters the channel ID, and the group typeand group ID information related to the channel. Special values such asGROUP_ID_ALL and GROUP_TYPE_ALL are allowed on these param-eters.

10.2.5 Channel data publishingThis algorithm is implemented as the �red event for a timer that is set foreach channel by algorithm 15. There is one timer for each channel. Only

Page 13: Chapter10 Pseudocodebibing.us.es/proyectos/abreproy/11364/fichero/memoria%2F10_Pseu… · CHAPTER10. PSEUDOCODE 64 Algorithm3Pseudocodeforgroupmembershipcheck foreachi ∈ GROUP_TYPES

CHAPTER 10. PSEUDOCODE 74

Algorithm 15 Pseudocode for channel activity checkfor each i ∈ CHANNELS doif channels[i].attribute 6= NOT_DEFINED then

groupType← channels[i].groupTypegroupID ← channels[i].groupIDif checkGroup(groupType, groupID, i) = true (call to algorithm 16)thenif channels[i].active = false then

channels[i].active← trueSchedule periodic execution of data publishing for channel i withperiod channels[i].period ms {this schedules execution of algo-rithm 17}

end ifelseif channels[i].active = true then

channels[i].active← falseStop periodic execution of data publishing for channel i

end ifend if

elseif channels[i].active = true then

channels[i].active← falseStop periodic execution of data publishing for channel i

end ifend if

end for

Page 14: Chapter10 Pseudocodebibing.us.es/proyectos/abreproy/11364/fichero/memoria%2F10_Pseu… · CHAPTER10. PSEUDOCODE 64 Algorithm3Pseudocodeforgroupmembershipcheck foreachi ∈ GROUP_TYPES

CHAPTER 10. PSEUDOCODE 75

Algorithm 16 Pseudocode for group membership conditions checkRequire: i = channel ID for which we want to check group membership

conditionsRequire: groupType = group type to which the channel is associated

{GROUP_TYPE_ALL is a possible value here}Require: groupID = group ID to which the channel is associated

{GROUP_ID_ALL is a possible value here}Require: channels[] = array containing information about the active chan-

nelsj = 0if groupType = GROUP_TYPE_ALL thenrepeatif node is LEADER OF groups[i] ‖ node is MEMBER of groups[i]then

channels[i].groupType = ireturn true

end ifi← i + 1

until i = NUMGROUPSelseif node is LEADER OF groups[groupType] ‖ node is MEMBER ofgroups[groupType] thenif groupID = GROUP_ID_ALL ‖ groupID =groups[groupType].groupID then

channels[i].groupType = groupTypereturn true

end ifend if

end ifreturn false

Page 15: Chapter10 Pseudocodebibing.us.es/proyectos/abreproy/11364/fichero/memoria%2F10_Pseu… · CHAPTER10. PSEUDOCODE 64 Algorithm3Pseudocodeforgroupmembershipcheck foreachi ∈ GROUP_TYPES

CHAPTER 10. PSEUDOCODE 76

timer associated with channels on which the mote must publish are actuallyactive, the rest are not set, so the mote is not woken up innecessarily.

Whenever the timer is �red, the algorithm aggregates data collected locallywith the data received from child nodes since last execution of the algorithm.Data received from other nodes is aggregated just as it is received (see section10.2.7). Lastly, channel data transmission is scheduled (alg. 18).

Algorithm 17 Pseudocode for channel data publishingRequire: i = channel ID in which the data is to be publishedRequire: data[] = array to store value to send to parent node (indexed by

channel ID)Require: measurements[] = array to store number of measurements that

were used to compute the value in data[] arrayRequire: attribute[] = array that contains the last value of each attribute.

This array is updated by GroupMng component (see algorithm 8)data[i]← data[i] + attribute[i]measurements[i]← measurements[i] + 1if putInQueue(i) = true then

Schedule channel data transmission {algorithm 18}end if

10.2.6 Channel data transmissionThis algorithm is implemented as a TinyOS task, scheduled for execution atthe last step of algorithm 17. It performs channel data transmission in eitherleader or member nodes, although there are some di�erences according tothe status of the node.

In the case of a member node, the data is sent through the multi-hop grouprouting tree. This tree has the leader as sink node. The data sent includes thesum of all the readings received from child nodes and the reading obtainedby the node itself. It also includes the number of measurements that havebeen taken into account to perform this sum. The objective is to provide theleader node with enough information to calculate the average readings in thewhole group.

When the node itself is the leader of the group, channel data is sent throughthe multi-hop global routing tree. This routing tree has the gateway as

Page 16: Chapter10 Pseudocodebibing.us.es/proyectos/abreproy/11364/fichero/memoria%2F10_Pseu… · CHAPTER10. PSEUDOCODE 64 Algorithm3Pseudocodeforgroupmembershipcheck foreachi ∈ GROUP_TYPES

CHAPTER 10. PSEUDOCODE 77

a sink. In this case, the sum of all the readings performed by the groupnodes is divided by the number of measurements that were used to calculatethat sum. The reading obtained by the leader node is also included in thisoperation. As a result, the data sent to the gateway contains the averageof all the readings in the group and the number of measurements that weretaken to calculate such average. The number of readings can be used toestimate the size (in nodes) of the group.

10.2.7 Channel data received from other group mem-bers

This algorithm, implemented as the receive event for the Receive interfaceassociated with the channel data for each channel, manages the aggregationof the received data with data received previously from other nodes.

Channel data messages are taken advantage of in order to collect infor-mation about the members. This information is used then by GroupMng toupdate the handover candidate and the leader's weight. (See also algorithms19, 5, 6 and 7).

10.3 Component AppMThis component implements the application functionality. The applicationmust register all the attributes that the mote is capable of providing. Inthis implementation we have considered that the application registers twoattributes, one for the TSR (Total Solar Radiation) sensor and another onefor the PAR (Photosynthetically Active Radiation) sensor. The registrationis done by using TinySchema (see section 3.4). The application (that is,this module) must provide a callback function to obtain the readings of eachsensor. This component also implements callback functions for attribute ini-tialization. However, in this implementation these functions do not actuallyperform any action, since ADC converter (used by both TSR and PAR sen-sors) is initialize when node boots. For that reason, initialization functionsare not described here.

10.3.1 Attribute update callbackThis section describes the algorithm implemented to read the sensors when anattribute update is requested. In the implementation, TinySchema calls oneof these function (which are implemented in AppM component) whenever a

Page 17: Chapter10 Pseudocodebibing.us.es/proyectos/abreproy/11364/fichero/memoria%2F10_Pseu… · CHAPTER10. PSEUDOCODE 64 Algorithm3Pseudocodeforgroupmembershipcheck foreachi ∈ GROUP_TYPES

CHAPTER 10. PSEUDOCODE 78

Algorithm 18 Pseudocode for channel data transmissionRequire: data[] = array to store value to send to parent node (indexed by

channel ID)Require: measurements[] = array to store number of measurements that

were used to compute the value in data[] arrayRequire: msgBusy[] = array that contains �ags for every channel indicating

whether a data transmission is taking place for that channelRequire: handoverCandidates[] = array that contains the candidates for

handover for each group. This information is collected by ChannelMngand is passed to GroupMng

Require: msgBuffer[i] = bu�ers for message data (one per channel)Require: sent = �ag for message successfully sent. Initially set to falseif queueIsEmpty() = false then

i← popFromQueue()if measurements[i] > 0 && msgBusy[i] = false then

msgBusy[i] = true{Data transmission is split-phase operation. This�ag is set back to falsein the event for �nished data transmission}if node is MEMBER of groups[i] then

Fill msgBuffer[i] with measurements[i] and data[i]Fill auxiliary �elds of msgBuffer[i] (sender, etc.)if send(msgBuffer[i],GROUPROUTINGT REE) 6= ERRORthen

sent← trueend if

elseif node is LEADER of groups[i] then

data[i]← data[i]/measurements[i]Fill msgBuffer[i] with measurements[i] and data[i]Fill auxiliary �elds of msgBuffer[i] (sender, etc.)Inform GroupMng about measurements[i] so that leader weightcan be updatedInform GroupMng about handoverCandidates[i] so that leaderweight can be updatedif send(msgBuffer[i],GLOBALROUTINGT REE) 6= ERRORthen

sent← trueend if

end ifend ifif sent = false then

msgBusy[i] = falseend ifdata[i]← 0measurements[i]← 0

end ifend if

Page 18: Chapter10 Pseudocodebibing.us.es/proyectos/abreproy/11364/fichero/memoria%2F10_Pseu… · CHAPTER10. PSEUDOCODE 64 Algorithm3Pseudocodeforgroupmembershipcheck foreachi ∈ GROUP_TYPES

CHAPTER 10. PSEUDOCODE 79

Algorithm 19 Pseudocode for channel data received from other group mem-bersRequire: i = channel ID of received dataRequire: data[] = array to store the value received from another node. The

value is added to perform an AVG aggregation (indexed by channel ID)Require: measurements[] = array to store number of measurements that

were used to compute the value in data[] arrayRequire: handoverCandidates[] = array that contains the candidates for

handover for each group. This information is to be passed to GroupMng,but is collected by ChannelMng since the latter handles channel data re-ception

Require: groupID = group ID to which the channel is associatedRequire: receivedData = channel data receivedRequire: receivedMeasurements = number of measurements that were

taken into account by the child node to compute the value of receivedData.This value is also sent by the child node.

Require: sender = sender's IDmeasurements[i]← measurements[i] + receivedMeasurementsdata[i]← data[i] + receivedDataif node is LEADER of groups[i] then

handoverCandidates[i]← senderend if

Algorithm 20 Global pseudocode for component AppMRegister attribute TSR as attribute 0Register attribute PAR as attribute 1Notify AttrMng (see section 10.4) about attribute registration complete

Page 19: Chapter10 Pseudocodebibing.us.es/proyectos/abreproy/11364/fichero/memoria%2F10_Pseu… · CHAPTER10. PSEUDOCODE 64 Algorithm3Pseudocodeforgroupmembershipcheck foreachi ∈ GROUP_TYPES

CHAPTER 10. PSEUDOCODE 80

component asks for an attribute value update. Attribute update as de�ned inTinySchema is a split-phase operation. Sensors used in this implementationare also read in a split-phase way. Thus, in this function no useful data isreturned in the resultBuffer provided by TinySchema, since the value ofthe reading is no to be know until the split-phase operation to read the sensorhas �nished.

Algorithm 21 Pseudocode for TSR attribute update callback functionRequire: TSRBusy = Component variable that indicates whether there is

a TSR reading taking placeRequire: TSRBuffer = Component bu�er to store value provided by TSR

after the split-phase reading operationRequire: TSRState = Component bu�er to return operation when the sen-

sor reading split-phased-operation is �nishedRequire: schemaState = Bu�er provided by TinySchema to return the

state of the update operationRequire: resultBuffer = Bu�er provided by TinySchema to return the

result of the attribute updateif TSRBusy = false then

TSRBusy ← true∗schemaState← SCHEMA_RESULT_PENDINGTSRBuffer ← resultBufferTSRState← schemaStateif Start ADC conversion for TSR = ERROR then∗schemaState← SCHEMA_ERRORTSRBusy ← false

end ifelse∗schemaState← SCHEMA_ERROR

end if

10.3.2 Sensor reading readySensor reading is split-phase operation. Thus, when a new reading is re-quested, TinyOS signals an event as soon as the reading is ready, allowingthe CPU to be put to sleep or complete other tasks in the meantime. Thissection describes the algorithm executed when the sensor reading process has�nished and the value returned is available.

Page 20: Chapter10 Pseudocodebibing.us.es/proyectos/abreproy/11364/fichero/memoria%2F10_Pseu… · CHAPTER10. PSEUDOCODE 64 Algorithm3Pseudocodeforgroupmembershipcheck foreachi ∈ GROUP_TYPES

CHAPTER 10. PSEUDOCODE 81

Algorithm 22 Pseudocode for PAR attribute update callback functionRequire: PARBusy = Component variable that indicates whether there is

a PAR reading taking placeRequire: PARBuffer = Component bu�er to store value provided by PAR

after the split-phase reading operationRequire: PARState = Component bu�er to return operation when the

sensor reading split-phased-operation is �nishedRequire: schemaState = Bu�er provided by TinySchema to return the

state of the update operationRequire: resultBuffer = Bu�er provided by TinySchema to return the

result of the attribute updateif PARBusy = false then

PARBusy ← true∗schemaState← SCHEMA_RESULT_PENDINGPARBuffer ← resultBufferPARState← schemaStateif Start ADC conversion for PAR = ERROR then∗schemaState← SCHEMA_ERRORPARBusy ← false

end ifelse∗schemaState← SCHEMA_ERROR

end if

Algorithm 23 Pseudocode for TSR reading process �nishedRequire: data = Value returned by the sensorRequire: TSRBuffer = Component bu�er to store value provided by TSR

after the split-phase reading operation. This value has been previouslyinitialized by algorithm 21

Require: TSRBusy = Component variable that indicates whether there isa TSR reading taking place

Require: TSRState = Component bu�er to return operation when the sen-sor reading split-phased-operation is �nished. This value has been previ-ously initialized by algorithm 21∗TSRBuffer ← data/8TSRBusy = falseTSRState = SCHEMA_RESULT_READYNotify TinySchema about attribute update �nished, result in TSRState,data in TSRBuffer

Page 21: Chapter10 Pseudocodebibing.us.es/proyectos/abreproy/11364/fichero/memoria%2F10_Pseu… · CHAPTER10. PSEUDOCODE 64 Algorithm3Pseudocodeforgroupmembershipcheck foreachi ∈ GROUP_TYPES

CHAPTER 10. PSEUDOCODE 82

Algorithm 24 Pseudocode for PAR reading process �nishedRequire: data = Value returned by the sensorRequire: PARBuffer = Component bu�er to store value provided by PAR

after the split-phase reading operation. This value has been previouslyinitialized by algorithm 22

Require: PARBusy = Component variable that indicates whether there isa PAR reading taking place

Require: PARState = Component bu�er to return operation when thesensor reading split-phased-operation is �nished. This value has been pre-viously initialized by algorithm 22∗PARBuffer ← data/8PARBusy = falsePARState = SCHEMA_RESULT_READYNotify TinySchema about attribute update �nished, result in PARState,data in PARBuffer

10.4 Component AttrMngThis component waits until attributes have been registered, and then it per-forms an attribute initialization. Please note that sensors are initialized atboot time as described in section 10.3. However, attributes are not. It mustbe taken into account that attributes provide a general abstraction, and arenot restricted to sensor readings. In order to make a coherent implemen-tation it is necessary to initialize TinySchema attributes, even if they onlyprovide values from sensor that needn't be initialized.

Algorithm 25 Global pseudocode for AttrMng componentInitialize component variablesSleep until noti�cation from AppM that the attributes have been registered(see algorithm 20)

10.4.1 Attributes registered noti�cation from AppMNext algorithm is executed when AppM noti�es AttrMng that attribute reg-istration has �nished. Then, attributes can be initialized by AttrMng. At-tribute initialization provided by TinySchema is a split-phase operation [4].Thus, after initialization has been performed, an event is generated to in-form about initialization complete. This event is implemented by AttrMng.However, there is nothing to do in that event and the function just returns

Page 22: Chapter10 Pseudocodebibing.us.es/proyectos/abreproy/11364/fichero/memoria%2F10_Pseu… · CHAPTER10. PSEUDOCODE 64 Algorithm3Pseudocodeforgroupmembershipcheck foreachi ∈ GROUP_TYPES

CHAPTER 10. PSEUDOCODE 83

a non-error condition. That is the reason why that event is not described asa separate algorithm here.

Algorithm 26 Pseudocode for attribute initialization completeRequire: TSRStarted = Component variable that indicates whether the

attribute for TSR readings has been startedRequire: PARStarted = Component variable that indicates whether the

attribute for PAR readings has been startedif TSRStarted = false thenif Ask TinySchema for TSR attribute initialization = SUCCESS then

TSRStarted← trueend ifif Ask TinySchema for PAR attribute initialization = SUCCESS then

PARStarted← trueend if

end if

10.5 Component PacketInjectorThis component manages all the packets that are received through the motesserial port. These messages come from the PC, and they contain informa-tion about the de�ned groups and channels. Whenever a new packet isreceived, this component checks that it corresponds to a Drip packet (see7.2.3) and delivers it to the appropriate component: GroupMng for packetscontaining group de�nitions and ChannelMng for packets that contain chan-nel de�nitions. In case the received packet contains a command, it noti�esCommandMng for command execution.

After component initialization, PacketInjector waits for an incoming packetreceived by the mote's UART. Once the packet is received, it begins process-ing it. Noti�cations to GroupMng, ChannelMng and CommandMng takeplace by using NewDrip interface.

Algorithm 27 Global algorithm for component PacketInjectorComponent initializationSleep until packet is received

Page 23: Chapter10 Pseudocodebibing.us.es/proyectos/abreproy/11364/fichero/memoria%2F10_Pseu… · CHAPTER10. PSEUDOCODE 64 Algorithm3Pseudocodeforgroupmembershipcheck foreachi ∈ GROUP_TYPES

CHAPTER 10. PSEUDOCODE 84

10.5.1 Received packet from UARTPacketInjector uses SPReceive interface (see [6]). Whenever a packet hasbeen received, SP component -to which PacketInjector is wired by inter-face SPReceive- signals the receive event. Implementation of this event incomponent PacketInjector is described by this algorithm.

The algorithm makes a copy of the message for later processing and thenschedules the processing algorithm (alg. 29) for execution.

Algorithm 28 Pseudocode for UART packet receptionRequire: msgBuffer = component bu�er to store the received messageRequire: receivedMsg = bu�er containing the receive message∗msgBuffer ← ∗receivedMsgSchedule execution of processing algorithm

10.5.2 Process UART packetUART packet processing is implemented as a TinyOS task. This task isscheduled for execution by algorithm 28, after a new packet has been receivedthrough the UART.

Algorithm 29 Pseudocode for UART packet processingRequire: msgBuffer = component bu�er containing the last message re-

ceived through the UARTif msgBuffer− > type = DRIP_GROUP then

Notify GroupMng about new group de�nitionselseif msgBuffer− > type = DRIP_CHANNEL then

Notify ChannelMng about new channel de�nitionselseif msgBuffer− > type = DRIP_COMMAND then

Notify CommandMng about new commandend if

end ifend if