1: Initialization:

2: P is the node position

3: BS is the sink position

4: R is the sink transmission range

5: OUTPUT: I D is the ID of the chosen gateway

6: L (u) = Ď• //List of ID and Metrics of candidate gateways

7: if (isCH) then

8: if (dist (P, BS) < R) then //No need for gateway, send directly to base station

9: sendToBS()

10: while (t < Synchro_ADV _GW) do

11: if (receivedADV _GW (v, metric)) then

12: add (v, metric, L (u))

13: end if

14: end while

15: if (card (L (u)) == 1) then

16: sendToGW (L(u) (0)) //only one available gateway, use it to send

17: else

18: choiceBestGw(L(u)) //to choose the best gateway from the list L (u) based on the lowest gateway candidates’ metrics

19: end if

20: end if

21: end if