Contiki-Inga 3.x
contikimac.c
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2010, 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  */
32 
33 /**
34  * \file
35  * Implementation of the ContikiMAC power-saving radio duty cycling protocol
36  * \author
37  * Adam Dunkels <adam@sics.se>
38  * Niclas Finne <nfi@sics.se>
39  * Joakim Eriksson <joakime@sics.se>
40  */
41 
42 #include "contiki-conf.h"
43 #include "dev/leds.h"
44 #include "dev/radio.h"
45 #include "dev/watchdog.h"
46 #include "lib/random.h"
47 #include "net/mac/mac-sequence.h"
49 #include "net/netstack.h"
50 #include "net/rime/rime.h"
51 #include "sys/compower.h"
52 #include "sys/pt.h"
53 #include "sys/rtimer.h"
54 
55 
56 #include <string.h>
57 
58 /* TX/RX cycles are synchronized with neighbor wake periods */
59 #ifdef CONTIKIMAC_CONF_WITH_PHASE_OPTIMIZATION
60 #define WITH_PHASE_OPTIMIZATION CONTIKIMAC_CONF_WITH_PHASE_OPTIMIZATION
61 #else /* CONTIKIMAC_CONF_WITH_PHASE_OPTIMIZATION */
62 #define WITH_PHASE_OPTIMIZATION 1
63 #endif /* CONTIKIMAC_CONF_WITH_PHASE_OPTIMIZATION */
64 /* Two byte header added to allow recovery of padded short packets */
65 /* Wireshark will not understand such packets at present */
66 #ifdef CONTIKIMAC_CONF_WITH_CONTIKIMAC_HEADER
67 #define WITH_CONTIKIMAC_HEADER CONTIKIMAC_CONF_WITH_CONTIKIMAC_HEADER
68 #else
69 #define WITH_CONTIKIMAC_HEADER 1
70 #endif
71 /* More aggressive radio sleeping when channel is busy with other traffic */
72 #ifndef WITH_FAST_SLEEP
73 #define WITH_FAST_SLEEP 1
74 #endif
75 /* Radio does CSMA and autobackoff */
76 #ifndef RDC_CONF_HARDWARE_CSMA
77 #define RDC_CONF_HARDWARE_CSMA 0
78 #endif
79 /* Radio returns TX_OK/TX_NOACK after autoack wait */
80 #ifndef RDC_CONF_HARDWARE_ACK
81 #define RDC_CONF_HARDWARE_ACK 0
82 #endif
83 /* MCU can sleep during radio off */
84 #ifndef RDC_CONF_MCU_SLEEP
85 #define RDC_CONF_MCU_SLEEP 0
86 #endif
87 
88 #if NETSTACK_RDC_CHANNEL_CHECK_RATE >= 64
89 #undef WITH_PHASE_OPTIMIZATION
90 #define WITH_PHASE_OPTIMIZATION 0
91 #endif
92 
93 #if WITH_CONTIKIMAC_HEADER
94 #define CONTIKIMAC_ID 0x00
95 
96 struct hdr {
97  uint8_t id;
98  uint8_t len;
99 };
100 #endif /* WITH_CONTIKIMAC_HEADER */
101 
102 /* CYCLE_TIME for channel cca checks, in rtimer ticks. */
103 #ifdef CONTIKIMAC_CONF_CYCLE_TIME
104 #define CYCLE_TIME (CONTIKIMAC_CONF_CYCLE_TIME)
105 #else
106 #define CYCLE_TIME (RTIMER_ARCH_SECOND / NETSTACK_RDC_CHANNEL_CHECK_RATE)
107 #endif
108 
109 /* CHANNEL_CHECK_RATE is enforced to be a power of two.
110  * If RTIMER_ARCH_SECOND is not also a power of two, there will be an inexact
111  * number of channel checks per second due to the truncation of CYCLE_TIME.
112  * This will degrade the effectiveness of phase optimization with neighbors that
113  * do not have the same truncation error.
114  * Define SYNC_CYCLE_STARTS to ensure an integral number of checks per second.
115  */
116 #if RTIMER_ARCH_SECOND & (RTIMER_ARCH_SECOND - 1)
117 #define SYNC_CYCLE_STARTS 1
118 #endif
119 
120 /* Are we currently receiving a burst? */
121 static int we_are_receiving_burst = 0;
122 
123 /* INTER_PACKET_DEADLINE is the maximum time a receiver waits for the
124  next packet of a burst when FRAME_PENDING is set. */
125 #define INTER_PACKET_DEADLINE CLOCK_SECOND / 32
126 
127 /* ContikiMAC performs periodic channel checks. Each channel check
128  consists of two or more CCA checks. CCA_COUNT_MAX is the number of
129  CCAs to be done for each periodic channel check. The default is
130  two.*/
131 #ifdef CONTIKIMAC_CONF_CCA_COUNT_MAX
132 #define CCA_COUNT_MAX (CONTIKIMAC_CONF_CCA_COUNT_MAX)
133 #else
134 #define CCA_COUNT_MAX 2
135 #endif
136 
137 /* Before starting a transmission, Contikimac checks the availability
138  of the channel with CCA_COUNT_MAX_TX consecutive CCAs */
139 #ifdef CONTIKIMAC_CONF_CCA_COUNT_MAX_TX
140 #define CCA_COUNT_MAX_TX (CONTIKIMAC_CONF_CCA_COUNT_MAX_TX)
141 #else
142 #define CCA_COUNT_MAX_TX 6
143 #endif
144 
145 /* CCA_CHECK_TIME is the time it takes to perform a CCA check. */
146 /* Note this may be zero. AVRs have 7612 ticks/sec, but block until cca is done */
147 #ifdef CONTIKIMAC_CONF_CCA_CHECK_TIME
148 #define CCA_CHECK_TIME (CONTIKIMAC_CONF_CCA_CHECK_TIME)
149 #else
150 #define CCA_CHECK_TIME RTIMER_ARCH_SECOND / 8192
151 #endif
152 
153 /* CCA_SLEEP_TIME is the time between two successive CCA checks. */
154 /* Add 1 when rtimer ticks are coarse */
155 #if RTIMER_ARCH_SECOND > 8000
156 #define CCA_SLEEP_TIME RTIMER_ARCH_SECOND / 2000
157 #else
158 #define CCA_SLEEP_TIME (RTIMER_ARCH_SECOND / 2000) + 1
159 #endif
160 
161 /* CHECK_TIME is the total time it takes to perform CCA_COUNT_MAX
162  CCAs. */
163 #define CHECK_TIME (CCA_COUNT_MAX * (CCA_CHECK_TIME + CCA_SLEEP_TIME))
164 
165 /* CHECK_TIME_TX is the total time it takes to perform CCA_COUNT_MAX_TX
166  CCAs. */
167 #define CHECK_TIME_TX (CCA_COUNT_MAX_TX * (CCA_CHECK_TIME + CCA_SLEEP_TIME))
168 
169 /* LISTEN_TIME_AFTER_PACKET_DETECTED is the time that we keep checking
170  for activity after a potential packet has been detected by a CCA
171  check. */
172 #define LISTEN_TIME_AFTER_PACKET_DETECTED RTIMER_ARCH_SECOND / 80
173 
174 /* MAX_SILENCE_PERIODS is the maximum amount of periods (a period is
175  CCA_CHECK_TIME + CCA_SLEEP_TIME) that we allow to be silent before
176  we turn of the radio. */
177 #define MAX_SILENCE_PERIODS 5
178 
179 /* MAX_NONACTIVITY_PERIODS is the maximum number of periods we allow
180  the radio to be turned on without any packet being received, when
181  WITH_FAST_SLEEP is enabled. */
182 #define MAX_NONACTIVITY_PERIODS 10
183 
184 
185 
186 /* STROBE_TIME is the maximum amount of time a transmitted packet
187  should be repeatedly transmitted as part of a transmission. */
188 #define STROBE_TIME (CYCLE_TIME + 2 * CHECK_TIME)
189 
190 /* GUARD_TIME is the time before the expected phase of a neighbor that
191  a transmitted should begin transmitting packets. */
192 #define GUARD_TIME 10 * CHECK_TIME + CHECK_TIME_TX
193 
194 /* INTER_PACKET_INTERVAL is the interval between two successive packet transmissions */
195 #ifdef CONTIKIMAC_CONF_INTER_PACKET_INTERVAL
196 #define INTER_PACKET_INTERVAL CONTIKIMAC_CONF_INTER_PACKET_INTERVAL
197 #else
198 #define INTER_PACKET_INTERVAL RTIMER_ARCH_SECOND / 2500
199 #endif
200 
201 /* AFTER_ACK_DETECTECT_WAIT_TIME is the time to wait after a potential
202  ACK packet has been detected until we can read it out from the
203  radio. */
204 #ifdef CONTIKIMAC_CONF_AFTER_ACK_DETECTECT_WAIT_TIME
205 #define AFTER_ACK_DETECTECT_WAIT_TIME CONTIKIMAC_CONF_AFTER_ACK_DETECTECT_WAIT_TIME
206 #else
207 #define AFTER_ACK_DETECTECT_WAIT_TIME RTIMER_ARCH_SECOND / 1500
208 #endif
209 
210 /* MAX_PHASE_STROBE_TIME is the time that we transmit repeated packets
211  to a neighbor for which we have a phase lock. */
212 #define MAX_PHASE_STROBE_TIME RTIMER_ARCH_SECOND / 60
213 
214 
215 /* SHORTEST_PACKET_SIZE is the shortest packet that ContikiMAC
216  allows. Packets have to be a certain size to be able to be detected
217  by two consecutive CCA checks, and here is where we define this
218  shortest size.
219  Padded packets will have the wrong ipv6 checksum unless CONTIKIMAC_HEADER
220  is used (on both sides) and the receiver will ignore them.
221  With no header, reduce to transmit a proper multicast RPL DIS. */
222 #ifdef CONTIKIMAC_CONF_SHORTEST_PACKET_SIZE
223 #define SHORTEST_PACKET_SIZE CONTIKIMAC_CONF_SHORTEST_PACKET_SIZE
224 #else
225 #define SHORTEST_PACKET_SIZE 43
226 #endif
227 
228 
229 #define ACK_LEN 3
230 
231 #include <stdio.h>
232 static struct rtimer rt;
233 static struct pt pt;
234 
235 static volatile uint8_t contikimac_is_on = 0;
236 static volatile uint8_t contikimac_keep_radio_on = 0;
237 
238 static volatile unsigned char we_are_sending = 0;
239 static volatile unsigned char radio_is_on = 0;
240 
241 #define DEBUG 0
242 #if DEBUG
243 #include <stdio.h>
244 #define PRINTF(...) printf(__VA_ARGS__)
245 #define PRINTDEBUG(...) printf(__VA_ARGS__)
246 #else
247 #define PRINTF(...)
248 #define PRINTDEBUG(...)
249 #endif
250 
251 #if CONTIKIMAC_CONF_COMPOWER
252 static struct compower_activity current_packet;
253 #endif /* CONTIKIMAC_CONF_COMPOWER */
254 
255 #if WITH_PHASE_OPTIMIZATION
256 
257 #include "net/mac/phase.h"
258 
259 #endif /* WITH_PHASE_OPTIMIZATION */
260 
261 #define DEFAULT_STREAM_TIME (4 * CYCLE_TIME)
262 
263 #ifndef MIN
264 #define MIN(a, b) ((a) < (b)? (a) : (b))
265 #endif /* MIN */
266 
267 #if CONTIKIMAC_CONF_BROADCAST_RATE_LIMIT
268 static struct timer broadcast_rate_timer;
269 static int broadcast_rate_counter;
270 #endif /* CONTIKIMAC_CONF_BROADCAST_RATE_LIMIT */
271 
272 /*---------------------------------------------------------------------------*/
273 static void
274 on(void)
275 {
276  if(contikimac_is_on && radio_is_on == 0) {
277  radio_is_on = 1;
278  NETSTACK_RADIO.on();
279  }
280 }
281 /*---------------------------------------------------------------------------*/
282 static void
283 off(void)
284 {
285  if(contikimac_is_on && radio_is_on != 0 &&
286  contikimac_keep_radio_on == 0) {
287  radio_is_on = 0;
288  NETSTACK_RADIO.off();
289  }
290 }
291 /*---------------------------------------------------------------------------*/
292 static volatile rtimer_clock_t cycle_start;
293 static char powercycle(struct rtimer *t, void *ptr);
294 static void
295 schedule_powercycle(struct rtimer *t, rtimer_clock_t time)
296 {
297  int r;
298 
299  if(contikimac_is_on) {
300 
301  if(RTIMER_CLOCK_LT(RTIMER_TIME(t) + time, RTIMER_NOW() + 2)) {
302  time = RTIMER_NOW() - RTIMER_TIME(t) + 2;
303  }
304 
305  r = rtimer_set(t, RTIMER_TIME(t) + time, 1,
306  (void (*)(struct rtimer *, void *))powercycle, NULL);
307  if(r != RTIMER_OK) {
308  PRINTF("schedule_powercycle: could not set rtimer\n");
309  }
310  }
311 }
312 /*---------------------------------------------------------------------------*/
313 static void
314 schedule_powercycle_fixed(struct rtimer *t, rtimer_clock_t fixed_time)
315 {
316  int r;
317 
318  if(contikimac_is_on) {
319 
320  if(RTIMER_CLOCK_LT(fixed_time, RTIMER_NOW() + 1)) {
321  fixed_time = RTIMER_NOW() + 1;
322  }
323 
324  r = rtimer_set(t, fixed_time, 1,
325  (void (*)(struct rtimer *, void *))powercycle, NULL);
326  if(r != RTIMER_OK) {
327  PRINTF("schedule_powercycle: could not set rtimer\n");
328  }
329  }
330 }
331 /*---------------------------------------------------------------------------*/
332 static void
333 powercycle_turn_radio_off(void)
334 {
335 #if CONTIKIMAC_CONF_COMPOWER
336  uint8_t was_on = radio_is_on;
337 #endif /* CONTIKIMAC_CONF_COMPOWER */
338 
339  if(we_are_sending == 0 && we_are_receiving_burst == 0) {
340  off();
341 #if CONTIKIMAC_CONF_COMPOWER
342  if(was_on && !radio_is_on) {
344  }
345 #endif /* CONTIKIMAC_CONF_COMPOWER */
346  }
347 }
348 /*---------------------------------------------------------------------------*/
349 static void
350 powercycle_turn_radio_on(void)
351 {
352  if(we_are_sending == 0 && we_are_receiving_burst == 0) {
353  on();
354  }
355 }
356 /*---------------------------------------------------------------------------*/
357 static char
358 powercycle(struct rtimer *t, void *ptr)
359 {
360 #if SYNC_CYCLE_STARTS
361  static volatile rtimer_clock_t sync_cycle_start;
362  static volatile uint8_t sync_cycle_phase;
363 #endif
364 
365  PT_BEGIN(&pt);
366 
367 #if SYNC_CYCLE_STARTS
368  sync_cycle_start = RTIMER_NOW();
369 #else
370  cycle_start = RTIMER_NOW();
371 #endif
372 
373  while(1) {
374  static uint8_t packet_seen;
375  static rtimer_clock_t t0;
376  static uint8_t count;
377 
378 #if SYNC_CYCLE_STARTS
379  /* Compute cycle start when RTIMER_ARCH_SECOND is not a multiple
380  of CHANNEL_CHECK_RATE */
381  if(sync_cycle_phase++ == NETSTACK_RDC_CHANNEL_CHECK_RATE) {
382  sync_cycle_phase = 0;
383  sync_cycle_start += RTIMER_ARCH_SECOND;
384  cycle_start = sync_cycle_start;
385  } else {
386 #if (RTIMER_ARCH_SECOND * NETSTACK_RDC_CHANNEL_CHECK_RATE) > 65535
387  cycle_start = sync_cycle_start + ((unsigned long)(sync_cycle_phase*RTIMER_ARCH_SECOND))/NETSTACK_RDC_CHANNEL_CHECK_RATE;
388 #else
389  cycle_start = sync_cycle_start + (sync_cycle_phase*RTIMER_ARCH_SECOND)/NETSTACK_RDC_CHANNEL_CHECK_RATE;
390 #endif
391  }
392 #else
393  cycle_start += CYCLE_TIME;
394 #endif
395 
396  packet_seen = 0;
397 
398  for(count = 0; count < CCA_COUNT_MAX; ++count) {
399  t0 = RTIMER_NOW();
400  if(we_are_sending == 0 && we_are_receiving_burst == 0) {
401  powercycle_turn_radio_on();
402  /* Check if a packet is seen in the air. If so, we keep the
403  radio on for a while (LISTEN_TIME_AFTER_PACKET_DETECTED) to
404  be able to receive the packet. We also continuously check
405  the radio medium to make sure that we wasn't woken up by a
406  false positive: a spurious radio interference that was not
407  caused by an incoming packet. */
408  if(NETSTACK_RADIO.channel_clear() == 0) {
409  packet_seen = 1;
410  break;
411  }
412  powercycle_turn_radio_off();
413  }
414  schedule_powercycle_fixed(t, RTIMER_NOW() + CCA_SLEEP_TIME);
415  PT_YIELD(&pt);
416  }
417 
418  if(packet_seen) {
419  static rtimer_clock_t start;
420  static uint8_t silence_periods, periods;
421  start = RTIMER_NOW();
422 
423  periods = silence_periods = 0;
424  while(we_are_sending == 0 && radio_is_on &&
425  RTIMER_CLOCK_LT(RTIMER_NOW(),
426  (start + LISTEN_TIME_AFTER_PACKET_DETECTED))) {
427 
428  /* Check for a number of consecutive periods of
429  non-activity. If we see two such periods, we turn the
430  radio off. Also, if a packet has been successfully
431  received (as indicated by the
432  NETSTACK_RADIO.pending_packet() function), we stop
433  snooping. */
434 #if !RDC_CONF_HARDWARE_CSMA
435  /* A cca cycle will disrupt rx on some radios, e.g. mc1322x, rf230 */
436  /*TODO: Modify those drivers to just return the internal RSSI when already in rx mode */
437  if(NETSTACK_RADIO.channel_clear()) {
438  ++silence_periods;
439  } else {
440  silence_periods = 0;
441  }
442 #endif
443 
444  ++periods;
445 
446  if(NETSTACK_RADIO.receiving_packet()) {
447  silence_periods = 0;
448  }
449  if(silence_periods > MAX_SILENCE_PERIODS) {
450  powercycle_turn_radio_off();
451  break;
452  }
453  if(WITH_FAST_SLEEP &&
454  periods > MAX_NONACTIVITY_PERIODS &&
455  !(NETSTACK_RADIO.receiving_packet() ||
456  NETSTACK_RADIO.pending_packet())) {
457  powercycle_turn_radio_off();
458  break;
459  }
460  if(NETSTACK_RADIO.pending_packet()) {
461  break;
462  }
463 
464  schedule_powercycle(t, CCA_CHECK_TIME + CCA_SLEEP_TIME);
465  PT_YIELD(&pt);
466  }
467  if(radio_is_on) {
468  if(!(NETSTACK_RADIO.receiving_packet() ||
469  NETSTACK_RADIO.pending_packet()) ||
470  !RTIMER_CLOCK_LT(RTIMER_NOW(),
471  (start + LISTEN_TIME_AFTER_PACKET_DETECTED))) {
472  powercycle_turn_radio_off();
473  }
474  }
475  }
476 
477  if(RTIMER_CLOCK_LT(RTIMER_NOW() - cycle_start, CYCLE_TIME - CHECK_TIME * 4)) {
478  /* Schedule the next powercycle interrupt, or sleep the mcu
479  until then. Sleeping will not exit from this interrupt, so
480  ensure an occasional wake cycle or foreground processing will
481  be blocked until a packet is detected */
482 #if RDC_CONF_MCU_SLEEP
483  static uint8_t sleepcycle;
484  if((sleepcycle++ < 16) && !we_are_sending && !radio_is_on) {
485  rtimer_arch_sleep(CYCLE_TIME - (RTIMER_NOW() - cycle_start));
486  } else {
487  sleepcycle = 0;
488  schedule_powercycle_fixed(t, CYCLE_TIME + cycle_start);
489  PT_YIELD(&pt);
490  }
491 #else
492  schedule_powercycle_fixed(t, CYCLE_TIME + cycle_start);
493  PT_YIELD(&pt);
494 #endif
495  }
496  }
497 
498  PT_END(&pt);
499 }
500 /*---------------------------------------------------------------------------*/
501 static int
502 broadcast_rate_drop(void)
503 {
504 #if CONTIKIMAC_CONF_BROADCAST_RATE_LIMIT
505  if(!timer_expired(&broadcast_rate_timer)) {
506  broadcast_rate_counter++;
507  if(broadcast_rate_counter < CONTIKIMAC_CONF_BROADCAST_RATE_LIMIT) {
508  return 0;
509  } else {
510  return 1;
511  }
512  } else {
513  timer_set(&broadcast_rate_timer, CLOCK_SECOND);
514  broadcast_rate_counter = 0;
515  return 0;
516  }
517 #else /* CONTIKIMAC_CONF_BROADCAST_RATE_LIMIT */
518  return 0;
519 #endif /* CONTIKIMAC_CONF_BROADCAST_RATE_LIMIT */
520 }
521 /*---------------------------------------------------------------------------*/
522 static int
523 send_packet(mac_callback_t mac_callback, void *mac_callback_ptr,
524  struct rdc_buf_list *buf_list,
525  int is_receiver_awake)
526 {
527  rtimer_clock_t t0;
528  rtimer_clock_t encounter_time = 0;
529  int strobes;
530  uint8_t got_strobe_ack = 0;
531  int hdrlen, len;
532  uint8_t is_broadcast = 0;
533  uint8_t is_reliable = 0;
534  uint8_t is_known_receiver = 0;
535  uint8_t collisions;
536  int transmit_len;
537  int ret;
538  uint8_t contikimac_was_on;
539  uint8_t seqno;
540 #if WITH_CONTIKIMAC_HEADER
541  struct hdr *chdr;
542 #endif /* WITH_CONTIKIMAC_HEADER */
543 
544  /* Exit if RDC and radio were explicitly turned off */
545  if(!contikimac_is_on && !contikimac_keep_radio_on) {
546  PRINTF("contikimac: radio is turned off\n");
547  return MAC_TX_ERR_FATAL;
548  }
549 
550  if(packetbuf_totlen() == 0) {
551  PRINTF("contikimac: send_packet data len 0\n");
552  return MAC_TX_ERR_FATAL;
553  }
554 
555 #if !NETSTACK_CONF_BRIDGE_MODE
556  /* If NETSTACK_CONF_BRIDGE_MODE is set, assume PACKETBUF_ADDR_SENDER is already set. */
557  packetbuf_set_addr(PACKETBUF_ADDR_SENDER, &linkaddr_node_addr);
558 #endif
559  if(linkaddr_cmp(packetbuf_addr(PACKETBUF_ADDR_RECEIVER), &linkaddr_null)) {
560  is_broadcast = 1;
561  PRINTDEBUG("contikimac: send broadcast\n");
562 
563  if(broadcast_rate_drop()) {
564  return MAC_TX_COLLISION;
565  }
566  } else {
567 #if UIP_CONF_IPV6
568  PRINTDEBUG("contikimac: send unicast to %02x%02x:%02x%02x:%02x%02x:%02x%02x\n",
569  packetbuf_addr(PACKETBUF_ADDR_RECEIVER)->u8[0],
570  packetbuf_addr(PACKETBUF_ADDR_RECEIVER)->u8[1],
571  packetbuf_addr(PACKETBUF_ADDR_RECEIVER)->u8[2],
572  packetbuf_addr(PACKETBUF_ADDR_RECEIVER)->u8[3],
573  packetbuf_addr(PACKETBUF_ADDR_RECEIVER)->u8[4],
574  packetbuf_addr(PACKETBUF_ADDR_RECEIVER)->u8[5],
575  packetbuf_addr(PACKETBUF_ADDR_RECEIVER)->u8[6],
576  packetbuf_addr(PACKETBUF_ADDR_RECEIVER)->u8[7]);
577 #else /* UIP_CONF_IPV6 */
578  PRINTDEBUG("contikimac: send unicast to %u.%u\n",
579  packetbuf_addr(PACKETBUF_ADDR_RECEIVER)->u8[0],
580  packetbuf_addr(PACKETBUF_ADDR_RECEIVER)->u8[1]);
581 #endif /* UIP_CONF_IPV6 */
582  }
583  is_reliable = packetbuf_attr(PACKETBUF_ATTR_RELIABLE) ||
584  packetbuf_attr(PACKETBUF_ATTR_ERELIABLE);
585 
586  packetbuf_set_attr(PACKETBUF_ATTR_MAC_ACK, 1);
587 
588 #if WITH_CONTIKIMAC_HEADER
589  hdrlen = packetbuf_totlen();
590  if(packetbuf_hdralloc(sizeof(struct hdr)) == 0) {
591  /* Failed to allocate space for contikimac header */
592  PRINTF("contikimac: send failed, too large header\n");
593  return MAC_TX_ERR_FATAL;
594  }
595  chdr = packetbuf_hdrptr();
596  chdr->id = CONTIKIMAC_ID;
597  chdr->len = hdrlen;
598 
599  /* Create the MAC header for the data packet. */
600  hdrlen = NETSTACK_FRAMER.create();
601  if(hdrlen < 0) {
602  /* Failed to send */
603  PRINTF("contikimac: send failed, too large header\n");
604  packetbuf_hdr_remove(sizeof(struct hdr));
605  return MAC_TX_ERR_FATAL;
606  }
607  hdrlen += sizeof(struct hdr);
608 #else
609  /* Create the MAC header for the data packet. */
610  hdrlen = NETSTACK_FRAMER.create();
611  if(hdrlen < 0) {
612  /* Failed to send */
613  PRINTF("contikimac: send failed, too large header\n");
614  return MAC_TX_ERR_FATAL;
615  }
616 #endif
617 
618  /* Make sure that the packet is longer or equal to the shortest
619  packet length. */
620  transmit_len = packetbuf_totlen();
621  if(transmit_len < SHORTEST_PACKET_SIZE) {
622  /* Pad with zeroes */
623  uint8_t *ptr;
624  ptr = packetbuf_dataptr();
625  // memset(ptr + packetbuf_datalen(), 0, SHORTEST_PACKET_SIZE - packetbuf_totlen());
626 
627  printf("contikimac: shorter than shortest (%d)\n", packetbuf_totlen());
628  // transmit_len = SHORTEST_PACKET_SIZE;
629  }
630 
631 
633 
634 #ifdef NETSTACK_ENCRYPT
635  NETSTACK_ENCRYPT();
636 #endif /* NETSTACK_ENCRYPT */
637 
638  transmit_len = packetbuf_totlen();
639 
640  NETSTACK_RADIO.prepare(packetbuf_hdrptr(), transmit_len);
641 
642  /* Remove the MAC-layer header since it will be recreated next time around. */
643  packetbuf_hdr_remove(hdrlen);
644 
645  if(!is_broadcast && !is_receiver_awake) {
646 #if WITH_PHASE_OPTIMIZATION
647  ret = phase_wait(packetbuf_addr(PACKETBUF_ADDR_RECEIVER),
648  CYCLE_TIME, GUARD_TIME,
649  mac_callback, mac_callback_ptr, buf_list);
650  if(ret == PHASE_DEFERRED) {
651  return MAC_TX_DEFERRED;
652  }
653  if(ret != PHASE_UNKNOWN) {
654  is_known_receiver = 1;
655  }
656 #endif /* WITH_PHASE_OPTIMIZATION */
657  }
658 
659 
660 
661  /* By setting we_are_sending to one, we ensure that the rtimer
662  powercycle interrupt do not interfere with us sending the packet. */
663  we_are_sending = 1;
664 
665  /* If we have a pending packet in the radio, we should not send now,
666  because we will trash the received packet. Instead, we signal
667  that we have a collision, which lets the packet be received. This
668  packet will be retransmitted later by the MAC protocol
669  instread. */
670  if(NETSTACK_RADIO.receiving_packet() || NETSTACK_RADIO.pending_packet()) {
671  we_are_sending = 0;
672  PRINTF("contikimac: collision receiving %d, pending %d\n",
673  NETSTACK_RADIO.receiving_packet(), NETSTACK_RADIO.pending_packet());
674  return MAC_TX_COLLISION;
675  }
676 
677  /* Switch off the radio to ensure that we didn't start sending while
678  the radio was doing a channel check. */
679  off();
680 
681 
682  strobes = 0;
683 
684  /* Send a train of strobes until the receiver answers with an ACK. */
685  collisions = 0;
686 
687  got_strobe_ack = 0;
688 
689  /* Set contikimac_is_on to one to allow the on() and off() functions
690  to control the radio. We restore the old value of
691  contikimac_is_on when we are done. */
692  contikimac_was_on = contikimac_is_on;
693  contikimac_is_on = 1;
694 
695 #if !RDC_CONF_HARDWARE_CSMA
696  /* Check if there are any transmissions by others. */
697  /* TODO: why does this give collisions before sending with the mc1322x? */
698  if(is_receiver_awake == 0) {
699  int i;
700  for(i = 0; i < CCA_COUNT_MAX_TX; ++i) {
701  t0 = RTIMER_NOW();
702  on();
703 #if CCA_CHECK_TIME > 0
704  while(RTIMER_CLOCK_LT(RTIMER_NOW(), t0 + CCA_CHECK_TIME)) { }
705 #endif
706  if(NETSTACK_RADIO.channel_clear() == 0) {
707  collisions++;
708  off();
709  break;
710  }
711  off();
712  t0 = RTIMER_NOW();
713  while(RTIMER_CLOCK_LT(RTIMER_NOW(), t0 + CCA_SLEEP_TIME)) { }
714  }
715  }
716 
717  if(collisions > 0) {
718  we_are_sending = 0;
719  off();
720  PRINTF("contikimac: collisions before sending\n");
721  contikimac_is_on = contikimac_was_on;
722  return MAC_TX_COLLISION;
723  }
724 #endif /* RDC_CONF_HARDWARE_CSMA */
725 
726 #if !RDC_CONF_HARDWARE_ACK
727  if(!is_broadcast) {
728  /* Turn radio on to receive expected unicast ack. Not necessary
729  with hardware ack detection, and may trigger an unnecessary cca
730  or rx cycle */
731  on();
732  }
733 #endif
734 
736  t0 = RTIMER_NOW();
737  seqno = packetbuf_attr(PACKETBUF_ATTR_MAC_SEQNO);
738  for(strobes = 0, collisions = 0;
739  got_strobe_ack == 0 && collisions == 0 &&
740  RTIMER_CLOCK_LT(RTIMER_NOW(), t0 + STROBE_TIME); strobes++) {
741 
743 
744  if(!is_broadcast && (is_receiver_awake || is_known_receiver) &&
745  !RTIMER_CLOCK_LT(RTIMER_NOW(), t0 + MAX_PHASE_STROBE_TIME)) {
746  PRINTF("miss to %d\n", packetbuf_addr(PACKETBUF_ADDR_RECEIVER)->u8[0]);
747  break;
748  }
749 
750  len = 0;
751 
752  {
753  rtimer_clock_t wt;
754  rtimer_clock_t txtime;
755  int ret;
756 
757  txtime = RTIMER_NOW();
758  ret = NETSTACK_RADIO.transmit(transmit_len);
759 
760 #if RDC_CONF_HARDWARE_ACK
761  /* For radios that block in the transmit routine and detect the
762  ACK in hardware */
763  if(ret == RADIO_TX_OK) {
764  if(!is_broadcast) {
765  got_strobe_ack = 1;
766  encounter_time = txtime;
767  break;
768  }
769  } else if (ret == RADIO_TX_NOACK) {
770  } else if (ret == RADIO_TX_COLLISION) {
771  PRINTF("contikimac: collisions while sending\n");
772  collisions++;
773  }
774  wt = RTIMER_NOW();
775  while(RTIMER_CLOCK_LT(RTIMER_NOW(), wt + INTER_PACKET_INTERVAL)) { }
776 #else /* RDC_CONF_HARDWARE_ACK */
777  /* Wait for the ACK packet */
778  wt = RTIMER_NOW();
779  while(RTIMER_CLOCK_LT(RTIMER_NOW(), wt + INTER_PACKET_INTERVAL)) { }
780 
781  if(!is_broadcast && (NETSTACK_RADIO.receiving_packet() ||
782  NETSTACK_RADIO.pending_packet() ||
783  NETSTACK_RADIO.channel_clear() == 0)) {
784  uint8_t ackbuf[ACK_LEN];
785  wt = RTIMER_NOW();
786  while(RTIMER_CLOCK_LT(RTIMER_NOW(), wt + AFTER_ACK_DETECTECT_WAIT_TIME)) { }
787 
788  len = NETSTACK_RADIO.read(ackbuf, ACK_LEN);
789  if(len == ACK_LEN && seqno == ackbuf[ACK_LEN - 1]) {
790  got_strobe_ack = 1;
791  encounter_time = txtime;
792  break;
793  } else {
794  PRINTF("contikimac: collisions while sending\n");
795  collisions++;
796  }
797  }
798 #endif /* RDC_CONF_HARDWARE_ACK */
799  }
800  }
801 
802  off();
803 
804  PRINTF("contikimac: send (strobes=%u, len=%u, %s, %s), done\n", strobes,
806  got_strobe_ack ? "ack" : "no ack",
807  collisions ? "collision" : "no collision");
808 
809 #if CONTIKIMAC_CONF_COMPOWER
810  /* Accumulate the power consumption for the packet transmission. */
811  compower_accumulate(&current_packet);
812 
813  /* Convert the accumulated power consumption for the transmitted
814  packet to packet attributes so that the higher levels can keep
815  track of the amount of energy spent on transmitting the
816  packet. */
817  compower_attrconv(&current_packet);
818 
819  /* Clear the accumulated power consumption so that it is ready for
820  the next packet. */
821  compower_clear(&current_packet);
822 #endif /* CONTIKIMAC_CONF_COMPOWER */
823 
824  contikimac_is_on = contikimac_was_on;
825  we_are_sending = 0;
826 
827  /* Determine the return value that we will return from the
828  function. We must pass this value to the phase module before we
829  return from the function. */
830  if(collisions > 0) {
831  ret = MAC_TX_COLLISION;
832  } else if(!is_broadcast && !got_strobe_ack) {
833  ret = MAC_TX_NOACK;
834  } else {
835  ret = MAC_TX_OK;
836  }
837 
838 #if WITH_PHASE_OPTIMIZATION
839  if(is_known_receiver && got_strobe_ack) {
840  PRINTF("no miss %d wake-ups %d\n",
841  packetbuf_addr(PACKETBUF_ADDR_RECEIVER)->u8[0],
842  strobes);
843  }
844 
845  if(!is_broadcast) {
846  if(collisions == 0 && is_receiver_awake == 0) {
847  phase_update(packetbuf_addr(PACKETBUF_ADDR_RECEIVER),
848  encounter_time, ret);
849  }
850  }
851 #endif /* WITH_PHASE_OPTIMIZATION */
852 
853  return ret;
854 }
855 /*---------------------------------------------------------------------------*/
856 static void
857 qsend_packet(mac_callback_t sent, void *ptr)
858 {
859  int ret = send_packet(sent, ptr, NULL, 0);
860  if(ret != MAC_TX_DEFERRED) {
861  mac_call_sent_callback(sent, ptr, ret, 1);
862  }
863 }
864 /*---------------------------------------------------------------------------*/
865 static void
866 qsend_list(mac_callback_t sent, void *ptr, struct rdc_buf_list *buf_list)
867 {
868  struct rdc_buf_list *curr = buf_list;
869  struct rdc_buf_list *next;
870  int ret;
871  int is_receiver_awake;
872 
873  if(curr == NULL) {
874  return;
875  }
876  /* Do not send during reception of a burst */
877  if(we_are_receiving_burst) {
878  /* Prepare the packetbuf for callback */
879  queuebuf_to_packetbuf(curr->buf);
880  /* Return COLLISION so the MAC may try again later */
881  mac_call_sent_callback(sent, ptr, MAC_TX_COLLISION, 1);
882  return;
883  }
884  /* The receiver needs to be awoken before we send */
885  is_receiver_awake = 0;
886  do { /* A loop sending a burst of packets from buf_list */
887  next = list_item_next(curr);
888 
889  /* Prepare the packetbuf */
890  queuebuf_to_packetbuf(curr->buf);
891  if(next != NULL) {
892  packetbuf_set_attr(PACKETBUF_ATTR_PENDING, 1);
893  }
894 
895  /* Send the current packet */
896  ret = send_packet(sent, ptr, curr, is_receiver_awake);
897  if(ret != MAC_TX_DEFERRED) {
898  mac_call_sent_callback(sent, ptr, ret, 1);
899  }
900 
901  if(ret == MAC_TX_OK) {
902  if(next != NULL) {
903  /* We're in a burst, no need to wake the receiver up again */
904  is_receiver_awake = 1;
905  curr = next;
906  }
907  } else {
908  /* The transmission failed, we stop the burst */
909  next = NULL;
910  }
911  } while(next != NULL);
912 }
913 /*---------------------------------------------------------------------------*/
914 /* Timer callback triggered when receiving a burst, after having
915  waited for a next packet for a too long time. Turns the radio off
916  and leaves burst reception mode */
917 static void
918 recv_burst_off(void *ptr)
919 {
920  off();
921  we_are_receiving_burst = 0;
922 }
923 /*---------------------------------------------------------------------------*/
924 static void
925 input_packet(void)
926 {
927  static struct ctimer ct;
928  if(!we_are_receiving_burst) {
929  off();
930  }
931 
932  /* printf("cycle_start 0x%02x 0x%02x\n", cycle_start, cycle_start % CYCLE_TIME);*/
933 
934 #ifdef NETSTACK_DECRYPT
935  NETSTACK_DECRYPT();
936 #endif /* NETSTACK_DECRYPT */
937 
938  if(packetbuf_totlen() > 0 && NETSTACK_FRAMER.parse() >= 0) {
939 
940 #if WITH_CONTIKIMAC_HEADER
941  struct hdr *chdr;
942  chdr = packetbuf_dataptr();
943  if(chdr->id != CONTIKIMAC_ID) {
944  PRINTF("contikimac: failed to parse hdr (%u)\n", packetbuf_totlen());
945  return;
946  }
947  packetbuf_hdrreduce(sizeof(struct hdr));
948  packetbuf_set_datalen(chdr->len);
949 #endif /* WITH_CONTIKIMAC_HEADER */
950 
951  if(packetbuf_datalen() > 0 &&
952  packetbuf_totlen() > 0 &&
953  (linkaddr_cmp(packetbuf_addr(PACKETBUF_ADDR_RECEIVER),
954  &linkaddr_node_addr) ||
955  linkaddr_cmp(packetbuf_addr(PACKETBUF_ADDR_RECEIVER),
956  &linkaddr_null))) {
957  /* This is a regular packet that is destined to us or to the
958  broadcast address. */
959 
960  /* If FRAME_PENDING is set, we are receiving a packets in a burst */
961  we_are_receiving_burst = packetbuf_attr(PACKETBUF_ATTR_PENDING);
962  if(we_are_receiving_burst) {
963  on();
964  /* Set a timer to turn the radio off in case we do not receive
965  a next packet */
966  ctimer_set(&ct, INTER_PACKET_DEADLINE, recv_burst_off, NULL);
967  } else {
968  off();
969  ctimer_stop(&ct);
970  }
971 
972  /* Check for duplicate packet. */
974  /* Drop the packet. */
975  /* printf("Drop duplicate ContikiMAC layer packet\n");*/
976  return;
977  }
979 
980 #if CONTIKIMAC_CONF_COMPOWER
981  /* Accumulate the power consumption for the packet reception. */
982  compower_accumulate(&current_packet);
983  /* Convert the accumulated power consumption for the received
984  packet to packet attributes so that the higher levels can
985  keep track of the amount of energy spent on receiving the
986  packet. */
987  compower_attrconv(&current_packet);
988 
989  /* Clear the accumulated power consumption so that it is ready
990  for the next packet. */
991  compower_clear(&current_packet);
992 #endif /* CONTIKIMAC_CONF_COMPOWER */
993 
994  PRINTDEBUG("contikimac: data (%u)\n", packetbuf_datalen());
995  NETSTACK_MAC.input();
996  return;
997  } else {
998  PRINTDEBUG("contikimac: data not for us\n");
999  }
1000  } else {
1001  PRINTF("contikimac: failed to parse (%u)\n", packetbuf_totlen());
1002  }
1003 }
1004 /*---------------------------------------------------------------------------*/
1005 static void
1006 init(void)
1007 {
1008  radio_is_on = 0;
1009  PT_INIT(&pt);
1010 
1011  rtimer_set(&rt, RTIMER_NOW() + CYCLE_TIME, 1,
1012  (void (*)(struct rtimer *, void *))powercycle, NULL);
1013 
1014  contikimac_is_on = 1;
1015 
1016 #if WITH_PHASE_OPTIMIZATION
1017  phase_init();
1018 #endif /* WITH_PHASE_OPTIMIZATION */
1019 
1020 }
1021 /*---------------------------------------------------------------------------*/
1022 static int
1023 turn_on(void)
1024 {
1025  if(contikimac_is_on == 0) {
1026  contikimac_is_on = 1;
1027  contikimac_keep_radio_on = 0;
1028  rtimer_set(&rt, RTIMER_NOW() + CYCLE_TIME, 1,
1029  (void (*)(struct rtimer *, void *))powercycle, NULL);
1030  }
1031  return 1;
1032 }
1033 /*---------------------------------------------------------------------------*/
1034 static int
1035 turn_off(int keep_radio_on)
1036 {
1037  contikimac_is_on = 0;
1038  contikimac_keep_radio_on = keep_radio_on;
1039  if(keep_radio_on) {
1040  radio_is_on = 1;
1041  return NETSTACK_RADIO.on();
1042  } else {
1043  radio_is_on = 0;
1044  return NETSTACK_RADIO.off();
1045  }
1046 }
1047 /*---------------------------------------------------------------------------*/
1048 static unsigned short
1049 duty_cycle(void)
1050 {
1051  return (1ul * CLOCK_SECOND * CYCLE_TIME) / RTIMER_ARCH_SECOND;
1052 }
1053 /*---------------------------------------------------------------------------*/
1054 const struct rdc_driver contikimac_driver = {
1055  "ContikiMAC",
1056  init,
1057  qsend_packet,
1058  qsend_list,
1059  input_packet,
1060  turn_on,
1061  turn_off,
1062  duty_cycle,
1063 };
1064 /*---------------------------------------------------------------------------*/
1065 uint16_t
1066 contikimac_debug_print(void)
1067 {
1068  return 0;
1069 }
1070 /*---------------------------------------------------------------------------*/