Contiki 2.5
lpp.c
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2008, Swedish Institute of Computer Science.
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  * notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  * notice, this list of conditions and the following disclaimer in the
12  * documentation and/or other materials provided with the distribution.
13  * 3. Neither the name of the Institute nor the names of its contributors
14  * may be used to endorse or promote products derived from this software
15  * without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  *
29  * This file is part of the Contiki operating system.
30  *
31  * $Id: lpp.c,v 1.40 2010/12/02 15:55:17 dak664 Exp $
32  */
33 
34 /**
35  * \file
36  * Low power probing (R. Musaloiu-Elefteri, C. Liang,
37  * A. Terzis. Koala: Ultra-Low Power Data Retrieval in
38  * Wireless Sensor Networks, IPSN 2008)
39  *
40  * \author
41  * Adam Dunkels <adam@sics.se>
42  *
43  *
44  * This is an implementation of the LPP (Low-Power Probing) MAC
45  * protocol. LPP is a power-saving MAC protocol that works by sending
46  * a probe packet each time the radio is turned on. If another node
47  * wants to transmit a packet, it can do so after hearing the
48  * probe. To send a packet, the sending node turns on its radio to
49  * listen for probe packets.
50  *
51  */
52 
53 #include "dev/leds.h"
54 #include "lib/list.h"
55 #include "lib/memb.h"
56 #include "lib/random.h"
57 #include "net/rime.h"
58 #include "net/netstack.h"
59 #include "net/mac/mac.h"
60 #include "net/mac/lpp.h"
61 #include "net/packetbuf.h"
62 #include "net/rime/announcement.h"
63 #include "sys/compower.h"
64 
65 #include <stdlib.h>
66 #include <stdio.h>
67 #include <string.h>
68 
69 #define DEBUG 0
70 #if DEBUG
71 #include <stdio.h>
72 #define PRINTF(...) printf(__VA_ARGS__)
73 #else
74 #define PRINTF(...)
75 #endif
76 
77 #define WITH_ACK_OPTIMIZATION 0
78 #define WITH_PROBE_AFTER_RECEPTION 0
79 #define WITH_PROBE_AFTER_TRANSMISSION 0
80 #define WITH_ENCOUNTER_OPTIMIZATION 0
81 #define WITH_ADAPTIVE_OFF_TIME 0
82 #define WITH_PENDING_BROADCAST 0
83 #define WITH_STREAMING 1
84 
85 #define LISTEN_TIME (CLOCK_SECOND / 128)
86 #define OFF_TIME (CLOCK_SECOND / NETSTACK_RDC_CHANNEL_CHECK_RATE - LISTEN_TIME)
87 
88 #define PACKET_LIFETIME (LISTEN_TIME + OFF_TIME)
89 #define UNICAST_TIMEOUT (1 * PACKET_LIFETIME + PACKET_LIFETIME / 2)
90 #define PROBE_AFTER_TRANSMISSION_TIME (LISTEN_TIME * 2)
91 
92 #define LOWEST_OFF_TIME (CLOCK_SECOND / 8)
93 
94 #define ENCOUNTER_LIFETIME (16 * OFF_TIME)
95 
96 #ifdef QUEUEBUF_CONF_NUM
97 #define MAX_QUEUED_PACKETS QUEUEBUF_CONF_NUM / 2
98 #else /* QUEUEBUF_CONF_NUM */
99 #define MAX_QUEUED_PACKETS 4
100 #endif /* QUEUEBUF_CONF_NUM */
101 
102 
103 /* If CLOCK_SECOND is less than 4, we may end up with an OFF_TIME that
104  is 0 which will make compilation fail due to a modulo operation in
105  the code. To ensure that OFF_TIME is greater than zero, we use the
106  construct below. */
107 #if OFF_TIME < 2
108 #undef OFF_TIME
109 #define OFF_TIME 2
110 #endif
111 
112 struct announcement_data {
113  uint16_t id;
114  uint16_t value;
115 };
116 
117 #define ANNOUNCEMENT_MSG_HEADERLEN 2
118 struct announcement_msg {
119  uint16_t num;
120  struct announcement_data data[];
121 };
122 
123 #define LPP_PROBE_HEADERLEN 2
124 
125 #define TYPE_PROBE 1
126 #define TYPE_DATA 2
127 struct lpp_hdr {
128  uint16_t type;
129  rimeaddr_t sender;
130  rimeaddr_t receiver;
131 };
132 
133 static uint8_t lpp_is_on;
134 
135 static struct compower_activity current_packet;
136 
137 static struct pt dutycycle_pt;
138 static struct ctimer timer;
139 
140 static uint8_t is_listening = 0;
141 static clock_time_t off_time_adjustment = 0;
142 static clock_time_t off_time = OFF_TIME;
143 
144 struct queue_list_item {
145  struct queue_list_item *next;
146  struct queuebuf *packet;
147  struct ctimer removal_timer;
148  struct compower_activity compower;
149  mac_callback_t sent_callback;
150  void *sent_callback_ptr;
151  uint8_t num_transmissions;
152 #if WITH_PENDING_BROADCAST
153  uint8_t broadcast_flag;
154 #endif /* WITH_PENDING_BROADCAST */
155 };
156 
157 #define BROADCAST_FLAG_NONE 0
158 #define BROADCAST_FLAG_WAITING 1
159 #define BROADCAST_FLAG_PENDING 2
160 #define BROADCAST_FLAG_SEND 3
161 
162 LIST(pending_packets_list);
163 LIST(queued_packets_list);
164 MEMB(queued_packets_memb, struct queue_list_item, MAX_QUEUED_PACKETS);
165 
166 struct encounter {
167  struct encounter *next;
168  rimeaddr_t neighbor;
169  clock_time_t time;
170  struct ctimer remove_timer;
171  struct ctimer turn_on_radio_timer;
172 };
173 
174 #define MAX_ENCOUNTERS 4
175 LIST(encounter_list);
176 MEMB(encounter_memb, struct encounter, MAX_ENCOUNTERS);
177 
178 static uint8_t is_streaming = 0;
179 #if WITH_STREAMING
180 static struct ctimer stream_probe_timer, stream_off_timer;
181 #define STREAM_PROBE_TIME CLOCK_SECOND / 128
182 #define STREAM_OFF_TIME CLOCK_SECOND / 2
183 #endif /* WITH_STREAMING */
184 
185 #ifndef MIN
186 #define MIN(a, b) ((a) < (b)? (a) : (b))
187 #endif /* MIN */
188 
189 /*---------------------------------------------------------------------------*/
190 static void
191 turn_radio_on(void)
192 {
193  NETSTACK_RADIO.on();
194  /* leds_on(LEDS_YELLOW);*/
195 }
196 /*---------------------------------------------------------------------------*/
197 static void
198 turn_radio_off(void)
199 {
200  if(lpp_is_on && is_streaming == 0) {
201  NETSTACK_RADIO.off();
202  }
203  /* leds_off(LEDS_YELLOW);*/
204 }
205 /*---------------------------------------------------------------------------*/
206 static void
207 remove_encounter(void *encounter)
208 {
209  struct encounter *e = encounter;
210 
211  ctimer_stop(&e->remove_timer);
212  ctimer_stop(&e->turn_on_radio_timer);
213  list_remove(encounter_list, e);
214  memb_free(&encounter_memb, e);
215 }
216 /*---------------------------------------------------------------------------*/
217 static void
218 register_encounter(rimeaddr_t *neighbor, clock_time_t time)
219 {
220  struct encounter *e;
221 
222  /* If we have an entry for this neighbor already, we renew it. */
223  for(e = list_head(encounter_list); e != NULL; e = list_item_next(e)) {
224  if(rimeaddr_cmp(neighbor, &e->neighbor)) {
225  e->time = time;
226  ctimer_set(&e->remove_timer, ENCOUNTER_LIFETIME, remove_encounter, e);
227  break;
228  }
229  }
230  /* No matchin encounter was found, so we allocate a new one. */
231  if(e == NULL) {
232  e = memb_alloc(&encounter_memb);
233  if(e == NULL) {
234  /* We could not allocate memory for this encounter, so we just drop it. */
235  return;
236  }
237  rimeaddr_copy(&e->neighbor, neighbor);
238  e->time = time;
239  ctimer_set(&e->remove_timer, ENCOUNTER_LIFETIME, remove_encounter, e);
240  list_add(encounter_list, e);
241  }
242 }
243 
244 #if WITH_ENCOUNTER_OPTIMIZATION
245 /*---------------------------------------------------------------------------*/
246 static void
247 turn_radio_on_callback(void *packet)
248 {
249  struct queue_list_item *p = packet;
250 
251  list_remove(pending_packets_list, p);
252  list_add(queued_packets_list, p);
253  turn_radio_on();
254 
255  /* printf("enc\n");*/
256 }
257 #endif /* WITH_ENCOUNTER_OPTIMIZATION */
258 
259 /*---------------------------------------------------------------------------*/
260 static void
261 stream_off(void *dummy)
262 {
263  is_streaming = 0;
264 }
265 /*---------------------------------------------------------------------------*/
266 /* This function goes through all encounters to see if it finds a
267  matching neighbor. If so, we set a ctimer that will turn on the
268  radio just before we expect the neighbor to send a probe packet. If
269  we cannot find a matching encounter, we just turn on the radio.
270 
271  The outbound packet is put on either the pending_packets_list or
272  the queued_packets_list, depending on if the packet should be sent
273  immediately.
274 */
275 static void
276 turn_radio_on_for_neighbor(rimeaddr_t *neighbor, struct queue_list_item *i)
277 {
278 
279 #if WITH_STREAMING
280  if(packetbuf_attr(PACKETBUF_ATTR_PACKET_TYPE) ==
281  PACKETBUF_ATTR_PACKET_TYPE_STREAM) {
282  is_streaming = 1;
283  turn_radio_on();
284  list_add(queued_packets_list, i);
285  ctimer_set(&stream_off_timer, STREAM_OFF_TIME,
286  stream_off, NULL);
287  return;
288  }
289 #endif /* WITH_STREAMING */
290 
291  if(rimeaddr_cmp(neighbor, &rimeaddr_null)) {
292 #if ! WITH_PENDING_BROADCAST
293  /* We have been asked to turn on the radio for a broadcast, so we
294  just turn on the radio. */
295  turn_radio_on();
296 #endif /* ! WITH_PENDING_BROADCAST */
297  list_add(queued_packets_list, i);
298  return;
299  }
300 
301 #if WITH_ENCOUNTER_OPTIMIZATION
302  struct encounter *e;
303 
304  /* We go through the list of encounters to find if we have recorded
305  an encounter with this particular neighbor. If so, we can compute
306  the time for the next expected encounter and setup a ctimer to
307  switch on the radio just before the encounter. */
308  for(e = list_head(encounter_list); e != NULL; e = list_item_next(e)) {
309  if(rimeaddr_cmp(neighbor, &e->neighbor)) {
310  clock_time_t wait, now;
311 
312  /* We expect encounters to happen roughly every OFF_TIME time
313  units. The next expected encounter is at time e->time +
314  OFF_TIME. To compute a relative offset, we subtract with
315  clock_time(). Because we are only interested in turning on
316  the radio within the OFF_TIME period, we compute the waiting
317  time with modulo OFF_TIME. */
318 
319  now = clock_time();
320  wait = (((clock_time_t)(e->time - now)) % (OFF_TIME + LISTEN_TIME)) -
321  2 * LISTEN_TIME;
322 
323  /* printf("now %d e %d e-n %d w %d %d\n", now, e->time, e->time - now, (e->time - now) % (OFF_TIME), wait);
324 
325  printf("Time now %lu last encounter %lu next expected encouter %lu wait %lu/%d (%lu)\n",
326  (1000ul * (unsigned long)now) / CLOCK_SECOND,
327  (1000ul * (unsigned long)e->time) / CLOCK_SECOND,
328  (1000ul * (unsigned long)(e->time + OFF_TIME)) / CLOCK_SECOND,
329  (1000ul * (unsigned long)wait) / CLOCK_SECOND, wait,
330  (1000ul * (unsigned long)(wait + now)) / CLOCK_SECOND);*/
331 
332  /* printf("Neighbor %d.%d found encounter, waiting %d ticks\n",
333  neighbor->u8[0], neighbor->u8[1], wait);*/
334 
335  ctimer_set(&e->turn_on_radio_timer, wait, turn_radio_on_callback, i);
336  list_add(pending_packets_list, i);
337  return;
338  }
339  }
340 #endif /* WITH_ENCOUNTER_OPTIMIZATION */
341 
342  /* We did not find the neighbor in the list of recent encounters, so
343  we just turn on the radio. */
344  /* printf("Neighbor %d.%d not found in recent encounters\n",
345  neighbor->u8[0], neighbor->u8[1]);*/
346  turn_radio_on();
347  list_add(queued_packets_list, i);
348  return;
349 }
350 /*---------------------------------------------------------------------------*/
351 static void
352 remove_queued_packet(struct queue_list_item *i, uint8_t tx_ok)
353 {
354  mac_callback_t sent;
355  void *ptr;
356  int num_transmissions = 0;
357  int status;
358 
359  PRINTF("%d.%d: removing queued packet\n",
361 
362 
363  queuebuf_to_packetbuf(i->packet);
364 
365  ctimer_stop(&i->removal_timer);
366  queuebuf_free(i->packet);
367  list_remove(pending_packets_list, i);
368  list_remove(queued_packets_list, i);
369 
370  /* XXX potential optimization */
371  if(list_length(queued_packets_list) == 0 && is_listening == 0) {
372  turn_radio_off();
373  compower_accumulate(&i->compower);
374  }
375 
376  sent = i->sent_callback;
377  ptr = i->sent_callback_ptr;
378  num_transmissions = i->num_transmissions;
379  memb_free(&queued_packets_memb, i);
380  if(num_transmissions == 0 || tx_ok == 0) {
381  status = MAC_TX_NOACK;
382  } else {
383  status = MAC_TX_OK;
384  }
385  mac_call_sent_callback(sent, ptr, status, num_transmissions);
386 }
387 /*---------------------------------------------------------------------------*/
388 static void
389 remove_queued_old_packet_callback(void *item)
390 {
391  remove_queued_packet(item, 0);
392 }
393 
394 #if WITH_PENDING_BROADCAST
395 /*---------------------------------------------------------------------------*/
396 static void
397 remove_queued_broadcast_packet_callback(void *item)
398 {
399  remove_queued_packet(item, 1);
400 }
401 /*---------------------------------------------------------------------------*/
402 static void
403 set_broadcast_flag(struct queue_list_item *i, uint8_t flag)
404 {
405  i->broadcast_flag = flag;
406  ctimer_set(&i->removal_timer, PACKET_LIFETIME,
407  remove_queued_broadcast_packet_callback, i);
408 }
409 #endif /* WITH_PENDING_BROADCAST */
410 /*---------------------------------------------------------------------------*/
411 static void
412 listen_callback(int periods)
413 {
414  is_listening = periods;
415  turn_radio_on();
416 }
417 /*---------------------------------------------------------------------------*/
418 /**
419  * Send a probe packet.
420  */
421 static void
422 send_probe(void)
423 {
424  struct lpp_hdr *hdr;
425  struct announcement_msg *adata;
426  struct announcement *a;
427 
428  /* Set up the probe header. */
429  packetbuf_clear();
430  packetbuf_set_datalen(sizeof(struct lpp_hdr));
431  hdr = packetbuf_dataptr();
432  hdr->type = TYPE_PROBE;
433  rimeaddr_copy(&hdr->sender, &rimeaddr_node_addr);
434  /* rimeaddr_copy(&hdr->receiver, packetbuf_addr(PACKETBUF_ADDR_RECEIVER));*/
435  rimeaddr_copy(&hdr->receiver, &rimeaddr_null);
436 
437  packetbuf_set_addr(PACKETBUF_ADDR_RECEIVER, &rimeaddr_null);
438  {
439  int hdrlen = NETSTACK_FRAMER.create();
440  if(hdrlen == 0) {
441  /* Failed to send */
442  return;
443  }
444  }
445 
446  /* Construct the announcements */
447  adata = (struct announcement_msg *)((char *)hdr + sizeof(struct lpp_hdr));
448 
449  adata->num = 0;
450  for(a = announcement_list(); a != NULL; a = list_item_next(a)) {
451  adata->data[adata->num].id = a->id;
452  adata->data[adata->num].value = a->value;
453  adata->num++;
454  }
455 
456  packetbuf_set_datalen(sizeof(struct lpp_hdr) +
457  ANNOUNCEMENT_MSG_HEADERLEN +
458  sizeof(struct announcement_data) * adata->num);
459 
460  /* PRINTF("Sending probe\n");*/
461 
462  /* printf("probe\n");*/
463 
464  if(NETSTACK_RADIO.channel_clear()) {
465  NETSTACK_RADIO.send(packetbuf_hdrptr(), packetbuf_totlen());
466  } else {
467  off_time_adjustment = random_rand() % (OFF_TIME / 2);
468  }
469 
471 }
472 /*---------------------------------------------------------------------------*/
473 static void
474 send_stream_probe(void *dummy)
475 {
476  /* Turn on the radio for sending a probe packet and
477  anticipating a data packet from a neighbor. */
478  turn_radio_on();
479 
480  /* Send a probe packet. */
481  send_probe();
482 
483 #if WITH_STREAMING
484  is_streaming = 1;
485 #endif /* WITH_STREAMING */
486 }
487 /*---------------------------------------------------------------------------*/
488 static int
489 num_packets_to_send(void)
490 {
491 #if WITH_PENDING_BROADCAST
492  struct queue_list_item *i;
493  int num = 0;
494 
495  for(i = list_head(queued_packets_list); i != NULL; i = list_item_next(i)) {
496  if(i->broadcast_flag == BROADCAST_FLAG_SEND ||
497  i->broadcast_flag == BROADCAST_FLAG_NONE) {
498  ++num;
499  }
500  }
501  return num;
502 #else /* WITH_PENDING_BROADCAST */
503  return list_length(queued_packets_list);
504 #endif /* WITH_PENDING_BROADCAST */
505 }
506 /*---------------------------------------------------------------------------*/
507 /**
508  * Duty cycle the radio and send probes. This function is called
509  * repeatedly by a ctimer. The function restart_dutycycle() is used to
510  * (re)start the duty cycling.
511  */
512 static int
513 dutycycle(void *ptr)
514 {
515  struct ctimer *t = ptr;
516 
517  PT_BEGIN(&dutycycle_pt);
518 
519  while(1) {
520 
521 #if WITH_PENDING_BROADCAST
522  {
523  /* Before sending the probe, we mark all broadcast packets in
524  our output queue to be pending. This means that they are
525  ready to be sent, once we know that no neighbor is
526  currently broadcasting. */
527  for(p = list_head(queued_packets_list); p != NULL; p = list_item_next(p)) {
528  if(p->broadcast_flag == BROADCAST_FLAG_WAITING) {
529  PRINTF("wait -> pending\n");
530  set_broadcast_flag(p, BROADCAST_FLAG_PENDING);
531  }
532  }
533  }
534 #endif /* WITH_PENDING_BROADCAST */
535 
536  /* Turn on the radio for sending a probe packet and
537  anticipating a data packet from a neighbor. */
538  turn_radio_on();
539 
540  /* Send a probe packet. */
541  send_probe();
542 
543  /* Set a timer so that we keep the radio on for LISTEN_TIME. */
544  ctimer_set(t, LISTEN_TIME, (void (*)(void *))dutycycle, t);
545  PT_YIELD(&dutycycle_pt);
546 
547 #if WITH_PENDING_BROADCAST
548  {
549  struct queue_list_item *p;
550  /* Go through the list of packets we are waiting to send, and
551  check if there are any pending broadcasts in the list. If
552  there are pending broadcasts, and we did not receive any
553  broadcast packets from a neighbor in response to our probe,
554  we mark the broadcasts as being ready to send. */
555  for(p = list_head(queued_packets_list); p != NULL; p = list_item_next(p)) {
556  if(p->broadcast_flag == BROADCAST_FLAG_PENDING) {
557  PRINTF("pending -> send\n");
558  set_broadcast_flag(p, BROADCAST_FLAG_SEND);
559  turn_radio_on();
560  }
561  }
562  }
563 #endif /* WITH_PENDING_BROADCAST */
564 
565  /* If we have no packets to send (indicated by the list length of
566  queued_packets_list being zero), we should turn the radio
567  off. Othersize, we keep the radio on. */
568  if(num_packets_to_send() == 0) {
569 
570  /* If we are not listening for announcements, we turn the radio
571  off and wait until we send the next probe. */
572  if(is_listening == 0) {
573  int current_off_time;
574  if(!NETSTACK_RADIO.receiving_packet()) {
575  turn_radio_off();
577  }
578  current_off_time = off_time - off_time_adjustment;
579  if(current_off_time < LISTEN_TIME * 2) {
580  current_off_time = LISTEN_TIME * 2;
581  }
582  off_time_adjustment = 0;
583  ctimer_set(t, current_off_time, (void (*)(void *))dutycycle, t);
584  PT_YIELD(&dutycycle_pt);
585 
586 #if WITH_ADAPTIVE_OFF_TIME
587  off_time += LOWEST_OFF_TIME;
588  if(off_time > OFF_TIME) {
589  off_time = OFF_TIME;
590  }
591 #endif /* WITH_ADAPTIVE_OFF_TIME */
592 
593  } else {
594  /* We are listening for annonucements, so we count down the
595  listen time, and keep the radio on. */
596  is_listening--;
597  ctimer_set(t, OFF_TIME, (void (*)(void *))dutycycle, t);
598  PT_YIELD(&dutycycle_pt);
599  }
600  } else {
601  /* We had pending packets to send, so we do not turn the radio off. */
602 
603  ctimer_set(t, off_time, (void (*)(void *))dutycycle, t);
604  PT_YIELD(&dutycycle_pt);
605  }
606  }
607 
608  PT_END(&dutycycle_pt);
609 }
610 /*---------------------------------------------------------------------------*/
611 static void
612 restart_dutycycle(clock_time_t initial_wait)
613 {
614  PT_INIT(&dutycycle_pt);
615  ctimer_set(&timer, initial_wait, (void (*)(void *))dutycycle, &timer);
616 }
617 /*---------------------------------------------------------------------------*/
618 /**
619  *
620  * Send a packet. This function builds a complete packet with an LPP
621  * header and queues the packet. When a probe is heard (in the
622  * read_packet() function), and the sender of the probe matches the
623  * receiver of the queued packet, the queued packet is sent.
624  *
625  * ACK packets are treated differently from other packets: if a node
626  * sends a packet that it expects to be ACKed, the sending node keeps
627  * its radio on for some time after sending its packet. So we do not
628  * need to wait for a probe packet: we just transmit the ACK packet
629  * immediately.
630  *
631  */
632 static void
633 send_packet(mac_callback_t sent, void *ptr)
634 {
635  struct lpp_hdr hdr;
636  clock_time_t timeout;
637  uint8_t is_broadcast = 0;
638 
639  rimeaddr_copy(&hdr.sender, &rimeaddr_node_addr);
640  rimeaddr_copy(&hdr.receiver, packetbuf_addr(PACKETBUF_ADDR_RECEIVER));
641  if(rimeaddr_cmp(&hdr.receiver, &rimeaddr_null)) {
642  is_broadcast = 1;
643  }
644  hdr.type = TYPE_DATA;
645 
646  packetbuf_hdralloc(sizeof(struct lpp_hdr));
647  memcpy(packetbuf_hdrptr(), &hdr, sizeof(struct lpp_hdr));
649 
650  packetbuf_set_attr(PACKETBUF_ATTR_MAC_ACK, 1);
651 
652  {
653  int hdrlen = NETSTACK_FRAMER.create();
654  if(hdrlen == 0) {
655  /* Failed to send */
656  mac_call_sent_callback(sent, ptr, MAC_TX_ERR_FATAL, 0);
657  return;
658  }
659  }
660 
661  PRINTF("%d.%d: queueing packet to %d.%d, channel %d\n",
663  hdr.receiver.u8[0], hdr.receiver.u8[1],
664  packetbuf_attr(PACKETBUF_ATTR_CHANNEL));
665 #if WITH_ACK_OPTIMIZATION
666  if(packetbuf_attr(PACKETBUF_ATTR_PACKET_TYPE) == PACKETBUF_ATTR_PACKET_TYPE_ACK) {
667  /* Send ACKs immediately. */
668  NETSTACK_RADIO.send(packetbuf_hdrptr(), packetbuf_totlen());
669  mac_call_sent_callback(sent, ptr, MAC_TX_OK, 1);
670  return;
671  }
672 #endif /* WITH_ACK_OPTIMIZATION */
673 
674 #if WITH_ADAPTIVE_OFF_TIME
675  off_time = LOWEST_OFF_TIME;
676  restart_dutycycle(off_time);
677 #endif /* WITH_ADAPTIVE_OFF_TIME */
678 
679  {
680  struct queue_list_item *i;
681  i = memb_alloc(&queued_packets_memb);
682  if(i != NULL) {
683  i->sent_callback = sent;
684  i->sent_callback_ptr = ptr;
685  i->num_transmissions = 0;
686  i->packet = queuebuf_new_from_packetbuf();
687  if(i->packet == NULL) {
688  memb_free(&queued_packets_memb, i);
689  printf("null packet\n");
690  mac_call_sent_callback(sent, ptr, MAC_TX_ERR, 0);
691  return;
692  } else {
693  if(is_broadcast) {
694  timeout = PACKET_LIFETIME;
695 #if WITH_PENDING_BROADCAST
696  /* We set the broadcast state of the packet to be
697  waiting. This means that the packet is waiting for our
698  next probe to be sent. Our next probe is used to check if
699  there are any neighbors currently broadcasting a
700  packet. If so, we will get a broadcast packet in response
701  to our probe. If no broadcast packet is received in
702  response to our probe, we mark the packet as ready to be
703  sent. */
704  set_broadcast_flag(i, BROADCAST_FLAG_WAITING);
705  PRINTF("-> waiting\n");
706 #endif /* WITH_PENDING_BROADCAST */
707  } else {
708  timeout = UNICAST_TIMEOUT;
709 #if WITH_PENDING_BROADCAST
710  i->broadcast_flag = BROADCAST_FLAG_NONE;
711 #endif /* WITH_PENDING_BROADCAST */
712  }
713  ctimer_set(&i->removal_timer, timeout,
714  remove_queued_old_packet_callback, i);
715 
716  /* Wait for a probe packet from a neighbor. The actual packet
717  transmission is handled by the read_packet() function,
718  which receives the probe from the neighbor. */
719  turn_radio_on_for_neighbor(&hdr.receiver, i);
720 
721  }
722  } else {
723  printf("i == NULL\n");
724  mac_call_sent_callback(sent, ptr, MAC_TX_ERR, 0);
725  }
726  }
727 }
728 /*---------------------------------------------------------------------------*/
729 static int
730 detect_ack(void)
731 {
732 #define INTER_PACKET_INTERVAL RTIMER_ARCH_SECOND / 5000
733 #define ACK_LEN 3
734 #define AFTER_ACK_DETECTECT_WAIT_TIME RTIMER_ARCH_SECOND / 1000
735  rtimer_clock_t wt;
736  uint8_t ack_received = 0;
737 
738  wt = RTIMER_NOW();
739  leds_on(LEDS_GREEN);
740  while(RTIMER_CLOCK_LT(RTIMER_NOW(), wt + INTER_PACKET_INTERVAL)) { }
741  leds_off(LEDS_GREEN);
742  /* Check for incoming ACK. */
743  if((NETSTACK_RADIO.receiving_packet() ||
744  NETSTACK_RADIO.pending_packet() ||
745  NETSTACK_RADIO.channel_clear() == 0)) {
746  int len;
747  uint8_t ackbuf[ACK_LEN + 2];
748 
749  wt = RTIMER_NOW();
750  while(RTIMER_CLOCK_LT(RTIMER_NOW(), wt + AFTER_ACK_DETECTECT_WAIT_TIME)) { }
751 
752  len = NETSTACK_RADIO.read(ackbuf, ACK_LEN);
753  if(len == ACK_LEN) {
754  ack_received = 1;
755  }
756  }
757  if(ack_received) {
758  leds_toggle(LEDS_RED);
759  }
760  return ack_received;
761 }
762 /*---------------------------------------------------------------------------*/
763 /**
764  * Read a packet from the underlying radio driver. If the incoming
765  * packet is a probe packet and the sender of the probe matches the
766  * destination address of the queued packet (if any), the queued packet
767  * is sent.
768  */
769 static void
770 input_packet(void)
771 {
772  struct lpp_hdr hdr;
773  clock_time_t reception_time;
774 
775  reception_time = clock_time();
776 
777  if(!NETSTACK_FRAMER.parse()) {
778  printf("lpp input_packet framer error\n");
779  }
780 
781  memcpy(&hdr, packetbuf_dataptr(), sizeof(struct lpp_hdr));;
782  packetbuf_hdrreduce(sizeof(struct lpp_hdr));
783  /* PRINTF("got packet type %d\n", hdr->type);*/
784 
785  if(hdr.type == TYPE_PROBE) {
786  struct announcement_msg adata;
787 
788  /* Register the encounter with the sending node. We now know the
789  neighbor's phase. */
790  register_encounter(&hdr.sender, reception_time);
791 
792  /* Parse incoming announcements */
793  memcpy(&adata, packetbuf_dataptr(),
794  MIN(packetbuf_datalen(), sizeof(adata)));
795 #if 0
796  PRINTF("%d.%d: probe from %d.%d with %d announcements\n",
798  hdr.sender.u8[0], hdr.sender.u8[1], adata->num);
799 
800  if(adata.num / sizeof(struct announcement_data) > sizeof(struct announcement_msg)) {
801  /* Sanity check. The number of announcements is too large -
802  corrupt packet has been received. */
803  return 0;
804  }
805 
806  for(i = 0; i < adata.num; ++i) {
807  /* PRINTF("%d.%d: announcement %d: %d\n",
808  rimeaddr_node_addr.u8[0], rimeaddr_node_addr.u8[1],
809  adata->data[i].id,
810  adata->data[i].value);*/
811 
812  announcement_heard(&hdr.sender,
813  adata.data[i].id,
814  adata.data[i].value);
815  }
816 #endif /* 0 */
817 
818  /* Go through the list of packets to be sent to see if any of
819  them match the sender of the probe, or if they are a
820  broadcast packet that should be sent. */
821  if(list_length(queued_packets_list) > 0) {
822  struct queue_list_item *i;
823  for(i = list_head(queued_packets_list); i != NULL; i = list_item_next(i)) {
824  const rimeaddr_t *receiver;
825  uint8_t sent;
826 
827  sent = 0;
828 
829  receiver = queuebuf_addr(i->packet, PACKETBUF_ADDR_RECEIVER);
830  if(rimeaddr_cmp(receiver, &hdr.sender) ||
831  rimeaddr_cmp(receiver, &rimeaddr_null)) {
832  queuebuf_to_packetbuf(i->packet);
833 
834 #if WITH_PENDING_BROADCAST
835  if(i->broadcast_flag == BROADCAST_FLAG_NONE ||
836  i->broadcast_flag == BROADCAST_FLAG_SEND) {
837  i->num_transmissions = 1;
838  NETSTACK_RADIO.send(queuebuf_dataptr(i->packet),
839  queuebuf_datalen(i->packet));
840  sent = 1;
841  PRINTF("%d.%d: got a probe from %d.%d, sent packet to %d.%d\n",
843  hdr.sender.u8[0], hdr.sender.u8[1],
844  receiver->u8[0], receiver->u8[1]);
845 
846  } else {
847  PRINTF("%d.%d: got a probe from %d.%d, did not send packet\n",
849  hdr.sender.u8[0], hdr.sender.u8[1]);
850  }
851 #else /* WITH_PENDING_BROADCAST */
852  i->num_transmissions = 1;
853  NETSTACK_RADIO.send(queuebuf_dataptr(i->packet),
854  queuebuf_datalen(i->packet));
855  PRINTF("%d.%d: got a probe from %d.%d, sent packet to %d.%d\n",
857  hdr.sender.u8[0], hdr.sender.u8[1],
858  receiver->u8[0], receiver->u8[1]);
859 #endif /* WITH_PENDING_BROADCAST */
860 
861  /* off();*/
862 
863  /* Attribute the energy spent on listening for the probe
864  to this packet transmission. */
865  compower_accumulate(&i->compower);
866 
867  /* If the packet was not a broadcast packet, we dequeue it
868  now. Broadcast packets should be transmitted to all
869  neighbors, and are dequeued by the dutycycling function
870  instead, after the appropriate time. */
871  if(!rimeaddr_cmp(receiver, &rimeaddr_null)) {
872  if(detect_ack()) {
873  remove_queued_packet(i, 1);
874  } else {
875  remove_queued_packet(i, 0);
876  }
877 
878 #if WITH_PROBE_AFTER_TRANSMISSION
879  /* Send a probe packet to catch any reply from the other node. */
880  restart_dutycycle(PROBE_AFTER_TRANSMISSION_TIME);
881 #endif /* WITH_PROBE_AFTER_TRANSMISSION */
882 
883 #if WITH_STREAMING
884  if(is_streaming) {
885  ctimer_set(&stream_probe_timer, STREAM_PROBE_TIME,
886  send_stream_probe, NULL);
887  }
888 #endif /* WITH_STREAMING */
889  }
890 
891  if(sent) {
892  turn_radio_off();
893  }
894 
895 #if WITH_ACK_OPTIMIZATION
896  if(packetbuf_attr(PACKETBUF_ATTR_RELIABLE) ||
897  packetbuf_attr(PACKETBUF_ATTR_ERELIABLE)) {
898  /* We're sending a packet that needs an ACK, so we keep
899  the radio on in anticipation of the ACK. */
900  turn_radio_on();
901  }
902 #endif /* WITH_ACK_OPTIMIZATION */
903 
904  }
905  }
906  }
907 
908  } else if(hdr.type == TYPE_DATA) {
909  turn_radio_off();
910  if(!rimeaddr_cmp(&hdr.receiver, &rimeaddr_null)) {
911  if(!rimeaddr_cmp(&hdr.receiver, &rimeaddr_node_addr)) {
912  /* Not broadcast or for us */
913  PRINTF("%d.%d: data not for us from %d.%d\n",
915  hdr.sender.u8[0], hdr.sender.u8[1]);
916  return;
917  }
918  packetbuf_set_addr(PACKETBUF_ADDR_RECEIVER, &hdr.receiver);
919  }
920  packetbuf_set_addr(PACKETBUF_ADDR_SENDER, &hdr.sender);
921 
922  PRINTF("%d.%d: got data from %d.%d\n",
924  hdr.sender.u8[0], hdr.sender.u8[1]);
925 
926  /* Accumulate the power consumption for the packet reception. */
927  compower_accumulate(&current_packet);
928  /* Convert the accumulated power consumption for the received
929  packet to packet attributes so that the higher levels can
930  keep track of the amount of energy spent on receiving the
931  packet. */
932  compower_attrconv(&current_packet);
933 
934  /* Clear the accumulated power consumption so that it is ready
935  for the next packet. */
936  compower_clear(&current_packet);
937 
938 #if WITH_PENDING_BROADCAST
939  if(rimeaddr_cmp(&hdr.receiver, &rimeaddr_null)) {
940  /* This is a broadcast packet. Check the list of pending
941  packets to see if we are currently sending a broadcast. If
942  so, we refrain from sending our broadcast until one sleep
943  cycle period, so that the other broadcaster will have
944  finished sending. */
945 
946  struct queue_list_item *i;
947  for(i = list_head(queued_packets_list); i != NULL; i = list_item_next(i)) {
948  /* If the packet is a broadcast packet that is not yet
949  ready to be sent, we do not send it. */
950  if(i->broadcast_flag == BROADCAST_FLAG_PENDING) {
951  PRINTF("Someone else is sending, pending -> waiting\n");
952  set_broadcast_flag(i, BROADCAST_FLAG_WAITING);
953  }
954  }
955  }
956 #endif /* WITH_PENDING_BROADCAST */
957 
958 
959 #if WITH_PROBE_AFTER_RECEPTION
960  /* XXX send probe after receiving a packet to facilitate data
961  streaming. We must first copy the contents of the packetbuf into
962  a queuebuf to avoid overwriting the data with the probe packet. */
963  if(rimeaddr_cmp(&hdr.receiver, &rimeaddr_node_addr)) {
964  struct queuebuf *q;
965  q = queuebuf_new_from_packetbuf();
966  if(q != NULL) {
967  send_probe();
968  queuebuf_to_packetbuf(q);
969  queuebuf_free(q);
970  }
971  }
972 #endif /* WITH_PROBE_AFTER_RECEPTION */
973 
974 #if WITH_ADAPTIVE_OFF_TIME
975  off_time = LOWEST_OFF_TIME;
976  restart_dutycycle(off_time);
977 #endif /* WITH_ADAPTIVE_OFF_TIME */
978 
979  NETSTACK_MAC.input();
980  }
981 }
982 /*---------------------------------------------------------------------------*/
983 static int
984 on(void)
985 {
986  lpp_is_on = 1;
987  turn_radio_on();
988  return 1;
989 }
990 /*---------------------------------------------------------------------------*/
991 static int
992 off(int keep_radio_on)
993 {
994  lpp_is_on = 0;
995  if(keep_radio_on) {
996  turn_radio_on();
997  } else {
998  turn_radio_off();
999  }
1000  return 1;
1001 }
1002 /*---------------------------------------------------------------------------*/
1003 static unsigned short
1004 channel_check_interval(void)
1005 {
1006  return OFF_TIME + LISTEN_TIME;
1007 }
1008 /*---------------------------------------------------------------------------*/
1009 static void
1010 init(void)
1011 {
1012  restart_dutycycle(random_rand() % OFF_TIME);
1013 
1014  lpp_is_on = 1;
1015 
1016  announcement_register_listen_callback(listen_callback);
1017 
1018  memb_init(&queued_packets_memb);
1019  list_init(queued_packets_list);
1020  list_init(pending_packets_list);
1021 }
1022 /*---------------------------------------------------------------------------*/
1023 const struct rdc_driver lpp_driver = {
1024  "LPP",
1025  init,
1026  send_packet,
1027  input_packet,
1028  on,
1029  off,
1031 };
1032 /*---------------------------------------------------------------------------*/