Contiki-NG
tsch.c
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2015, SICS Swedish ICT.
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  * IEEE 802.15.4 TSCH MAC implementation.
36  * Does not use any RDC layer. Should be used with nordc.
37  * \author
38  * Simon Duquennoy <simonduq@sics.se>
39  * Beshr Al Nahas <beshr@sics.se>
40  *
41  */
42 
43 /**
44  * \addtogroup tsch
45  * @{
46 */
47 
48 #include "contiki.h"
49 #include "dev/radio.h"
50 #include "net/netstack.h"
51 #include "net/packetbuf.h"
52 #include "net/queuebuf.h"
53 #include "net/nbr-table.h"
54 #include "net/link-stats.h"
56 #include "net/mac/tsch/tsch.h"
57 #include "net/mac/mac-sequence.h"
58 #include "lib/random.h"
59 #include "net/routing/routing.h"
60 
61 #if TSCH_WITH_SIXTOP
63 #endif
64 
65 #if FRAME802154_VERSION < FRAME802154_IEEE802154_2015
66 #error TSCH: FRAME802154_VERSION must be at least FRAME802154_IEEE802154_2015
67 #endif
68 
69 /* Log configuration */
70 #include "sys/log.h"
71 #define LOG_MODULE "TSCH"
72 #define LOG_LEVEL LOG_LEVEL_MAC
73 
74 /* Use to collect link statistics even on Keep-Alive, even though they were
75  * not sent from an upper layer and don't have a valid packet_sent callback */
76 #ifndef TSCH_LINK_NEIGHBOR_CALLBACK
77 #if NETSTACK_CONF_WITH_IPV6
78 void uip_ds6_link_neighbor_callback(int status, int numtx);
79 #define TSCH_LINK_NEIGHBOR_CALLBACK(dest, status, num) uip_ds6_link_neighbor_callback(status, num)
80 #endif /* NETSTACK_CONF_WITH_IPV6 */
81 #endif /* TSCH_LINK_NEIGHBOR_CALLBACK */
82 
83 /* The address of the last node we received an EB from (other than our time source).
84  * Used for recovery */
85 static linkaddr_t last_eb_nbr_addr;
86 /* The join priority advertised by last_eb_nbr_addr */
87 static uint8_t last_eb_nbr_jp;
88 
89 /* Let TSCH select a time source with no help of an upper layer.
90  * We do so using statistics from incoming EBs */
91 #if TSCH_AUTOSELECT_TIME_SOURCE
92 int best_neighbor_eb_count;
93 struct eb_stat {
94  int rx_count;
95  int jp;
96 };
97 NBR_TABLE(struct eb_stat, eb_stats);
98 #endif /* TSCH_AUTOSELECT_TIME_SOURCE */
99 
100 /* TSCH channel hopping sequence */
101 uint8_t tsch_hopping_sequence[TSCH_HOPPING_SEQUENCE_MAX_LEN];
102 struct tsch_asn_divisor_t tsch_hopping_sequence_length;
103 
104 /* Default TSCH timeslot timing (in micro-second) */
105 static const uint16_t *tsch_default_timing_us;
106 /* TSCH timeslot timing (in micro-second) */
107 uint16_t tsch_timing_us[tsch_ts_elements_count];
108 /* TSCH timeslot timing (in rtimer ticks) */
109 rtimer_clock_t tsch_timing[tsch_ts_elements_count];
110 
111 #if LINKADDR_SIZE == 8
112 /* 802.15.4 broadcast MAC address */
113 const linkaddr_t tsch_broadcast_address = { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff } };
114 /* Address used for the EB virtual neighbor queue */
115 const linkaddr_t tsch_eb_address = { { 0, 0, 0, 0, 0, 0, 0, 0 } };
116 #else /* LINKADDR_SIZE == 8 */
117 const linkaddr_t tsch_broadcast_address = { { 0xff, 0xff } };
118 const linkaddr_t tsch_eb_address = { { 0, 0 } };
119 #endif /* LINKADDR_SIZE == 8 */
120 
121 /* Is TSCH started? */
122 int tsch_is_started = 0;
123 /* Has TSCH initialization failed? */
124 int tsch_is_initialized = 0;
125 /* Are we coordinator of the TSCH network? */
126 int tsch_is_coordinator = 0;
127 /* Are we associated to a TSCH network? */
128 int tsch_is_associated = 0;
129 /* Total number of associations since boot */
130 int tsch_association_count = 0;
131 /* Is the PAN running link-layer security? */
132 int tsch_is_pan_secured = LLSEC802154_ENABLED;
133 /* The current Absolute Slot Number (ASN) */
134 struct tsch_asn_t tsch_current_asn;
135 /* Device rank or join priority:
136  * For PAN coordinator: 0 -- lower is better */
137 uint8_t tsch_join_priority;
138 /* The current TSCH sequence number, used for unicast data frames only */
139 static uint8_t tsch_packet_seqno;
140 /* Current period for EB output */
141 static clock_time_t tsch_current_eb_period;
142 /* Current period for keepalive output */
143 static clock_time_t tsch_current_ka_timeout;
144 
145 /* timer for sending keepalive messages */
146 static struct ctimer keepalive_timer;
147 
148 /* Statistics on the current session */
149 unsigned long tx_count;
150 unsigned long rx_count;
151 unsigned long sync_count;
152 int32_t min_drift_seen;
153 int32_t max_drift_seen;
154 
155 /* TSCH processes and protothreads */
156 PT_THREAD(tsch_scan(struct pt *pt));
157 PROCESS(tsch_process, "main process");
158 PROCESS(tsch_send_eb_process, "send EB process");
159 PROCESS(tsch_pending_events_process, "pending events process");
160 
161 /* Other function prototypes */
162 static void packet_input(void);
163 
164 /* Getters and setters */
165 
166 /*---------------------------------------------------------------------------*/
167 void
169 {
170  if(tsch_is_coordinator != enable) {
171  tsch_is_associated = 0;
172  }
173  tsch_is_coordinator = enable;
174  tsch_set_eb_period(TSCH_EB_PERIOD);
175 }
176 /*---------------------------------------------------------------------------*/
177 void
179 {
180  tsch_is_pan_secured = LLSEC802154_ENABLED && enable;
181 }
182 /*---------------------------------------------------------------------------*/
183 void
185 {
186  tsch_join_priority = jp;
187 }
188 /*---------------------------------------------------------------------------*/
189 void
190 tsch_set_ka_timeout(uint32_t timeout)
191 {
192  tsch_current_ka_timeout = timeout;
193  if(timeout == 0) {
194  ctimer_stop(&keepalive_timer);
195  } else {
197  }
198 }
199 /*---------------------------------------------------------------------------*/
200 void
201 tsch_set_eb_period(uint32_t period)
202 {
203  tsch_current_eb_period = MIN(period, TSCH_MAX_EB_PERIOD);
204 }
205 /*---------------------------------------------------------------------------*/
206 static void
207 tsch_reset(void)
208 {
209  int i;
210  frame802154_set_pan_id(0xffff);
211  /* First make sure pending packet callbacks are sent etc */
212  process_post_synch(&tsch_pending_events_process, PROCESS_EVENT_POLL, NULL);
213  /* Reset neighbor queues */
215  /* Remove unused neighbors */
218  /* Initialize global variables */
219  tsch_join_priority = 0xff;
220  TSCH_ASN_INIT(tsch_current_asn, 0, 0);
221  current_link = NULL;
222  /* Reset timeslot timing to defaults */
223  tsch_default_timing_us = TSCH_DEFAULT_TIMESLOT_TIMING;
224  for(i = 0; i < tsch_ts_elements_count; i++) {
225  tsch_timing_us[i] = tsch_default_timing_us[i];
226  tsch_timing[i] = US_TO_RTIMERTICKS(tsch_timing_us[i]);
227  }
228 #ifdef TSCH_CALLBACK_LEAVING_NETWORK
229  TSCH_CALLBACK_LEAVING_NETWORK();
230 #endif
231  linkaddr_copy(&last_eb_nbr_addr, &linkaddr_null);
232 #if TSCH_AUTOSELECT_TIME_SOURCE
233  struct nbr_sync_stat *stat;
234  best_neighbor_eb_count = 0;
235  /* Remove all nbr stats */
236  stat = nbr_table_head(sync_stats);
237  while(stat != NULL) {
238  nbr_table_remove(sync_stats, stat);
239  stat = nbr_table_next(sync_stats, stat);
240  }
241 #endif /* TSCH_AUTOSELECT_TIME_SOURCE */
242  tsch_set_eb_period(TSCH_EB_PERIOD);
243 }
244 /* TSCH keep-alive functions */
245 
246 /*---------------------------------------------------------------------------*/
247 /* Resynchronize to last_eb_nbr.
248  * Return non-zero if this function schedules the next keepalive.
249  * Return zero otherwise.
250  */
251 static int
252 resynchronize(const linkaddr_t *original_time_source_addr)
253 {
254  const struct tsch_neighbor *current_time_source = tsch_queue_get_time_source();
255  if(current_time_source && !linkaddr_cmp(&current_time_source->addr, original_time_source_addr)) {
256  /* Time source has already been changed (e.g. by RPL). Let's see if it works. */
257  LOG_INFO("time source has been changed to ");
258  LOG_INFO_LLADDR(&current_time_source->addr);
259  LOG_INFO_("\n");
260  return 0;
261  }
262  /* Switch time source to the last neighbor we received an EB from */
263  if(linkaddr_cmp(&last_eb_nbr_addr, &linkaddr_null)) {
264  LOG_WARN("not able to re-synchronize, received no EB from other neighbors\n");
265  if(sync_count == 0) {
266  /* We got no synchronization at all in this session, leave the network */
268  }
269  return 0;
270  } else {
271  LOG_WARN("re-synchronizing on ");
272  LOG_WARN_LLADDR(&last_eb_nbr_addr);
273  LOG_WARN_("\n");
274  /* We simply pick the last neighbor we receiver sync information from */
275  tsch_queue_update_time_source(&last_eb_nbr_addr);
276  tsch_join_priority = last_eb_nbr_jp + 1;
277  /* Try to get in sync ASAP */
279  return 1;
280  }
281 }
282 
283 /*---------------------------------------------------------------------------*/
284 /* Tx callback for keepalive messages */
285 static void
286 keepalive_packet_sent(void *ptr, int status, int transmissions)
287 {
288  int schedule_next_keepalive = 1;
289  /* Update neighbor link statistics */
290  link_stats_packet_sent(packetbuf_addr(PACKETBUF_ADDR_RECEIVER), status, transmissions);
291  /* Call RPL callback if RPL is enabled */
292 #ifdef TSCH_CALLBACK_KA_SENT
293  TSCH_CALLBACK_KA_SENT(status, transmissions);
294 #endif /* TSCH_CALLBACK_KA_SENT */
295  LOG_INFO("KA sent to ");
296  LOG_INFO_LLADDR(packetbuf_addr(PACKETBUF_ADDR_RECEIVER));
297  LOG_INFO_(", st %d-%d\n", status, transmissions);
298 
299  /* We got no ack, try to resynchronize */
300  if(status == MAC_TX_NOACK) {
301  schedule_next_keepalive = !resynchronize(packetbuf_addr(PACKETBUF_ADDR_RECEIVER));
302  }
303 
304  if(schedule_next_keepalive) {
306  }
307 }
308 /*---------------------------------------------------------------------------*/
309 /* Prepare and send a keepalive message */
310 static void
311 keepalive_send(void *ptr)
312 {
313  if(tsch_is_associated) {
315  if(n != NULL) {
316  /* Simply send an empty packet */
317  packetbuf_clear();
318  packetbuf_set_addr(PACKETBUF_ADDR_RECEIVER, &n->addr);
319  NETSTACK_MAC.send(keepalive_packet_sent, NULL);
320  LOG_INFO("sending KA to ");
321  LOG_INFO_LLADDR(&n->addr);
322  LOG_INFO_("\n");
323  } else {
324  LOG_ERR("no timesource - KA not sent\n");
325  }
326  }
327 }
328 /*---------------------------------------------------------------------------*/
329 /* Set ctimer to send a keepalive message after expiration of TSCH_KEEPALIVE_TIMEOUT */
330 void
332 {
333  /* Pick a delay in the range [tsch_current_ka_timeout*0.9, tsch_current_ka_timeout[ */
334  if(!tsch_is_coordinator && tsch_is_associated && tsch_current_ka_timeout > 0) {
335  unsigned long delay = (tsch_current_ka_timeout - tsch_current_ka_timeout / 10)
336  + random_rand() % (tsch_current_ka_timeout / 10);
337  ctimer_set(&keepalive_timer, delay, keepalive_send, NULL);
338  }
339 }
340 /*---------------------------------------------------------------------------*/
341 /* Set ctimer to send a keepalive message immediately */
342 void
344 {
345  /* Pick a delay in the range [tsch_current_ka_timeout*0.9, tsch_current_ka_timeout[ */
346  if(!tsch_is_coordinator && tsch_is_associated) {
347  ctimer_set(&keepalive_timer, 0, keepalive_send, NULL);
348  }
349 }
350 /*---------------------------------------------------------------------------*/
351 static void
352 eb_input(struct input_packet *current_input)
353 {
354  /* LOG_INFO("EB received\n"); */
355  frame802154_t frame;
356  /* Verify incoming EB (does its ASN match our Rx time?),
357  * and update our join priority. */
358  struct ieee802154_ies eb_ies;
359 
360  if(tsch_packet_parse_eb(current_input->payload, current_input->len,
361  &frame, &eb_ies, NULL, 1)) {
362  /* PAN ID check and authentication done at rx time */
363 
364  /* Got an EB from a different neighbor than our time source, keep enough data
365  * to switch to it in case we lose the link to our time source */
367  if(ts == NULL || !linkaddr_cmp(&last_eb_nbr_addr, &ts->addr)) {
368  linkaddr_copy(&last_eb_nbr_addr, (linkaddr_t *)&frame.src_addr);
369  last_eb_nbr_jp = eb_ies.ie_join_priority;
370  }
371 
372 #if TSCH_AUTOSELECT_TIME_SOURCE
373  if(!tsch_is_coordinator) {
374  /* Maintain EB received counter for every neighbor */
375  struct eb_stat *stat = (struct eb_stat *)nbr_table_get_from_lladdr(eb_stats, (linkaddr_t *)&frame.src_addr);
376  if(stat == NULL) {
377  stat = (struct eb_stat *)nbr_table_add_lladdr(eb_stats, (linkaddr_t *)&frame.src_addr, NBR_TABLE_REASON_MAC, NULL);
378  }
379  if(stat != NULL) {
380  stat->rx_count++;
381  stat->jp = eb_ies.ie_join_priority;
382  best_neighbor_eb_count = MAX(best_neighbor_eb_count, stat->rx_count);
383  }
384  /* Select best time source */
385  struct eb_stat *best_stat = NULL;
386  stat = nbr_table_head(eb_stats);
387  while(stat != NULL) {
388  /* Is neighbor eligible as a time source? */
389  if(stat->rx_count > best_neighbor_eb_count / 2) {
390  if(best_stat == NULL ||
391  stat->jp < best_stat->jp) {
392  best_stat = stat;
393  }
394  }
395  stat = nbr_table_next(eb_stats, stat);
396  }
397  /* Update time source */
398  if(best_stat != NULL) {
399  tsch_queue_update_time_source(nbr_table_get_lladdr(eb_stats, best_stat));
400  tsch_join_priority = best_stat->jp + 1;
401  }
402  }
403 #endif /* TSCH_AUTOSELECT_TIME_SOURCE */
404 
405  /* Did the EB come from our time source? */
406  if(ts != NULL && linkaddr_cmp((linkaddr_t *)&frame.src_addr, &ts->addr)) {
407  /* Check for ASN drift */
408  int32_t asn_diff = TSCH_ASN_DIFF(current_input->rx_asn, eb_ies.ie_asn);
409  if(asn_diff != 0) {
410  /* We disagree with our time source's ASN -- leave the network */
411  LOG_WARN("! ASN drifted by %ld, leaving the network\n", asn_diff);
413  }
414 
415  if(eb_ies.ie_join_priority >= TSCH_MAX_JOIN_PRIORITY) {
416  /* Join priority unacceptable. Leave network. */
417  LOG_WARN("! EB JP too high %u, leaving the network\n",
418  eb_ies.ie_join_priority);
420  } else {
421 #if TSCH_AUTOSELECT_TIME_SOURCE
422  /* Update join priority */
423  if(tsch_join_priority != eb_ies.ie_join_priority + 1) {
424  LOG_INFO("update JP from EB %u -> %u\n",
425  tsch_join_priority, eb_ies.ie_join_priority + 1);
426  tsch_join_priority = eb_ies.ie_join_priority + 1;
427  }
428 #endif /* TSCH_AUTOSELECT_TIME_SOURCE */
429  }
430 
431  /* TSCH hopping sequence */
432  if(eb_ies.ie_channel_hopping_sequence_id != 0) {
433  if(eb_ies.ie_hopping_sequence_len != tsch_hopping_sequence_length.val
434  || memcmp((uint8_t *)tsch_hopping_sequence, eb_ies.ie_hopping_sequence_list, tsch_hopping_sequence_length.val)) {
435  if(eb_ies.ie_hopping_sequence_len <= sizeof(tsch_hopping_sequence)) {
436  memcpy((uint8_t *)tsch_hopping_sequence, eb_ies.ie_hopping_sequence_list,
437  eb_ies.ie_hopping_sequence_len);
438  TSCH_ASN_DIVISOR_INIT(tsch_hopping_sequence_length, eb_ies.ie_hopping_sequence_len);
439 
440  LOG_WARN("Updating TSCH hopping sequence from EB\n");
441  } else {
442  LOG_WARN("TSCH:! parse_eb: hopping sequence too long (%u)\n", eb_ies.ie_hopping_sequence_len);
443  }
444  }
445  }
446  }
447  }
448 }
449 /*---------------------------------------------------------------------------*/
450 /* Process pending input packet(s) */
451 static void
452 tsch_rx_process_pending()
453 {
454  int16_t input_index;
455  /* Loop on accessing (without removing) a pending input packet */
456  while((input_index = ringbufindex_peek_get(&input_ringbuf)) != -1) {
457  struct input_packet *current_input = &input_array[input_index];
458  frame802154_t frame;
459  uint8_t ret = frame802154_parse(current_input->payload, current_input->len, &frame);
460  int is_data = ret && frame.fcf.frame_type == FRAME802154_DATAFRAME;
461  int is_eb = ret
462  && frame.fcf.frame_version == FRAME802154_IEEE802154_2015
463  && frame.fcf.frame_type == FRAME802154_BEACONFRAME;
464 
465  if(is_data) {
466  /* Skip EBs and other control messages */
467  /* Copy to packetbuf for processing */
468  packetbuf_copyfrom(current_input->payload, current_input->len);
469  packetbuf_set_attr(PACKETBUF_ATTR_RSSI, current_input->rssi);
470  packetbuf_set_attr(PACKETBUF_ATTR_CHANNEL, current_input->channel);
471  }
472 
473  if(is_data) {
474  /* Pass to upper layers */
475  packet_input();
476  } else if(is_eb) {
477  eb_input(current_input);
478  }
479 
480  /* Remove input from ringbuf */
481  ringbufindex_get(&input_ringbuf);
482  }
483 }
484 /*---------------------------------------------------------------------------*/
485 /* Pass sent packets to upper layer */
486 static void
487 tsch_tx_process_pending(void)
488 {
489  int16_t dequeued_index;
490  /* Loop on accessing (without removing) a pending input packet */
491  while((dequeued_index = ringbufindex_peek_get(&dequeued_ringbuf)) != -1) {
492  struct tsch_packet *p = dequeued_array[dequeued_index];
493  /* Put packet into packetbuf for packet_sent callback */
494  queuebuf_to_packetbuf(p->qb);
495  LOG_INFO("packet sent to ");
496  LOG_INFO_LLADDR(packetbuf_addr(PACKETBUF_ADDR_RECEIVER));
497  LOG_INFO_(", seqno %u, status %d, tx %d\n",
498  packetbuf_attr(PACKETBUF_ATTR_MAC_SEQNO), p->ret, p->transmissions);
499  /* Call packet_sent callback */
500  mac_call_sent_callback(p->sent, p->ptr, p->ret, p->transmissions);
501  /* Free packet queuebuf */
503  /* Free all unused neighbors */
505  /* Remove dequeued packet from ringbuf */
506  ringbufindex_get(&dequeued_ringbuf);
507  }
508 }
509 /*---------------------------------------------------------------------------*/
510 /* Setup TSCH as a coordinator */
511 static void
512 tsch_start_coordinator(void)
513 {
514  frame802154_set_pan_id(IEEE802154_PANID);
515  /* Initialize hopping sequence as default */
516  memcpy(tsch_hopping_sequence, TSCH_DEFAULT_HOPPING_SEQUENCE, sizeof(TSCH_DEFAULT_HOPPING_SEQUENCE));
517  TSCH_ASN_DIVISOR_INIT(tsch_hopping_sequence_length, sizeof(TSCH_DEFAULT_HOPPING_SEQUENCE));
518 #if TSCH_SCHEDULE_WITH_6TISCH_MINIMAL
520 #endif
521 
522  tsch_is_associated = 1;
523  tsch_join_priority = 0;
524 
525  LOG_INFO("starting as coordinator, PAN ID %x, asn-%x.%lx\n",
526  frame802154_get_pan_id(), tsch_current_asn.ms1b, tsch_current_asn.ls4b);
527 
528  /* Start slot operation */
529  tsch_slot_operation_sync(RTIMER_NOW(), &tsch_current_asn);
530 }
531 /*---------------------------------------------------------------------------*/
532 /* Leave the TSCH network */
533 void
535 {
536  if(tsch_is_associated == 1) {
537  tsch_is_associated = 0;
538  process_poll(&tsch_process);
539  }
540 }
541 /*---------------------------------------------------------------------------*/
542 /* Attempt to associate to a network form an incoming EB */
543 static int
544 tsch_associate(const struct input_packet *input_eb, rtimer_clock_t timestamp)
545 {
546  frame802154_t frame;
547  struct ieee802154_ies ies;
548  uint8_t hdrlen;
549  int i;
550 
551  if(input_eb == NULL || tsch_packet_parse_eb(input_eb->payload, input_eb->len,
552  &frame, &ies, &hdrlen, 0) == 0) {
553  LOG_ERR("! failed to parse EB (len %u)\n", input_eb->len);
554  return 0;
555  }
556 
557  tsch_current_asn = ies.ie_asn;
558  tsch_join_priority = ies.ie_join_priority + 1;
559 
560 #if TSCH_JOIN_SECURED_ONLY
561  if(frame.fcf.security_enabled == 0) {
562  LOG_ERR("! parse_eb: EB is not secured\n");
563  return 0;
564  }
565 #endif /* TSCH_JOIN_SECURED_ONLY */
566 #if LLSEC802154_ENABLED
567  if(!tsch_security_parse_frame(input_eb->payload, hdrlen,
568  input_eb->len - hdrlen - tsch_security_mic_len(&frame),
569  &frame, (linkaddr_t*)&frame.src_addr, &tsch_current_asn)) {
570  LOG_ERR("! parse_eb: failed to authenticate\n");
571  return 0;
572  }
573 #endif /* LLSEC802154_ENABLED */
574 
575 #if !LLSEC802154_ENABLED
576  if(frame.fcf.security_enabled == 1) {
577  LOG_ERR("! parse_eb: we do not support security, but EB is secured\n");
578  return 0;
579  }
580 #endif /* !LLSEC802154_ENABLED */
581 
582 #if TSCH_JOIN_MY_PANID_ONLY
583  /* Check if the EB comes from the PAN ID we expect */
584  if(frame.src_pid != IEEE802154_PANID) {
585  LOG_ERR("! parse_eb: PAN ID %x != %x\n", frame.src_pid, IEEE802154_PANID);
586  return 0;
587  }
588 #endif /* TSCH_JOIN_MY_PANID_ONLY */
589 
590  /* There was no join priority (or 0xff) in the EB, do not join */
591  if(ies.ie_join_priority == 0xff) {
592  LOG_ERR("! parse_eb: no join priority\n");
593  return 0;
594  }
595 
596  /* TSCH timeslot timing */
597  for(i = 0; i < tsch_ts_elements_count; i++) {
598  if(ies.ie_tsch_timeslot_id == 0) {
599  tsch_timing_us[i] = tsch_default_timing_us[i];
600  } else {
601  tsch_timing_us[i] = ies.ie_tsch_timeslot[i];
602  }
603  tsch_timing[i] = US_TO_RTIMERTICKS(tsch_timing_us[i]);
604  }
605 
606  /* TSCH hopping sequence */
607  if(ies.ie_channel_hopping_sequence_id == 0) {
608  memcpy(tsch_hopping_sequence, TSCH_DEFAULT_HOPPING_SEQUENCE, sizeof(TSCH_DEFAULT_HOPPING_SEQUENCE));
609  TSCH_ASN_DIVISOR_INIT(tsch_hopping_sequence_length, sizeof(TSCH_DEFAULT_HOPPING_SEQUENCE));
610  } else {
611  if(ies.ie_hopping_sequence_len <= sizeof(tsch_hopping_sequence)) {
612  memcpy(tsch_hopping_sequence, ies.ie_hopping_sequence_list, ies.ie_hopping_sequence_len);
613  TSCH_ASN_DIVISOR_INIT(tsch_hopping_sequence_length, ies.ie_hopping_sequence_len);
614  } else {
615  LOG_ERR("! parse_eb: hopping sequence too long (%u)\n", ies.ie_hopping_sequence_len);
616  return 0;
617  }
618  }
619 
620 #if TSCH_CHECK_TIME_AT_ASSOCIATION > 0
621  /* Divide by 4k and multiply again to avoid integer overflow */
622  uint32_t expected_asn = 4096 * TSCH_CLOCK_TO_SLOTS(clock_time() / 4096, tsch_timing_timeslot_length); /* Expected ASN based on our current time*/
623  int32_t asn_threshold = TSCH_CHECK_TIME_AT_ASSOCIATION * 60ul * TSCH_CLOCK_TO_SLOTS(CLOCK_SECOND, tsch_timing_timeslot_length);
624  int32_t asn_diff = (int32_t)tsch_current_asn.ls4b - expected_asn;
625  if(asn_diff > asn_threshold) {
626  LOG_ERR("! EB ASN rejected %lx %lx %ld\n",
627  tsch_current_asn.ls4b, expected_asn, asn_diff);
628  return 0;
629  }
630 #endif
631 
632 #if TSCH_INIT_SCHEDULE_FROM_EB
633  /* Create schedule */
634  if(ies.ie_tsch_slotframe_and_link.num_slotframes == 0) {
635 #if TSCH_SCHEDULE_WITH_6TISCH_MINIMAL
636  LOG_INFO("parse_eb: no schedule, setting up minimal schedule\n");
638 #else
639  LOG_INFO("parse_eb: no schedule\n");
640 #endif
641  } else {
642  /* First, empty current schedule */
644  /* We support only 0 or 1 slotframe in this IE */
645  int num_links = ies.ie_tsch_slotframe_and_link.num_links;
646  if(num_links <= FRAME802154E_IE_MAX_LINKS) {
647  int i;
649  ies.ie_tsch_slotframe_and_link.slotframe_handle,
650  ies.ie_tsch_slotframe_and_link.slotframe_size);
651  for(i = 0; i < num_links; i++) {
653  ies.ie_tsch_slotframe_and_link.links[i].link_options,
654  LINK_TYPE_ADVERTISING, &tsch_broadcast_address,
655  ies.ie_tsch_slotframe_and_link.links[i].timeslot, ies.ie_tsch_slotframe_and_link.links[i].channel_offset);
656  }
657  } else {
658  LOG_ERR("! parse_eb: too many links in schedule (%u)\n", num_links);
659  return 0;
660  }
661  }
662 #endif /* TSCH_INIT_SCHEDULE_FROM_EB */
663 
664  if(tsch_join_priority < TSCH_MAX_JOIN_PRIORITY) {
665  struct tsch_neighbor *n;
666 
667  /* Add coordinator to list of neighbors, lock the entry */
668  n = tsch_queue_add_nbr((linkaddr_t *)&frame.src_addr);
669 
670  if(n != NULL) {
671  tsch_queue_update_time_source((linkaddr_t *)&frame.src_addr);
672 
673  /* Set PANID */
674  frame802154_set_pan_id(frame.src_pid);
675 
676  /* Synchronize on EB */
677  tsch_slot_operation_sync(timestamp - tsch_timing[tsch_ts_tx_offset], &tsch_current_asn);
678 
679  /* Update global flags */
680  tsch_is_associated = 1;
681  tsch_is_pan_secured = frame.fcf.security_enabled;
682  tx_count = 0;
683  rx_count = 0;
684  sync_count = 0;
685  min_drift_seen = 0;
686  max_drift_seen = 0;
687 
688  /* Start sending keep-alives now that tsch_is_associated is set */
690 
691 #ifdef TSCH_CALLBACK_JOINING_NETWORK
692  TSCH_CALLBACK_JOINING_NETWORK();
693 #endif
694 
695  tsch_association_count++;
696  LOG_INFO("association done (%u), sec %u, PAN ID %x, asn-%x.%lx, jp %u, timeslot id %u, hopping id %u, slotframe len %u with %u links, from ",
697  tsch_association_count,
698  tsch_is_pan_secured,
699  frame.src_pid,
700  tsch_current_asn.ms1b, tsch_current_asn.ls4b, tsch_join_priority,
701  ies.ie_tsch_timeslot_id,
702  ies.ie_channel_hopping_sequence_id,
703  ies.ie_tsch_slotframe_and_link.slotframe_size,
704  ies.ie_tsch_slotframe_and_link.num_links);
705  LOG_INFO_LLADDR((const linkaddr_t *)&frame.src_addr);
706  LOG_INFO_("\n");
707 
708  return 1;
709  }
710  }
711  LOG_ERR("! did not associate.\n");
712  return 0;
713 }
714 /* Processes and protothreads used by TSCH */
715 
716 /*---------------------------------------------------------------------------*/
717 /* Scanning protothread, called by tsch_process:
718  * Listen to different channels, and when receiving an EB,
719  * attempt to associate.
720  */
721 PT_THREAD(tsch_scan(struct pt *pt))
722 {
723  PT_BEGIN(pt);
724 
725  static struct input_packet input_eb;
726  static struct etimer scan_timer;
727  /* Time when we started scanning on current_channel */
728  static clock_time_t current_channel_since;
729 
730  TSCH_ASN_INIT(tsch_current_asn, 0, 0);
731 
732  etimer_set(&scan_timer, CLOCK_SECOND / TSCH_ASSOCIATION_POLL_FREQUENCY);
733  current_channel_since = clock_time();
734 
735  while(!tsch_is_associated && !tsch_is_coordinator) {
736  /* Hop to any channel offset */
737  static uint8_t current_channel = 0;
738 
739  /* We are not coordinator, try to associate */
740  rtimer_clock_t t0;
741  int is_packet_pending = 0;
742  clock_time_t now_time = clock_time();
743 
744  /* Switch to a (new) channel for scanning */
745  if(current_channel == 0 || now_time - current_channel_since > TSCH_CHANNEL_SCAN_DURATION) {
746  /* Pick a channel at random in TSCH_JOIN_HOPPING_SEQUENCE */
747  uint8_t scan_channel = TSCH_JOIN_HOPPING_SEQUENCE[
748  random_rand() % sizeof(TSCH_JOIN_HOPPING_SEQUENCE)];
749 
750  NETSTACK_RADIO.set_value(RADIO_PARAM_CHANNEL, scan_channel);
751  current_channel = scan_channel;
752  LOG_INFO("scanning on channel %u\n", scan_channel);
753 
754  current_channel_since = now_time;
755  }
756 
757  /* Turn radio on and wait for EB */
758  NETSTACK_RADIO.on();
759 
760  is_packet_pending = NETSTACK_RADIO.pending_packet();
761  if(!is_packet_pending && NETSTACK_RADIO.receiving_packet()) {
762  /* If we are currently receiving a packet, wait until end of reception */
763  t0 = RTIMER_NOW();
764  RTIMER_BUSYWAIT_UNTIL_ABS((is_packet_pending = NETSTACK_RADIO.pending_packet()), t0, RTIMER_SECOND / 100);
765  }
766 
767  if(is_packet_pending) {
768  rtimer_clock_t t1;
769  /* Read packet */
770  input_eb.len = NETSTACK_RADIO.read(input_eb.payload, TSCH_PACKET_MAX_LEN);
771 
772  /* Save packet timestamp */
773  NETSTACK_RADIO.get_object(RADIO_PARAM_LAST_PACKET_TIMESTAMP, &t0, sizeof(rtimer_clock_t));
774  t1 = RTIMER_NOW();
775 
776  /* Parse EB and attempt to associate */
777  LOG_INFO("scan: received packet (%u bytes) on channel %u\n", input_eb.len, current_channel);
778 
779  /* Sanity-check the timestamp */
780  if(ABS(RTIMER_CLOCK_DIFF(t0, t1)) < tsch_timing[tsch_ts_timeslot_length]) {
781  tsch_associate(&input_eb, t0);
782  } else {
783  LOG_WARN("scan: dropping packet, timestamp too far from current time %u %u\n",
784  (unsigned)t0,
785  (unsigned)t1
786  );
787  }
788  }
789 
790  if(tsch_is_associated) {
791  /* End of association, turn the radio off */
792  NETSTACK_RADIO.off();
793  } else if(!tsch_is_coordinator) {
794  /* Go back to scanning */
795  etimer_reset(&scan_timer);
796  PT_WAIT_UNTIL(pt, etimer_expired(&scan_timer));
797  }
798  }
799 
800  PT_END(pt);
801 }
802 
803 /*---------------------------------------------------------------------------*/
804 /* The main TSCH process */
805 PROCESS_THREAD(tsch_process, ev, data)
806 {
807  static struct pt scan_pt;
808 
809  PROCESS_BEGIN();
810 
811  while(1) {
812 
813  while(!tsch_is_associated) {
814  if(tsch_is_coordinator) {
815  /* We are coordinator, start operating now */
816  tsch_start_coordinator();
817  } else {
818  /* Start scanning, will attempt to join when receiving an EB */
819  PROCESS_PT_SPAWN(&scan_pt, tsch_scan(&scan_pt));
820  }
821  }
822 
823  /* We are part of a TSCH network, start slot operation */
825 
826  /* Yield our main process. Slot operation will re-schedule itself
827  * as long as we are associated */
828  PROCESS_YIELD_UNTIL(!tsch_is_associated);
829 
830  LOG_WARN("leaving the network, stats: tx %lu, rx %lu, sync %lu\n",
831  tx_count, rx_count, sync_count);
832 
833  /* Will need to re-synchronize */
834  tsch_reset();
835  }
836 
837  PROCESS_END();
838 }
839 
840 /*---------------------------------------------------------------------------*/
841 /* A periodic process to send TSCH Enhanced Beacons (EB) */
842 PROCESS_THREAD(tsch_send_eb_process, ev, data)
843 {
844  static struct etimer eb_timer;
845 
846  PROCESS_BEGIN();
847 
848  /* Wait until association */
849  etimer_set(&eb_timer, CLOCK_SECOND / 10);
850  while(!tsch_is_associated) {
852  etimer_reset(&eb_timer);
853  }
854 
855  /* Set an initial delay except for coordinator, which should send an EB asap */
856  if(!tsch_is_coordinator) {
857  etimer_set(&eb_timer, random_rand() % TSCH_EB_PERIOD);
859  }
860 
861  while(1) {
862  unsigned long delay;
863 
864  if(tsch_is_associated && tsch_current_eb_period > 0
865 #ifdef TSCH_RPL_CHECK_DODAG_JOINED
866  /* Implementation section 6.3 of RFC 8180 */
867  && TSCH_RPL_CHECK_DODAG_JOINED()
868 #endif /* TSCH_RPL_CHECK_DODAG_JOINED */
869  ) {
870  /* Enqueue EB only if there isn't already one in queue */
871  if(tsch_queue_packet_count(&tsch_eb_address) == 0) {
872  uint8_t hdr_len = 0;
873  uint8_t tsch_sync_ie_offset;
874  /* Prepare the EB packet and schedule it to be sent */
875  if(tsch_packet_create_eb(&hdr_len, &tsch_sync_ie_offset) > 0) {
876  struct tsch_packet *p;
877  /* Enqueue EB packet, for a single transmission only */
878  if(!(p = tsch_queue_add_packet(&tsch_eb_address, 1, NULL, NULL))) {
879  LOG_ERR("! could not enqueue EB packet\n");
880  } else {
881  LOG_INFO("TSCH: enqueue EB packet %u %u\n",
883  p->tsch_sync_ie_offset = tsch_sync_ie_offset;
884  p->header_len = hdr_len;
885  }
886  }
887  }
888  }
889  if(tsch_current_eb_period > 0) {
890  /* Next EB transmission with a random delay
891  * within [tsch_current_eb_period*0.75, tsch_current_eb_period[ */
892  delay = (tsch_current_eb_period - tsch_current_eb_period / 4)
893  + random_rand() % (tsch_current_eb_period / 4);
894  } else {
895  delay = TSCH_EB_PERIOD;
896  }
897  etimer_set(&eb_timer, delay);
899  }
900  PROCESS_END();
901 }
902 
903 /*---------------------------------------------------------------------------*/
904 /* A process that is polled from interrupt and calls tx/rx input
905  * callbacks, outputs pending logs. */
906 PROCESS_THREAD(tsch_pending_events_process, ev, data)
907 {
908  PROCESS_BEGIN();
909  while(1) {
910  PROCESS_YIELD_UNTIL(ev == PROCESS_EVENT_POLL);
911  tsch_rx_process_pending();
912  tsch_tx_process_pending();
914 #ifdef TSCH_CALLBACK_SELECT_CHANNELS
915  TSCH_CALLBACK_SELECT_CHANNELS();
916 #endif
917  }
918  PROCESS_END();
919 }
920 
921 /* Functions from the Contiki MAC layer driver interface */
922 
923 /*---------------------------------------------------------------------------*/
924 static void
925 tsch_init(void)
926 {
927  radio_value_t radio_rx_mode;
928  radio_value_t radio_tx_mode;
929  rtimer_clock_t t;
930 
931  /* Check that the platform provides a TSCH timeslot timing template */
932  if(TSCH_DEFAULT_TIMESLOT_TIMING == NULL) {
933  LOG_ERR("! platform does not provide a timeslot timing template.\n");
934  return;
935  }
936 
937  /* Radio Rx mode */
938  if(NETSTACK_RADIO.get_value(RADIO_PARAM_RX_MODE, &radio_rx_mode) != RADIO_RESULT_OK) {
939  LOG_ERR("! radio does not support getting RADIO_PARAM_RX_MODE. Abort init.\n");
940  return;
941  }
942  /* Disable radio in frame filtering */
943  radio_rx_mode &= ~RADIO_RX_MODE_ADDRESS_FILTER;
944  /* Unset autoack */
945  radio_rx_mode &= ~RADIO_RX_MODE_AUTOACK;
946  /* Set radio in poll mode */
947  radio_rx_mode |= RADIO_RX_MODE_POLL_MODE;
948  if(NETSTACK_RADIO.set_value(RADIO_PARAM_RX_MODE, radio_rx_mode) != RADIO_RESULT_OK) {
949  LOG_ERR("! radio does not support setting required RADIO_PARAM_RX_MODE. Abort init.\n");
950  return;
951  }
952 
953  /* Radio Tx mode */
954  if(NETSTACK_RADIO.get_value(RADIO_PARAM_TX_MODE, &radio_tx_mode) != RADIO_RESULT_OK) {
955  LOG_ERR("! radio does not support getting RADIO_PARAM_TX_MODE. Abort init.\n");
956  return;
957  }
958  /* Unset CCA */
959  radio_tx_mode &= ~RADIO_TX_MODE_SEND_ON_CCA;
960  if(NETSTACK_RADIO.set_value(RADIO_PARAM_TX_MODE, radio_tx_mode) != RADIO_RESULT_OK) {
961  LOG_ERR("! radio does not support setting required RADIO_PARAM_TX_MODE. Abort init.\n");
962  return;
963  }
964  /* Test setting channel */
965  if(NETSTACK_RADIO.set_value(RADIO_PARAM_CHANNEL, TSCH_DEFAULT_HOPPING_SEQUENCE[0]) != RADIO_RESULT_OK) {
966  LOG_ERR("! radio does not support setting channel. Abort init.\n");
967  return;
968  }
969  /* Test getting timestamp */
970  if(NETSTACK_RADIO.get_object(RADIO_PARAM_LAST_PACKET_TIMESTAMP, &t, sizeof(rtimer_clock_t)) != RADIO_RESULT_OK) {
971  LOG_ERR("! radio does not support getting last packet timestamp. Abort init.\n");
972  return;
973  }
974  /* Check max hopping sequence length vs default sequence length */
975  if(TSCH_HOPPING_SEQUENCE_MAX_LEN < sizeof(TSCH_DEFAULT_HOPPING_SEQUENCE)) {
976  LOG_ERR("! TSCH_HOPPING_SEQUENCE_MAX_LEN < sizeof(TSCH_DEFAULT_HOPPING_SEQUENCE). Abort init.\n");
977  return;
978  }
979 
980  /* Init TSCH sub-modules */
981  tsch_reset();
982  tsch_queue_init();
984  tsch_log_init();
985  ringbufindex_init(&input_ringbuf, TSCH_MAX_INCOMING_PACKETS);
986  ringbufindex_init(&dequeued_ringbuf, TSCH_DEQUEUED_ARRAY_SIZE);
987 #if TSCH_AUTOSELECT_TIME_SOURCE
988  nbr_table_register(sync_stats, NULL);
989 #endif /* TSCH_AUTOSELECT_TIME_SOURCE */
990 
991  tsch_packet_seqno = random_rand();
992  tsch_is_initialized = 1;
993 
994 #if TSCH_AUTOSTART
995  /* Start TSCH operation.
996  * If TSCH_AUTOSTART is not set, one needs to call NETSTACK_MAC.on() to start TSCH. */
997  NETSTACK_MAC.on();
998 #endif /* TSCH_AUTOSTART */
999 
1000 #if TSCH_WITH_SIXTOP
1001  sixtop_init();
1002 #endif
1003 
1004  tsch_stats_init();
1005 }
1006 /*---------------------------------------------------------------------------*/
1007 /* Function send for TSCH-MAC, puts the packet in packetbuf in the MAC queue */
1008 static void
1009 send_packet(mac_callback_t sent, void *ptr)
1010 {
1011  int ret = MAC_TX_DEFERRED;
1012  int hdr_len = 0;
1013  const linkaddr_t *addr = packetbuf_addr(PACKETBUF_ADDR_RECEIVER);
1014  uint8_t max_transmissions = 0;
1015 
1016  if(!tsch_is_associated) {
1017  if(!tsch_is_initialized) {
1018  LOG_WARN("! not initialized (see earlier logs), drop outgoing packet\n");
1019  } else {
1020  LOG_WARN("! not associated, drop outgoing packet\n");
1021  }
1022  ret = MAC_TX_ERR;
1023  mac_call_sent_callback(sent, ptr, ret, 1);
1024  return;
1025  }
1026 
1027  /* Ask for ACK if we are sending anything other than broadcast */
1028  if(!linkaddr_cmp(addr, &linkaddr_null)) {
1029  /* PACKETBUF_ATTR_MAC_SEQNO cannot be zero, due to a pecuilarity
1030  in framer-802154.c. */
1031  if(++tsch_packet_seqno == 0) {
1032  tsch_packet_seqno++;
1033  }
1034  packetbuf_set_attr(PACKETBUF_ATTR_MAC_SEQNO, tsch_packet_seqno);
1035  packetbuf_set_attr(PACKETBUF_ATTR_MAC_ACK, 1);
1036  } else {
1037  /* Broadcast packets shall be added to broadcast queue
1038  * The broadcast address in Contiki is linkaddr_null which is equal
1039  * to tsch_eb_address */
1040  addr = &tsch_broadcast_address;
1041  }
1042 
1043  packetbuf_set_attr(PACKETBUF_ATTR_FRAME_TYPE, FRAME802154_DATAFRAME);
1044 
1045 #if LLSEC802154_ENABLED
1046  if(tsch_is_pan_secured) {
1047  /* Set security level, key id and index */
1048  packetbuf_set_attr(PACKETBUF_ATTR_SECURITY_LEVEL, TSCH_SECURITY_KEY_SEC_LEVEL_OTHER);
1049  packetbuf_set_attr(PACKETBUF_ATTR_KEY_ID_MODE, FRAME802154_1_BYTE_KEY_ID_MODE); /* Use 1-byte key index */
1050  packetbuf_set_attr(PACKETBUF_ATTR_KEY_INDEX, TSCH_SECURITY_KEY_INDEX_OTHER);
1051  }
1052 #endif /* LLSEC802154_ENABLED */
1053 
1054 #if !NETSTACK_CONF_BRIDGE_MODE
1055  /*
1056  * In the Contiki stack, the source address of a frame is set at the RDC
1057  * layer. Since TSCH doesn't use any RDC protocol and bypasses the layer to
1058  * transmit a frame, it should set the source address by itself.
1059  */
1060  packetbuf_set_addr(PACKETBUF_ADDR_SENDER, &linkaddr_node_addr);
1061 #endif
1062 
1063  max_transmissions = packetbuf_attr(PACKETBUF_ATTR_MAX_MAC_TRANSMISSIONS);
1064  if(max_transmissions == 0) {
1065  /* If not set by the application, use the default TSCH value */
1066  max_transmissions = TSCH_MAC_MAX_FRAME_RETRIES + 1;
1067  }
1068 
1069  if((hdr_len = NETSTACK_FRAMER.create()) < 0) {
1070  LOG_ERR("! can't send packet due to framer error\n");
1071  ret = MAC_TX_ERR;
1072  } else {
1073  struct tsch_packet *p;
1074  /* Enqueue packet */
1075  p = tsch_queue_add_packet(addr, max_transmissions, sent, ptr);
1076  if(p == NULL) {
1077  LOG_ERR("! can't send packet to ");
1078  LOG_ERR_LLADDR(addr);
1079  LOG_ERR_(" with seqno %u, queue %u %u\n",
1080  tsch_packet_seqno, tsch_queue_packet_count(addr), tsch_queue_global_packet_count());
1081  ret = MAC_TX_ERR;
1082  } else {
1083  p->header_len = hdr_len;
1084  LOG_INFO("send packet to ");
1085  LOG_INFO_LLADDR(addr);
1086  LOG_INFO_(" with seqno %u, queue %u %u, len %u %u\n",
1087  tsch_packet_seqno,
1089  p->header_len, queuebuf_datalen(p->qb));
1090  }
1091  }
1092  if(ret != MAC_TX_DEFERRED) {
1093  mac_call_sent_callback(sent, ptr, ret, 1);
1094  }
1095 }
1096 /*---------------------------------------------------------------------------*/
1097 static void
1098 packet_input(void)
1099 {
1100  int frame_parsed = 1;
1101 
1102  frame_parsed = NETSTACK_FRAMER.parse();
1103 
1104  if(frame_parsed < 0) {
1105  LOG_ERR("! failed to parse %u\n", packetbuf_datalen());
1106  } else {
1107  int duplicate = 0;
1108 
1109  /* Seqno of 0xffff means no seqno */
1110  if(packetbuf_attr(PACKETBUF_ATTR_MAC_SEQNO) != 0xffff) {
1111  /* Check for duplicates */
1112  duplicate = mac_sequence_is_duplicate();
1113  if(duplicate) {
1114  /* Drop the packet. */
1115  LOG_WARN("! drop dup ll from ");
1116  LOG_WARN_LLADDR(packetbuf_addr(PACKETBUF_ADDR_SENDER));
1117  LOG_WARN_(" seqno %u\n", packetbuf_attr(PACKETBUF_ATTR_MAC_SEQNO));
1118  } else {
1120  }
1121  }
1122 
1123  if(!duplicate) {
1124  LOG_INFO("received from ");
1125  LOG_INFO_LLADDR(packetbuf_addr(PACKETBUF_ADDR_SENDER));
1126  LOG_INFO_(" with seqno %u\n", packetbuf_attr(PACKETBUF_ATTR_MAC_SEQNO));
1127 #if TSCH_WITH_SIXTOP
1128  sixtop_input();
1129 #endif /* TSCH_WITH_SIXTOP */
1130  NETSTACK_NETWORK.input();
1131  }
1132  }
1133 }
1134 /*---------------------------------------------------------------------------*/
1135 static int
1136 turn_on(void)
1137 {
1138  if(tsch_is_initialized == 1 && tsch_is_started == 0) {
1139  tsch_is_started = 1;
1140  /* Process tx/rx callback and log messages whenever polled */
1141  process_start(&tsch_pending_events_process, NULL);
1142  /* periodically send TSCH EBs */
1143  process_start(&tsch_send_eb_process, NULL);
1144  /* try to associate to a network or start one if setup as coordinator */
1145  process_start(&tsch_process, NULL);
1146  LOG_INFO("starting as %s\n", tsch_is_coordinator ? "coordinator": "node");
1147  return 1;
1148  }
1149  return 0;
1150 }
1151 /*---------------------------------------------------------------------------*/
1152 static int
1153 turn_off(void)
1154 {
1155  NETSTACK_RADIO.off();
1156  return 1;
1157 }
1158 /*---------------------------------------------------------------------------*/
1159 static int
1160 max_payload(void)
1161 {
1162  /* Setup security... before. */
1163  return TSCH_PACKET_MAX_LEN - NETSTACK_FRAMER.length();
1164 }
1165 /*---------------------------------------------------------------------------*/
1166 const struct mac_driver tschmac_driver = {
1167  "TSCH",
1168  tsch_init,
1169  send_packet,
1170  packet_input,
1171  turn_on,
1172  turn_off,
1173  max_payload,
1174 };
1175 /*---------------------------------------------------------------------------*/
1176 /** @} */
uint16_t src_pid
Source PAN ID.
Definition: frame802154.h:207
TSCH packet information.
Definition: tsch-types.h:97
#define TSCH_ASN_DIVISOR_INIT(div, val_)
Initialize a struct asn_divisor_t.
Definition: tsch-asn.h:86
int tsch_queue_global_packet_count(void)
Returns the number of packets currently in all TSCH queues.
Definition: tsch-queue.c:273
void process_post_synch(struct process *p, process_event_t ev, process_data_t data)
Post a synchronous event to a process.
Definition: process.c:362
#define PROCESS(name, strname)
Declare a process.
Definition: process.h:307
void ctimer_stop(struct ctimer *c)
Stop a pending callback timer.
Definition: ctimer.c:149
void ringbufindex_init(struct ringbufindex *r, uint8_t size)
Initialize a ring buffer.
Definition: ringbufindex.c:50
void tsch_log_process_pending(void)
Process pending log messages.
int tsch_packet_create_eb(uint8_t *hdr_len, uint8_t *tsch_sync_ie_offset)
Create an EB packet directly in packetbuf.
Definition: tsch-packet.c:227
int(* on)(void)
Turn the MAC layer on.
Definition: mac.h:75
frame802154_fcf_t fcf
Frame control field.
Definition: frame802154.h:204
The MAC layer transmission could not be performed because of a fatal error.
Definition: mac.h:101
void packetbuf_clear(void)
Clear and reset the packetbuf.
Definition: packetbuf.c:75
static uip_ds6_addr_t * addr
Pointer to a nbr cache entry.
Definition: uip-nd6.c:107
int ringbufindex_peek_get(const struct ringbufindex *r)
Return the index of the first element which will be removed if calling ringbufindex_get.
Definition: ringbufindex.c:115
int tsch_schedule_init(void)
Module initialization, call only once at init.
The structure of a MAC protocol driver in Contiki.
Definition: mac.h:62
void tsch_set_join_priority(uint8_t jp)
Set the TSCH join priority (JP)
Definition: tsch.c:184
#define PROCESS_YIELD_UNTIL(c)
Yield the currently running process until a condition occurs.
Definition: process.h:178
Header file for the radio API
#define PROCESS_BEGIN()
Define the beginning of a process.
Definition: process.h:120
uint8_t security_enabled
1 bit.
Definition: frame802154.h:154
void tsch_log_init(void)
Initialize log module.
#define PROCESS_END()
Define the end of a process.
Definition: process.h:131
static void send_packet(linkaddr_t *dest)
This function is called by the 6lowpan code to send out a packet.
Definition: sicslowpan.c:1453
int frame802154_parse(uint8_t *data, int len, frame802154_t *pf)
Parses an input frame.
Definition: frame802154.c:500
int mac_sequence_is_duplicate(void)
Tell whether the packetbuf is a duplicate packet.
Definition: mac-sequence.c:72
TSCH neighbor information.
Definition: tsch-types.h:109
802.15.4e slotframe (contains links)
Definition: tsch-types.h:84
void tsch_queue_init(void)
Initialize TSCH queue module.
Definition: tsch-queue.c:521
#define PT_BEGIN(pt)
Declare the start of a protothread inside the C function implementing the protothread.
Definition: pt.h:114
unsigned int tsch_security_parse_frame(const uint8_t *hdr, int hdrlen, int datalen, const frame802154_t *frame, const linkaddr_t *sender, struct tsch_asn_t *asn)
Parse and check a frame protected with encryption and/or MIC.
struct tsch_neighbor * tsch_queue_get_time_source(void)
Get the TSCH time source (we currently assume there is only one)
Definition: tsch-queue.c:124
#define PT_WAIT_UNTIL(pt, condition)
Block and wait until condition is true.
Definition: pt.h:147
void tsch_set_ka_timeout(uint32_t timeout)
Set the desynchronization timeout after which a node sends a unicasst keep-alive (KA) to its time sou...
Definition: tsch.c:190
void tsch_schedule_keepalive_immediately(void)
Schedule a keep-alive immediately.
Definition: tsch.c:343
uint8_t packetbuf_hdrlen(void)
Get the length of the header in the packetbuf.
Definition: packetbuf.c:161
struct tsch_slotframe * tsch_schedule_add_slotframe(uint16_t handle, uint16_t size)
Creates and adds a new slotframe.
Definition: tsch-schedule.c:72
int radio_value_t
Each radio has a set of parameters that designate the current configuration and state of the radio...
Definition: radio.h:88
uint8_t src_addr[8]
Source address.
Definition: frame802154.h:203
void tsch_schedule_keepalive(void)
Schedule a keep-alive transmission within [timeout*0.9, timeout[.
Definition: tsch.c:331
A MAC framer for IEEE 802.15.4
const linkaddr_t linkaddr_null
The null link-layer address.
Header file for MAC sequence numbers management
void tsch_queue_free_unused_neighbors(void)
Deallocate all neighbors with empty queue.
Definition: tsch-queue.c:383
uint16_t packetbuf_datalen(void)
Get the length of the data in the packetbuf.
Definition: packetbuf.c:155
linkaddr_t linkaddr_node_addr
The link-layer address of the node.
Definition: linkaddr.c:48
void sixtop_init(void)
Initialize 6top module This initialization function removes all the SFs which has been installed into...
Definition: sixtop.c:260
#define RTIMER_NOW()
Get the current clock time.
Definition: rtimer.h:160
void sixtop_input(void)
Input a packet stored in packetbuf.
Definition: sixtop.c:203
unsigned int tsch_security_mic_len(const frame802154_t *frame)
Return MIC length.
#define CLOCK_SECOND
A second, measured in system clock time.
Definition: clock.h:82
For quick modulo operation on ASN.
Definition: tsch-asn.h:54
#define PT_END(pt)
Declare the end of a protothread.
Definition: pt.h:126
struct tsch_neighbor * tsch_queue_add_nbr(const linkaddr_t *addr)
Add a TSCH neighbor queue.
Definition: tsch-queue.c:80
Header file for the Packet queue buffer management
void tsch_set_eb_period(uint32_t period)
Set the period at wich TSCH enhanced beacons (EBs) are sent.
Definition: tsch.c:201
uint8_t frame_version
2 bit.
Definition: frame802154.h:162
void process_poll(struct process *p)
Request a process to be polled.
Definition: process.c:371
uint16_t packetbuf_totlen(void)
Get the total length of the header and data in the packetbuf.
Definition: packetbuf.c:167
int tsch_queue_update_time_source(const linkaddr_t *new_addr)
Update TSCH time source.
Definition: tsch-queue.c:140
The MAC layer transmission could not be performed because of an error.
Definition: mac.h:97
void ctimer_set(struct ctimer *c, clock_time_t t, void(*f)(void *), void *ptr)
Set a callback timer.
Definition: ctimer.c:99
Routing driver header file
Main API declarations for TSCH.
int packetbuf_copyfrom(const void *from, uint16_t len)
Copy from external data into the packetbuf.
Definition: packetbuf.c:84
clock_time_t clock_time(void)
Get the current clock time.
Definition: clock.c:118
#define RTIMER_BUSYWAIT_UNTIL_ABS(cond, t0, max_time)
Busy-wait until a condition.
Definition: rtimer.h:193
int etimer_expired(struct etimer *et)
Check if an event timer has expired.
Definition: etimer.c:213
struct tsch_link * tsch_schedule_add_link(struct tsch_slotframe *slotframe, uint8_t link_options, enum link_type link_type, const linkaddr_t *address, uint16_t timeslot, uint16_t channel_offset)
Adds a link to a slotframe.
#define TSCH_ASN_INIT(asn, ms1b_, ls4b_)
Initialize ASN.
Definition: tsch-asn.h:62
#define RADIO_RX_MODE_ADDRESS_FILTER
The radio reception mode controls address filtering and automatic transmission of acknowledgements in...
Definition: radio.h:231
uint8_t frame_type
3 bit.
Definition: frame802154.h:153
void tsch_slot_operation_sync(rtimer_clock_t next_slot_start, struct tsch_asn_t *next_slot_asn)
Set global time before starting slot operation, with a rtimer time and an ASN.
The MAC layer deferred the transmission for a later time.
Definition: mac.h:94
Parameters used by the frame802154_create() function.
Definition: frame802154.h:198
void linkaddr_copy(linkaddr_t *dest, const linkaddr_t *src)
Copy a link-layer address.
Definition: linkaddr.c:63
#define PT_THREAD(name_args)
Declaration of a protothread.
Definition: pt.h:99
A timer.
Definition: etimer.h:76
6TiSCH Operation Sublayer (6top) APIs
#define RADIO_TX_MODE_SEND_ON_CCA
The radio transmission mode controls whether transmissions should be done using clear channel assessm...
Definition: radio.h:243
#define TSCH_ASN_DIFF(asn1, asn2)
Returns the 32-bit diff between asn1 and asn2.
Definition: tsch-asn.h:82
int linkaddr_cmp(const linkaddr_t *addr1, const linkaddr_t *addr2)
Compare two link-layer addresses.
Definition: linkaddr.c:69
void tsch_queue_reset(void)
Reset neighbor queues module.
Definition: tsch-queue.c:365
void(* send)(mac_callback_t sent_callback, void *ptr)
Send a packet from the packetbuf.
Definition: mac.h:69
int tsch_schedule_remove_all_slotframes(void)
Removes all slotframes, resulting in an empty schedule.
int tsch_queue_packet_count(const linkaddr_t *addr)
Returns the number of packets currently a given neighbor queue.
Definition: tsch-queue.c:280
int ringbufindex_get(struct ringbufindex *r)
Remove the first element and return its index.
Definition: ringbufindex.c:90
void tsch_disassociate(void)
Leave the TSCH network we are currently in.
Definition: tsch.c:534
void tsch_set_pan_secured(int enable)
Enable/disable security.
Definition: tsch.c:178
Header file for the Packet buffer (packetbuf) management
Include file for the Contiki low-layer network stack (NETSTACK)
void mac_sequence_register_seqno(void)
Register the sequence number of the packetbuf.
Definition: mac-sequence.c:101
#define PROCESS_PT_SPAWN(pt, thread)
Spawn a protothread from the process.
Definition: process.h:211
int(* max_payload)(void)
Read out estimated max payload size based on payload in packetbuf.
Definition: mac.h:81
void tsch_queue_free_packet(struct tsch_packet *p)
Free a packet.
Definition: tsch-queue.c:312
PROCESS_THREAD(cc2538_rf_process, ev, data)
Implementation of the cc2538 RF driver process.
Definition: cc2538-rf.c:1097
unsigned short random_rand(void)
Generates a new random number using the cc2538 RNG.
Definition: random.c:58
struct tsch_packet * tsch_queue_add_packet(const linkaddr_t *addr, uint8_t max_transmissions, mac_callback_t sent, void *ptr)
Add packet to neighbor queue.
Definition: tsch-queue.c:230
Stores data about an incoming packet.
Definition: tsch-types.h:152
void etimer_reset(struct etimer *et)
Reset an event timer with the same interval as was previously set.
Definition: etimer.c:192
Header file for the logging system
void tsch_slot_operation_start(void)
Start actual slot operation.
int tsch_packet_parse_eb(const uint8_t *buf, int buf_size, frame802154_t *frame, struct ieee802154_ies *ies, uint8_t *hdr_len, int frame_without_mic)
Parse EB.
Definition: tsch-packet.c:401
void etimer_set(struct etimer *et, clock_time_t interval)
Set an event timer.
Definition: etimer.c:177
The ASN is an absolute slot number over 5 bytes.
Definition: tsch-asn.h:48
void tsch_schedule_create_minimal(void)
Create a 6tisch minimal schedule with length TSCH_SCHEDULE_DEFAULT_LENGTH.
#define PROCESS_WAIT_UNTIL(c)
Wait for a condition to occur.
Definition: process.h:192
void tsch_set_coordinator(int enable)
Set the node as PAN coordinator.
Definition: tsch.c:168
void process_start(struct process *p, process_data_t data)
Start a process.
Definition: process.c:99