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 /* The address of the last node we received an EB from (other than our time source).
75  * Used for recovery */
76 static linkaddr_t last_eb_nbr_addr;
77 /* The join priority advertised by last_eb_nbr_addr */
78 static uint8_t last_eb_nbr_jp;
79 
80 /* Let TSCH select a time source with no help of an upper layer.
81  * We do so using statistics from incoming EBs */
82 #if TSCH_AUTOSELECT_TIME_SOURCE
83 int best_neighbor_eb_count;
84 struct eb_stat {
85  int rx_count;
86  int jp;
87 };
88 NBR_TABLE(struct eb_stat, eb_stats);
89 #endif /* TSCH_AUTOSELECT_TIME_SOURCE */
90 
91 /* TSCH channel hopping sequence */
92 uint8_t tsch_hopping_sequence[TSCH_HOPPING_SEQUENCE_MAX_LEN];
93 struct tsch_asn_divisor_t tsch_hopping_sequence_length;
94 
95 /* Default TSCH timeslot timing (in micro-second) */
96 static const uint16_t *tsch_default_timing_us;
97 /* TSCH timeslot timing (in micro-second) */
98 uint16_t tsch_timing_us[tsch_ts_elements_count];
99 /* TSCH timeslot timing (in rtimer ticks) */
100 rtimer_clock_t tsch_timing[tsch_ts_elements_count];
101 
102 #if LINKADDR_SIZE == 8
103 /* 802.15.4 broadcast MAC address */
104 const linkaddr_t tsch_broadcast_address = { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff } };
105 /* Address used for the EB virtual neighbor queue */
106 const linkaddr_t tsch_eb_address = { { 0, 0, 0, 0, 0, 0, 0, 0 } };
107 #else /* LINKADDR_SIZE == 8 */
108 const linkaddr_t tsch_broadcast_address = { { 0xff, 0xff } };
109 const linkaddr_t tsch_eb_address = { { 0, 0 } };
110 #endif /* LINKADDR_SIZE == 8 */
111 
112 /* Is TSCH started? */
113 int tsch_is_started = 0;
114 /* Has TSCH initialization failed? */
115 int tsch_is_initialized = 0;
116 /* Are we coordinator of the TSCH network? */
117 int tsch_is_coordinator = 0;
118 /* Are we associated to a TSCH network? */
119 int tsch_is_associated = 0;
120 /* Total number of associations since boot */
121 int tsch_association_count = 0;
122 /* Is the PAN running link-layer security? */
123 int tsch_is_pan_secured = LLSEC802154_ENABLED;
124 /* The current Absolute Slot Number (ASN) */
125 struct tsch_asn_t tsch_current_asn;
126 /* Device rank or join priority:
127  * For PAN coordinator: 0 -- lower is better */
128 uint8_t tsch_join_priority;
129 /* The current TSCH sequence number, used for unicast data frames only */
130 static uint8_t tsch_packet_seqno;
131 /* Current period for EB output */
132 static clock_time_t tsch_current_eb_period;
133 /* Current period for keepalive output */
134 static clock_time_t tsch_current_ka_timeout;
135 
136 /* For scheduling keepalive messages */
137 enum tsch_keepalive_status {
138  KEEPALIVE_SCHEDULING_UNCHANGED,
139  KEEPALIVE_SCHEDULE_OR_STOP,
140  KEEPALIVE_SEND_IMMEDIATELY,
141 };
142 /* Should we send or schedule a keepalive? */
143 static volatile enum tsch_keepalive_status keepalive_status;
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;
194 }
195 /*---------------------------------------------------------------------------*/
196 void
197 tsch_set_eb_period(uint32_t period)
198 {
199  tsch_current_eb_period = MIN(period, TSCH_MAX_EB_PERIOD);
200 }
201 /*---------------------------------------------------------------------------*/
202 static void
203 tsch_reset(void)
204 {
205  int i;
206  frame802154_set_pan_id(0xffff);
207  /* First make sure pending packet callbacks are sent etc */
208  process_post_synch(&tsch_pending_events_process, PROCESS_EVENT_POLL, NULL);
209  /* Reset neighbor queues */
211  /* Remove unused neighbors */
214  /* Initialize global variables */
215  tsch_join_priority = 0xff;
216  TSCH_ASN_INIT(tsch_current_asn, 0, 0);
217  current_link = NULL;
218  /* Reset timeslot timing to defaults */
219  tsch_default_timing_us = TSCH_DEFAULT_TIMESLOT_TIMING;
220  for(i = 0; i < tsch_ts_elements_count; i++) {
221  tsch_timing_us[i] = tsch_default_timing_us[i];
222  tsch_timing[i] = US_TO_RTIMERTICKS(tsch_timing_us[i]);
223  }
224 #ifdef TSCH_CALLBACK_LEAVING_NETWORK
225  TSCH_CALLBACK_LEAVING_NETWORK();
226 #endif
227  linkaddr_copy(&last_eb_nbr_addr, &linkaddr_null);
228 #if TSCH_AUTOSELECT_TIME_SOURCE
229  struct eb_stat *stat;
230  best_neighbor_eb_count = 0;
231  /* Remove all nbr stats */
232  stat = nbr_table_head(eb_stats);
233  while(stat != NULL) {
234  nbr_table_remove(eb_stats, stat);
235  stat = nbr_table_next(eb_stats, stat);
236  }
237 #endif /* TSCH_AUTOSELECT_TIME_SOURCE */
238  tsch_set_eb_period(TSCH_EB_PERIOD);
239  keepalive_status = KEEPALIVE_SCHEDULING_UNCHANGED;
240 }
241 /* TSCH keep-alive functions */
242 
243 /*---------------------------------------------------------------------------*/
244 /* Resynchronize to last_eb_nbr.
245  * Return non-zero if this function schedules the next keepalive.
246  * Return zero otherwise.
247  */
248 static int
249 resynchronize(const linkaddr_t *original_time_source_addr)
250 {
251  const struct tsch_neighbor *current_time_source = tsch_queue_get_time_source();
252  const linkaddr_t *ts_addr = tsch_queue_get_nbr_address(current_time_source);
253  if(ts_addr != NULL && !linkaddr_cmp(ts_addr, original_time_source_addr)) {
254  /* Time source has already been changed (e.g. by RPL). Let's see if it works. */
255  LOG_INFO("time source has been changed to ");
256  LOG_INFO_LLADDR(ts_addr);
257  LOG_INFO_("\n");
258  return 0;
259  }
260  /* Switch time source to the last neighbor we received an EB from */
261  if(linkaddr_cmp(&last_eb_nbr_addr, &linkaddr_null)) {
262  LOG_WARN("not able to re-synchronize, received no EB from other neighbors\n");
263  if(sync_count == 0) {
264  /* We got no synchronization at all in this session, leave the network */
266  }
267  return 0;
268  } else {
269  LOG_WARN("re-synchronizing on ");
270  LOG_WARN_LLADDR(&last_eb_nbr_addr);
271  LOG_WARN_("\n");
272  /* We simply pick the last neighbor we receiver sync information from */
273  tsch_queue_update_time_source(&last_eb_nbr_addr);
274  tsch_join_priority = last_eb_nbr_jp + 1;
275  linkaddr_copy(&last_eb_nbr_addr, &linkaddr_null);
276  /* Try to get in sync ASAP */
278  return 1;
279  }
280 }
281 
282 /*---------------------------------------------------------------------------*/
283 /* Tx callback for keepalive messages */
284 static void
285 keepalive_packet_sent(void *ptr, int status, int transmissions)
286 {
287  int schedule_next_keepalive = 1;
288  /* Update neighbor link statistics */
289  link_stats_packet_sent(packetbuf_addr(PACKETBUF_ADDR_RECEIVER), status, transmissions);
290  /* Call RPL callback if RPL is enabled */
291 #ifdef TSCH_CALLBACK_KA_SENT
292  TSCH_CALLBACK_KA_SENT(status, transmissions);
293 #endif /* TSCH_CALLBACK_KA_SENT */
294  LOG_INFO("KA sent to ");
295  LOG_INFO_LLADDR(packetbuf_addr(PACKETBUF_ADDR_RECEIVER));
296  LOG_INFO_(", st %d-%d\n", status, transmissions);
297 
298  /* We got no ack, try to resynchronize */
299  if(status == MAC_TX_NOACK) {
300  schedule_next_keepalive = !resynchronize(packetbuf_addr(PACKETBUF_ADDR_RECEIVER));
301  }
302 
303  if(schedule_next_keepalive) {
305  }
306 }
307 /*---------------------------------------------------------------------------*/
308 /* Prepare and send a keepalive message */
309 static void
310 keepalive_send(void *ptr)
311 {
312  /* If not here from a timer callback, the timer must be stopped */
313  ctimer_stop(&keepalive_timer);
314 
315  if(tsch_is_associated) {
317  if(n != NULL) {
318  linkaddr_t *destination = tsch_queue_get_nbr_address(n);
319  /* Simply send an empty packet */
320  packetbuf_clear();
321  packetbuf_set_addr(PACKETBUF_ADDR_RECEIVER, destination);
322  NETSTACK_MAC.send(keepalive_packet_sent, NULL);
323  LOG_INFO("sending KA to ");
324  LOG_INFO_LLADDR(destination);
325  LOG_INFO_("\n");
326  } else {
327  LOG_ERR("no timesource - KA not sent\n");
328  }
329  }
330 }
331 /*---------------------------------------------------------------------------*/
332 void
334 {
335  if(immediate) {
336  /* send as soon as possible */
337  keepalive_status = KEEPALIVE_SEND_IMMEDIATELY;
338  } else if(keepalive_status != KEEPALIVE_SEND_IMMEDIATELY) {
339  /* send based on the tsch_current_ka_timeout */
340  keepalive_status = KEEPALIVE_SCHEDULE_OR_STOP;
341  }
342  process_poll(&tsch_pending_events_process);
343 }
344 /*---------------------------------------------------------------------------*/
345 static void
346 tsch_keepalive_process_pending(void)
347 {
348  if(keepalive_status != KEEPALIVE_SCHEDULING_UNCHANGED) {
349  /* first, save and reset the old status */
350  enum tsch_keepalive_status scheduled_status = keepalive_status;
351  keepalive_status = KEEPALIVE_SCHEDULING_UNCHANGED;
352 
353  if(!tsch_is_coordinator && tsch_is_associated) {
354  switch(scheduled_status) {
355  case KEEPALIVE_SEND_IMMEDIATELY:
356  /* always send, and as soon as possible (now) */
357  keepalive_send(NULL);
358  break;
359 
360  case KEEPALIVE_SCHEDULE_OR_STOP:
361  if(tsch_current_ka_timeout > 0) {
362  /* Pick a delay in the range [tsch_current_ka_timeout*0.9, tsch_current_ka_timeout[ */
363  unsigned long delay;
364  if(tsch_current_ka_timeout >= 10) {
365  delay = (tsch_current_ka_timeout - tsch_current_ka_timeout / 10)
366  + random_rand() % (tsch_current_ka_timeout / 10);
367  } else {
368  delay = tsch_current_ka_timeout - 1;
369  }
370  ctimer_set(&keepalive_timer, delay, keepalive_send, NULL);
371  } else {
372  /* zero timeout set, stop sending keepalives */
373  ctimer_stop(&keepalive_timer);
374  }
375  break;
376 
377  default:
378  break;
379  }
380  } else {
381  /* either coordinator or not associated */
382  ctimer_stop(&keepalive_timer);
383  }
384  }
385 }
386 /*---------------------------------------------------------------------------*/
387 static void
388 eb_input(struct input_packet *current_input)
389 {
390  /* LOG_INFO("EB received\n"); */
391  frame802154_t frame;
392  /* Verify incoming EB (does its ASN match our Rx time?),
393  * and update our join priority. */
394  struct ieee802154_ies eb_ies;
395 
396  if(tsch_packet_parse_eb(current_input->payload, current_input->len,
397  &frame, &eb_ies, NULL, 1)) {
398  /* PAN ID check and authentication done at rx time */
399 
400  /* Got an EB from a different neighbor than our time source, keep enough data
401  * to switch to it in case we lose the link to our time source */
403  linkaddr_t *ts_addr = tsch_queue_get_nbr_address(ts);
404  if(ts_addr == NULL || !linkaddr_cmp((linkaddr_t *)&frame.src_addr, ts_addr)) {
405  linkaddr_copy(&last_eb_nbr_addr, (linkaddr_t *)&frame.src_addr);
406  last_eb_nbr_jp = eb_ies.ie_join_priority;
407  }
408 
409 #if TSCH_AUTOSELECT_TIME_SOURCE
410  if(!tsch_is_coordinator) {
411  /* Maintain EB received counter for every neighbor */
412  struct eb_stat *stat = (struct eb_stat *)nbr_table_get_from_lladdr(eb_stats, (linkaddr_t *)&frame.src_addr);
413  if(stat == NULL) {
414  stat = (struct eb_stat *)nbr_table_add_lladdr(eb_stats, (linkaddr_t *)&frame.src_addr, NBR_TABLE_REASON_MAC, NULL);
415  }
416  if(stat != NULL) {
417  stat->rx_count++;
418  stat->jp = eb_ies.ie_join_priority;
419  best_neighbor_eb_count = MAX(best_neighbor_eb_count, stat->rx_count);
420  }
421  /* Select best time source */
422  struct eb_stat *best_stat = NULL;
423  stat = nbr_table_head(eb_stats);
424  while(stat != NULL) {
425  /* Is neighbor eligible as a time source? */
426  if(stat->rx_count > best_neighbor_eb_count / 2) {
427  if(best_stat == NULL ||
428  stat->jp < best_stat->jp) {
429  best_stat = stat;
430  }
431  }
432  stat = nbr_table_next(eb_stats, stat);
433  }
434  /* Update time source */
435  if(best_stat != NULL) {
436  tsch_queue_update_time_source(nbr_table_get_lladdr(eb_stats, best_stat));
437  tsch_join_priority = best_stat->jp + 1;
438  }
439  }
440 #endif /* TSCH_AUTOSELECT_TIME_SOURCE */
441 
442  /* Did the EB come from our time source? */
443  if(ts_addr != NULL && linkaddr_cmp((linkaddr_t *)&frame.src_addr, ts_addr)) {
444  /* Check for ASN drift */
445  int32_t asn_diff = TSCH_ASN_DIFF(current_input->rx_asn, eb_ies.ie_asn);
446  if(asn_diff != 0) {
447  /* We disagree with our time source's ASN -- leave the network */
448  LOG_WARN("! ASN drifted by %ld, leaving the network\n", asn_diff);
450  }
451 
452  if(eb_ies.ie_join_priority >= TSCH_MAX_JOIN_PRIORITY) {
453  /* Join priority unacceptable. Leave network. */
454  LOG_WARN("! EB JP too high %u, leaving the network\n",
455  eb_ies.ie_join_priority);
457  } else {
458 #if TSCH_AUTOSELECT_TIME_SOURCE
459  /* Update join priority */
460  if(tsch_join_priority != eb_ies.ie_join_priority + 1) {
461  LOG_INFO("update JP from EB %u -> %u\n",
462  tsch_join_priority, eb_ies.ie_join_priority + 1);
463  tsch_join_priority = eb_ies.ie_join_priority + 1;
464  }
465 #endif /* TSCH_AUTOSELECT_TIME_SOURCE */
466  }
467 
468  /* TSCH hopping sequence */
469  if(eb_ies.ie_channel_hopping_sequence_id != 0) {
470  if(eb_ies.ie_hopping_sequence_len != tsch_hopping_sequence_length.val
471  || memcmp((uint8_t *)tsch_hopping_sequence, eb_ies.ie_hopping_sequence_list, tsch_hopping_sequence_length.val)) {
472  if(eb_ies.ie_hopping_sequence_len <= sizeof(tsch_hopping_sequence)) {
473  memcpy((uint8_t *)tsch_hopping_sequence, eb_ies.ie_hopping_sequence_list,
474  eb_ies.ie_hopping_sequence_len);
475  TSCH_ASN_DIVISOR_INIT(tsch_hopping_sequence_length, eb_ies.ie_hopping_sequence_len);
476 
477  LOG_WARN("Updating TSCH hopping sequence from EB\n");
478  } else {
479  LOG_WARN("TSCH:! parse_eb: hopping sequence too long (%u)\n", eb_ies.ie_hopping_sequence_len);
480  }
481  }
482  }
483  }
484  }
485 }
486 /*---------------------------------------------------------------------------*/
487 /* Process pending input packet(s) */
488 static void
489 tsch_rx_process_pending()
490 {
491  int16_t input_index;
492  /* Loop on accessing (without removing) a pending input packet */
493  while((input_index = ringbufindex_peek_get(&input_ringbuf)) != -1) {
494  struct input_packet *current_input = &input_array[input_index];
495  frame802154_t frame;
496  uint8_t ret = frame802154_parse(current_input->payload, current_input->len, &frame);
497  int is_data = ret && frame.fcf.frame_type == FRAME802154_DATAFRAME;
498  int is_eb = ret
499  && frame.fcf.frame_version == FRAME802154_IEEE802154_2015
500  && frame.fcf.frame_type == FRAME802154_BEACONFRAME;
501 
502  if(is_data) {
503  /* Skip EBs and other control messages */
504  /* Copy to packetbuf for processing */
505  packetbuf_copyfrom(current_input->payload, current_input->len);
506  packetbuf_set_attr(PACKETBUF_ATTR_RSSI, current_input->rssi);
507  packetbuf_set_attr(PACKETBUF_ATTR_CHANNEL, current_input->channel);
508  }
509 
510  if(is_data) {
511  /* Pass to upper layers */
512  packet_input();
513  } else if(is_eb) {
514  eb_input(current_input);
515  }
516 
517  /* Remove input from ringbuf */
518  ringbufindex_get(&input_ringbuf);
519  }
520 }
521 /*---------------------------------------------------------------------------*/
522 /* Pass sent packets to upper layer */
523 static void
524 tsch_tx_process_pending(void)
525 {
526  int16_t dequeued_index;
527  /* Loop on accessing (without removing) a pending input packet */
528  while((dequeued_index = ringbufindex_peek_get(&dequeued_ringbuf)) != -1) {
529  struct tsch_packet *p = dequeued_array[dequeued_index];
530  /* Put packet into packetbuf for packet_sent callback */
531  queuebuf_to_packetbuf(p->qb);
532  LOG_INFO("packet sent to ");
533  LOG_INFO_LLADDR(packetbuf_addr(PACKETBUF_ADDR_RECEIVER));
534  LOG_INFO_(", seqno %u, status %d, tx %d\n",
535  packetbuf_attr(PACKETBUF_ATTR_MAC_SEQNO), p->ret, p->transmissions);
536  /* Call packet_sent callback */
537  mac_call_sent_callback(p->sent, p->ptr, p->ret, p->transmissions);
538  /* Free packet queuebuf */
540  /* Free all unused neighbors */
542  /* Remove dequeued packet from ringbuf */
543  ringbufindex_get(&dequeued_ringbuf);
544  }
545 }
546 /*---------------------------------------------------------------------------*/
547 /* Setup TSCH as a coordinator */
548 static void
549 tsch_start_coordinator(void)
550 {
551  frame802154_set_pan_id(IEEE802154_PANID);
552  /* Initialize hopping sequence as default */
553  memcpy(tsch_hopping_sequence, TSCH_DEFAULT_HOPPING_SEQUENCE, sizeof(TSCH_DEFAULT_HOPPING_SEQUENCE));
554  TSCH_ASN_DIVISOR_INIT(tsch_hopping_sequence_length, sizeof(TSCH_DEFAULT_HOPPING_SEQUENCE));
555 #if TSCH_SCHEDULE_WITH_6TISCH_MINIMAL
557 #endif
558 
559  tsch_is_associated = 1;
560  tsch_join_priority = 0;
561 
562  LOG_INFO("starting as coordinator, PAN ID %x, asn-%x.%lx\n",
563  frame802154_get_pan_id(), tsch_current_asn.ms1b, tsch_current_asn.ls4b);
564 
565  /* Start slot operation */
566  tsch_slot_operation_sync(RTIMER_NOW(), &tsch_current_asn);
567 }
568 /*---------------------------------------------------------------------------*/
569 /* Leave the TSCH network */
570 void
572 {
573  if(tsch_is_associated == 1) {
574  tsch_is_associated = 0;
576  process_poll(&tsch_process);
577  }
578 }
579 /*---------------------------------------------------------------------------*/
580 /* Attempt to associate to a network form an incoming EB */
581 static int
582 tsch_associate(const struct input_packet *input_eb, rtimer_clock_t timestamp)
583 {
584  frame802154_t frame;
585  struct ieee802154_ies ies;
586  uint8_t hdrlen;
587  int i;
588 
589  if(input_eb == NULL || tsch_packet_parse_eb(input_eb->payload, input_eb->len,
590  &frame, &ies, &hdrlen, 0) == 0) {
591  LOG_DBG("! failed to parse packet as EB while scanning (len %u)\n",
592  input_eb->len);
593  return 0;
594  }
595 
596  tsch_current_asn = ies.ie_asn;
597  tsch_join_priority = ies.ie_join_priority + 1;
598 
599 #if TSCH_JOIN_SECURED_ONLY
600  if(frame.fcf.security_enabled == 0) {
601  LOG_ERR("! parse_eb: EB is not secured\n");
602  return 0;
603  }
604 #endif /* TSCH_JOIN_SECURED_ONLY */
605 #if LLSEC802154_ENABLED
606  if(!tsch_security_parse_frame(input_eb->payload, hdrlen,
607  input_eb->len - hdrlen - tsch_security_mic_len(&frame),
608  &frame, (linkaddr_t*)&frame.src_addr, &tsch_current_asn)) {
609  LOG_ERR("! parse_eb: failed to authenticate\n");
610  return 0;
611  }
612 #endif /* LLSEC802154_ENABLED */
613 
614 #if !LLSEC802154_ENABLED
615  if(frame.fcf.security_enabled == 1) {
616  LOG_ERR("! parse_eb: we do not support security, but EB is secured\n");
617  return 0;
618  }
619 #endif /* !LLSEC802154_ENABLED */
620 
621 #if TSCH_JOIN_MY_PANID_ONLY
622  /* Check if the EB comes from the PAN ID we expect */
623  if(frame.src_pid != IEEE802154_PANID) {
624  LOG_ERR("! parse_eb: PAN ID %x != %x\n", frame.src_pid, IEEE802154_PANID);
625  return 0;
626  }
627 #endif /* TSCH_JOIN_MY_PANID_ONLY */
628 
629  /* There was no join priority (or 0xff) in the EB, do not join */
630  if(ies.ie_join_priority == 0xff) {
631  LOG_ERR("! parse_eb: no join priority\n");
632  return 0;
633  }
634 
635  /* TSCH timeslot timing */
636  for(i = 0; i < tsch_ts_elements_count; i++) {
637  if(ies.ie_tsch_timeslot_id == 0) {
638  tsch_timing_us[i] = tsch_default_timing_us[i];
639  } else {
640  tsch_timing_us[i] = ies.ie_tsch_timeslot[i];
641  }
642  tsch_timing[i] = US_TO_RTIMERTICKS(tsch_timing_us[i]);
643  }
644 
645  /* TSCH hopping sequence */
646  if(ies.ie_channel_hopping_sequence_id == 0) {
647  memcpy(tsch_hopping_sequence, TSCH_DEFAULT_HOPPING_SEQUENCE, sizeof(TSCH_DEFAULT_HOPPING_SEQUENCE));
648  TSCH_ASN_DIVISOR_INIT(tsch_hopping_sequence_length, sizeof(TSCH_DEFAULT_HOPPING_SEQUENCE));
649  } else {
650  if(ies.ie_hopping_sequence_len <= sizeof(tsch_hopping_sequence)) {
651  memcpy(tsch_hopping_sequence, ies.ie_hopping_sequence_list, ies.ie_hopping_sequence_len);
652  TSCH_ASN_DIVISOR_INIT(tsch_hopping_sequence_length, ies.ie_hopping_sequence_len);
653  } else {
654  LOG_ERR("! parse_eb: hopping sequence too long (%u)\n", ies.ie_hopping_sequence_len);
655  return 0;
656  }
657  }
658 
659 #if TSCH_CHECK_TIME_AT_ASSOCIATION > 0
660  /* Divide by 4k and multiply again to avoid integer overflow */
661  uint32_t expected_asn = 4096 * TSCH_CLOCK_TO_SLOTS(clock_time() / 4096, tsch_timing_timeslot_length); /* Expected ASN based on our current time*/
662  int32_t asn_threshold = TSCH_CHECK_TIME_AT_ASSOCIATION * 60ul * TSCH_CLOCK_TO_SLOTS(CLOCK_SECOND, tsch_timing_timeslot_length);
663  int32_t asn_diff = (int32_t)tsch_current_asn.ls4b - expected_asn;
664  if(asn_diff > asn_threshold) {
665  LOG_ERR("! EB ASN rejected %lx %lx %ld\n",
666  tsch_current_asn.ls4b, expected_asn, asn_diff);
667  return 0;
668  }
669 #endif
670 
671 #if TSCH_INIT_SCHEDULE_FROM_EB
672  /* Create schedule */
673  if(ies.ie_tsch_slotframe_and_link.num_slotframes == 0) {
674 #if TSCH_SCHEDULE_WITH_6TISCH_MINIMAL
675  LOG_INFO("parse_eb: no schedule, setting up minimal schedule\n");
677 #else
678  LOG_INFO("parse_eb: no schedule\n");
679 #endif
680  } else {
681  /* First, empty current schedule */
683  /* We support only 0 or 1 slotframe in this IE */
684  int num_links = ies.ie_tsch_slotframe_and_link.num_links;
685  if(num_links <= FRAME802154E_IE_MAX_LINKS) {
686  int i;
688  ies.ie_tsch_slotframe_and_link.slotframe_handle,
689  ies.ie_tsch_slotframe_and_link.slotframe_size);
690  for(i = 0; i < num_links; i++) {
692  ies.ie_tsch_slotframe_and_link.links[i].link_options,
693  LINK_TYPE_ADVERTISING, &tsch_broadcast_address,
694  ies.ie_tsch_slotframe_and_link.links[i].timeslot,
695  ies.ie_tsch_slotframe_and_link.links[i].channel_offset, 1);
696  }
697  } else {
698  LOG_ERR("! parse_eb: too many links in schedule (%u)\n", num_links);
699  return 0;
700  }
701  }
702 #endif /* TSCH_INIT_SCHEDULE_FROM_EB */
703 
704  if(tsch_join_priority < TSCH_MAX_JOIN_PRIORITY) {
705  struct tsch_neighbor *n;
706 
707  /* Add coordinator to list of neighbors, lock the entry */
708  n = tsch_queue_add_nbr((linkaddr_t *)&frame.src_addr);
709 
710  if(n != NULL) {
711  tsch_queue_update_time_source((linkaddr_t *)&frame.src_addr);
712 
713  /* Set PANID */
714  frame802154_set_pan_id(frame.src_pid);
715 
716  /* Synchronize on EB */
717  tsch_slot_operation_sync(timestamp - tsch_timing[tsch_ts_tx_offset], &tsch_current_asn);
718 
719  /* Update global flags */
720  tsch_is_associated = 1;
721  tsch_is_pan_secured = frame.fcf.security_enabled;
722  tx_count = 0;
723  rx_count = 0;
724  sync_count = 0;
725  min_drift_seen = 0;
726  max_drift_seen = 0;
727 
728  /* Start sending keep-alives now that tsch_is_associated is set */
730 
731 #ifdef TSCH_CALLBACK_JOINING_NETWORK
732  TSCH_CALLBACK_JOINING_NETWORK();
733 #endif
734 
735  tsch_association_count++;
736  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 ",
737  tsch_association_count,
738  tsch_is_pan_secured,
739  frame.src_pid,
740  tsch_current_asn.ms1b, tsch_current_asn.ls4b, tsch_join_priority,
741  ies.ie_tsch_timeslot_id,
742  ies.ie_channel_hopping_sequence_id,
743  ies.ie_tsch_slotframe_and_link.slotframe_size,
744  ies.ie_tsch_slotframe_and_link.num_links);
745  LOG_INFO_LLADDR((const linkaddr_t *)&frame.src_addr);
746  LOG_INFO_("\n");
747 
748  return 1;
749  }
750  }
751  LOG_ERR("! did not associate.\n");
752  return 0;
753 }
754 /* Processes and protothreads used by TSCH */
755 
756 /*---------------------------------------------------------------------------*/
757 /* Scanning protothread, called by tsch_process:
758  * Listen to different channels, and when receiving an EB,
759  * attempt to associate.
760  */
761 PT_THREAD(tsch_scan(struct pt *pt))
762 {
763  PT_BEGIN(pt);
764 
765  static struct input_packet input_eb;
766  static struct etimer scan_timer;
767  /* Time when we started scanning on current_channel */
768  static clock_time_t current_channel_since;
769 
770  TSCH_ASN_INIT(tsch_current_asn, 0, 0);
771 
772  etimer_set(&scan_timer, CLOCK_SECOND / TSCH_ASSOCIATION_POLL_FREQUENCY);
773  current_channel_since = clock_time();
774 
775  while(!tsch_is_associated && !tsch_is_coordinator) {
776  /* Hop to any channel offset */
777  static uint8_t current_channel = 0;
778 
779  /* We are not coordinator, try to associate */
780  rtimer_clock_t t0;
781  int is_packet_pending = 0;
782  clock_time_t now_time = clock_time();
783 
784  /* Switch to a (new) channel for scanning */
785  if(current_channel == 0 || now_time - current_channel_since > TSCH_CHANNEL_SCAN_DURATION) {
786  /* Pick a channel at random in TSCH_JOIN_HOPPING_SEQUENCE */
787  uint8_t scan_channel = TSCH_JOIN_HOPPING_SEQUENCE[
788  random_rand() % sizeof(TSCH_JOIN_HOPPING_SEQUENCE)];
789 
790  NETSTACK_RADIO.set_value(RADIO_PARAM_CHANNEL, scan_channel);
791  current_channel = scan_channel;
792  LOG_INFO("scanning on channel %u\n", scan_channel);
793 
794  current_channel_since = now_time;
795  }
796 
797  /* Turn radio on and wait for EB */
798  NETSTACK_RADIO.on();
799 
800  is_packet_pending = NETSTACK_RADIO.pending_packet();
801  if(!is_packet_pending && NETSTACK_RADIO.receiving_packet()) {
802  /* If we are currently receiving a packet, wait until end of reception */
803  t0 = RTIMER_NOW();
804  RTIMER_BUSYWAIT_UNTIL_ABS((is_packet_pending = NETSTACK_RADIO.pending_packet()), t0, RTIMER_SECOND / 100);
805  }
806 
807  if(is_packet_pending) {
808  rtimer_clock_t t1;
809  /* Read packet */
810  input_eb.len = NETSTACK_RADIO.read(input_eb.payload, TSCH_PACKET_MAX_LEN);
811 
812  if(input_eb.len > 0) {
813  /* Save packet timestamp */
814  NETSTACK_RADIO.get_object(RADIO_PARAM_LAST_PACKET_TIMESTAMP, &t0, sizeof(rtimer_clock_t));
815  t1 = RTIMER_NOW();
816 
817  /* Parse EB and attempt to associate */
818  LOG_INFO("scan: received packet (%u bytes) on channel %u\n", input_eb.len, current_channel);
819 
820  /* Sanity-check the timestamp */
821  if(ABS(RTIMER_CLOCK_DIFF(t0, t1)) < 2ul * RTIMER_SECOND) {
822  tsch_associate(&input_eb, t0);
823  } else {
824  LOG_WARN("scan: dropping packet, timestamp too far from current time %u %u\n",
825  (unsigned)t0,
826  (unsigned)t1
827  );
828  }
829  }
830  }
831 
832  if(tsch_is_associated) {
833  /* End of association, turn the radio off */
834  NETSTACK_RADIO.off();
835  } else if(!tsch_is_coordinator) {
836  /* Go back to scanning */
837  etimer_reset(&scan_timer);
838  PT_WAIT_UNTIL(pt, etimer_expired(&scan_timer));
839  }
840  }
841 
842  PT_END(pt);
843 }
844 
845 /*---------------------------------------------------------------------------*/
846 /* The main TSCH process */
847 PROCESS_THREAD(tsch_process, ev, data)
848 {
849  static struct pt scan_pt;
850 
851  PROCESS_BEGIN();
852 
853  while(1) {
854 
855  while(!tsch_is_associated) {
856  if(tsch_is_coordinator) {
857  /* We are coordinator, start operating now */
858  tsch_start_coordinator();
859  } else {
860  /* Start scanning, will attempt to join when receiving an EB */
861  PROCESS_PT_SPAWN(&scan_pt, tsch_scan(&scan_pt));
862  }
863  }
864 
865  /* We are part of a TSCH network, start slot operation */
867 
868  /* Yield our main process. Slot operation will re-schedule itself
869  * as long as we are associated */
870  PROCESS_YIELD_UNTIL(!tsch_is_associated);
871 
872  LOG_WARN("leaving the network, stats: tx %lu, rx %lu, sync %lu\n",
873  tx_count, rx_count, sync_count);
874 
875  /* Will need to re-synchronize */
876  tsch_reset();
877  }
878 
879  PROCESS_END();
880 }
881 
882 /*---------------------------------------------------------------------------*/
883 /* A periodic process to send TSCH Enhanced Beacons (EB) */
884 PROCESS_THREAD(tsch_send_eb_process, ev, data)
885 {
886  static struct etimer eb_timer;
887 
888  PROCESS_BEGIN();
889 
890  /* Wait until association */
891  etimer_set(&eb_timer, CLOCK_SECOND / 10);
892  while(!tsch_is_associated) {
894  etimer_reset(&eb_timer);
895  }
896 
897  /* Set an initial delay except for coordinator, which should send an EB asap */
898  if(!tsch_is_coordinator) {
899  etimer_set(&eb_timer, TSCH_EB_PERIOD ? random_rand() % TSCH_EB_PERIOD : 0);
901  }
902 
903  while(1) {
904  unsigned long delay;
905 
906  if(!tsch_is_associated) {
907  LOG_DBG("skip sending EB: not joined a TSCH network\n");
908  } else if(tsch_current_eb_period <= 0) {
909  LOG_DBG("skip sending EB: EB period disabled\n");
910 #ifdef TSCH_RPL_CHECK_DODAG_JOINED
911  } else if(!TSCH_RPL_CHECK_DODAG_JOINED()) {
912  /* Implementation section 6.3 of RFC 8180 */
913  LOG_DBG("skip sending EB: not joined a routing DAG\n");
914 #endif /* TSCH_RPL_CHECK_DODAG_JOINED */
915  } else if(NETSTACK_ROUTING.is_in_leaf_mode()) {
916  /* don't send when in leaf mode */
917  LOG_DBG("skip sending EB: in the leaf mode\n");
918  } else if(tsch_queue_nbr_packet_count(n_eb) != 0) {
919  /* Enqueue EB only if there isn't already one in queue */
920  LOG_DBG("skip sending EB: already queued\n");
921  } else {
922  uint8_t hdr_len = 0;
923  uint8_t tsch_sync_ie_offset;
924  /* Prepare the EB packet and schedule it to be sent */
925  if(tsch_packet_create_eb(&hdr_len, &tsch_sync_ie_offset) > 0) {
926  struct tsch_packet *p;
927  /* Enqueue EB packet, for a single transmission only */
928  if(!(p = tsch_queue_add_packet(&tsch_eb_address, 1, NULL, NULL))) {
929  LOG_ERR("! could not enqueue EB packet\n");
930  } else {
931  LOG_INFO("TSCH: enqueue EB packet %u %u\n",
933  p->tsch_sync_ie_offset = tsch_sync_ie_offset;
934  p->header_len = hdr_len;
935  }
936  }
937  }
938  if(tsch_current_eb_period > 0) {
939  /* Next EB transmission with a random delay
940  * within [tsch_current_eb_period*0.75, tsch_current_eb_period[ */
941  delay = (tsch_current_eb_period - tsch_current_eb_period / 4)
942  + random_rand() % (tsch_current_eb_period / 4);
943  } else {
944  delay = TSCH_EB_PERIOD;
945  }
946  etimer_set(&eb_timer, delay);
948  }
949  PROCESS_END();
950 }
951 
952 /*---------------------------------------------------------------------------*/
953 /* A process that is polled from interrupt and calls tx/rx input
954  * callbacks, outputs pending logs. */
955 PROCESS_THREAD(tsch_pending_events_process, ev, data)
956 {
957  PROCESS_BEGIN();
958  while(1) {
959  PROCESS_YIELD_UNTIL(ev == PROCESS_EVENT_POLL);
960  tsch_rx_process_pending();
961  tsch_tx_process_pending();
963  tsch_keepalive_process_pending();
964 #ifdef TSCH_CALLBACK_SELECT_CHANNELS
965  TSCH_CALLBACK_SELECT_CHANNELS();
966 #endif
967  }
968  PROCESS_END();
969 }
970 
971 /* Functions from the Contiki MAC layer driver interface */
972 
973 /*---------------------------------------------------------------------------*/
974 static void
975 tsch_init(void)
976 {
977  radio_value_t radio_rx_mode;
978  radio_value_t radio_tx_mode;
979  radio_value_t radio_max_payload_len;
980 
981  rtimer_clock_t t;
982 
983  /* Check that the platform provides a TSCH timeslot timing template */
984  if(TSCH_DEFAULT_TIMESLOT_TIMING == NULL) {
985  LOG_ERR("! platform does not provide a timeslot timing template.\n");
986  return;
987  }
988 
989  /* Check that the radio can correctly report its max supported payload */
990  if(NETSTACK_RADIO.get_value(RADIO_CONST_MAX_PAYLOAD_LEN, &radio_max_payload_len) != RADIO_RESULT_OK) {
991  LOG_ERR("! radio does not support getting RADIO_CONST_MAX_PAYLOAD_LEN. Abort init.\n");
992  return;
993  }
994 
995  /* Radio Rx mode */
996  if(NETSTACK_RADIO.get_value(RADIO_PARAM_RX_MODE, &radio_rx_mode) != RADIO_RESULT_OK) {
997  LOG_ERR("! radio does not support getting RADIO_PARAM_RX_MODE. Abort init.\n");
998  return;
999  }
1000  /* Disable radio in frame filtering */
1001  radio_rx_mode &= ~RADIO_RX_MODE_ADDRESS_FILTER;
1002  /* Unset autoack */
1003  radio_rx_mode &= ~RADIO_RX_MODE_AUTOACK;
1004  /* Set radio in poll mode */
1005  radio_rx_mode |= RADIO_RX_MODE_POLL_MODE;
1006  if(NETSTACK_RADIO.set_value(RADIO_PARAM_RX_MODE, radio_rx_mode) != RADIO_RESULT_OK) {
1007  LOG_ERR("! radio does not support setting required RADIO_PARAM_RX_MODE. Abort init.\n");
1008  return;
1009  }
1010 
1011  /* Radio Tx mode */
1012  if(NETSTACK_RADIO.get_value(RADIO_PARAM_TX_MODE, &radio_tx_mode) != RADIO_RESULT_OK) {
1013  LOG_ERR("! radio does not support getting RADIO_PARAM_TX_MODE. Abort init.\n");
1014  return;
1015  }
1016  /* Unset CCA */
1017  radio_tx_mode &= ~RADIO_TX_MODE_SEND_ON_CCA;
1018  if(NETSTACK_RADIO.set_value(RADIO_PARAM_TX_MODE, radio_tx_mode) != RADIO_RESULT_OK) {
1019  LOG_ERR("! radio does not support setting required RADIO_PARAM_TX_MODE. Abort init.\n");
1020  return;
1021  }
1022  /* Test setting channel */
1023  if(NETSTACK_RADIO.set_value(RADIO_PARAM_CHANNEL, TSCH_DEFAULT_HOPPING_SEQUENCE[0]) != RADIO_RESULT_OK) {
1024  LOG_ERR("! radio does not support setting channel. Abort init.\n");
1025  return;
1026  }
1027  /* Test getting timestamp */
1028  if(NETSTACK_RADIO.get_object(RADIO_PARAM_LAST_PACKET_TIMESTAMP, &t, sizeof(rtimer_clock_t)) != RADIO_RESULT_OK) {
1029  LOG_ERR("! radio does not support getting last packet timestamp. Abort init.\n");
1030  return;
1031  }
1032  /* Check max hopping sequence length vs default sequence length */
1033  if(TSCH_HOPPING_SEQUENCE_MAX_LEN < sizeof(TSCH_DEFAULT_HOPPING_SEQUENCE)) {
1034  LOG_ERR("! TSCH_HOPPING_SEQUENCE_MAX_LEN < sizeof(TSCH_DEFAULT_HOPPING_SEQUENCE). Abort init.\n");
1035  return;
1036  }
1037 
1038  /* Init TSCH sub-modules */
1039 #if TSCH_AUTOSELECT_TIME_SOURCE
1040  nbr_table_register(eb_stats, NULL);
1041 #endif /* TSCH_AUTOSELECT_TIME_SOURCE */
1042  tsch_reset();
1043  tsch_queue_init();
1045  tsch_log_init();
1046  ringbufindex_init(&input_ringbuf, TSCH_MAX_INCOMING_PACKETS);
1047  ringbufindex_init(&dequeued_ringbuf, TSCH_DEQUEUED_ARRAY_SIZE);
1048 
1049  tsch_packet_seqno = random_rand();
1050  tsch_is_initialized = 1;
1051 
1052 #if TSCH_AUTOSTART
1053  /* Start TSCH operation.
1054  * If TSCH_AUTOSTART is not set, one needs to call NETSTACK_MAC.on() to start TSCH. */
1055  NETSTACK_MAC.on();
1056 #endif /* TSCH_AUTOSTART */
1057 
1058 #if TSCH_WITH_SIXTOP
1059  sixtop_init();
1060 #endif
1061 
1062  tsch_stats_init();
1063 }
1064 /*---------------------------------------------------------------------------*/
1065 /* Function send for TSCH-MAC, puts the packet in packetbuf in the MAC queue */
1066 static void
1067 send_packet(mac_callback_t sent, void *ptr)
1068 {
1069  int ret = MAC_TX_DEFERRED;
1070  int hdr_len = 0;
1071  const linkaddr_t *addr = packetbuf_addr(PACKETBUF_ADDR_RECEIVER);
1072  uint8_t max_transmissions = 0;
1073 
1074  if(!tsch_is_associated) {
1075  if(!tsch_is_initialized) {
1076  LOG_WARN("! not initialized (see earlier logs), drop outgoing packet\n");
1077  } else {
1078  LOG_WARN("! not associated, drop outgoing packet\n");
1079  }
1080  ret = MAC_TX_ERR;
1081  mac_call_sent_callback(sent, ptr, ret, 1);
1082  return;
1083  }
1084 
1085  /* Ask for ACK if we are sending anything other than broadcast */
1086  if(!linkaddr_cmp(addr, &linkaddr_null)) {
1087  /* PACKETBUF_ATTR_MAC_SEQNO cannot be zero, due to a pecuilarity
1088  in framer-802154.c. */
1089  if(++tsch_packet_seqno == 0) {
1090  tsch_packet_seqno++;
1091  }
1092  packetbuf_set_attr(PACKETBUF_ATTR_MAC_SEQNO, tsch_packet_seqno);
1093  packetbuf_set_attr(PACKETBUF_ATTR_MAC_ACK, 1);
1094  } else {
1095  /* Broadcast packets shall be added to broadcast queue
1096  * The broadcast address in Contiki is linkaddr_null which is equal
1097  * to tsch_eb_address */
1098  addr = &tsch_broadcast_address;
1099  }
1100 
1101  packetbuf_set_attr(PACKETBUF_ATTR_FRAME_TYPE, FRAME802154_DATAFRAME);
1102 
1103 #if LLSEC802154_ENABLED
1104  tsch_security_set_packetbuf_attr(FRAME802154_DATAFRAME);
1105 #endif /* LLSEC802154_ENABLED */
1106 
1107 #if !NETSTACK_CONF_BRIDGE_MODE
1108  /*
1109  * In the Contiki stack, the source address of a frame is set at the RDC
1110  * layer. Since TSCH doesn't use any RDC protocol and bypasses the layer to
1111  * transmit a frame, it should set the source address by itself.
1112  */
1113  packetbuf_set_addr(PACKETBUF_ADDR_SENDER, &linkaddr_node_addr);
1114 #endif
1115 
1116  max_transmissions = packetbuf_attr(PACKETBUF_ATTR_MAX_MAC_TRANSMISSIONS);
1117  if(max_transmissions == 0) {
1118  /* If not set by the application, use the default TSCH value */
1119  max_transmissions = TSCH_MAC_MAX_FRAME_RETRIES + 1;
1120  }
1121 
1122  if((hdr_len = NETSTACK_FRAMER.create()) < 0) {
1123  LOG_ERR("! can't send packet due to framer error\n");
1124  ret = MAC_TX_ERR;
1125  } else {
1126  struct tsch_packet *p;
1127  struct tsch_neighbor *n;
1128  /* Enqueue packet */
1129  p = tsch_queue_add_packet(addr, max_transmissions, sent, ptr);
1130  n = tsch_queue_get_nbr(addr);
1131  if(p == NULL) {
1132  LOG_ERR("! can't send packet to ");
1133  LOG_ERR_LLADDR(addr);
1134  LOG_ERR_(" with seqno %u, queue %u/%u %u/%u\n",
1135  tsch_packet_seqno, tsch_queue_nbr_packet_count(n),
1136  TSCH_QUEUE_NUM_PER_NEIGHBOR, tsch_queue_global_packet_count(),
1137  QUEUEBUF_NUM);
1138  ret = MAC_TX_ERR;
1139  } else {
1140  p->header_len = hdr_len;
1141  LOG_INFO("send packet to ");
1142  LOG_INFO_LLADDR(addr);
1143  LOG_INFO_(" with seqno %u, queue %u/%u %u/%u, len %u %u\n",
1144  tsch_packet_seqno, tsch_queue_nbr_packet_count(n),
1145  TSCH_QUEUE_NUM_PER_NEIGHBOR, tsch_queue_global_packet_count(),
1146  QUEUEBUF_NUM, p->header_len, queuebuf_datalen(p->qb));
1147  }
1148  }
1149  if(ret != MAC_TX_DEFERRED) {
1150  mac_call_sent_callback(sent, ptr, ret, 1);
1151  }
1152 }
1153 /*---------------------------------------------------------------------------*/
1154 static void
1155 packet_input(void)
1156 {
1157  int frame_parsed = 1;
1158 
1159  frame_parsed = NETSTACK_FRAMER.parse();
1160 
1161  if(frame_parsed < 0) {
1162  LOG_ERR("! failed to parse %u\n", packetbuf_datalen());
1163  } else {
1164  int duplicate = 0;
1165 
1166  /* Seqno of 0xffff means no seqno */
1167  if(packetbuf_attr(PACKETBUF_ATTR_MAC_SEQNO) != 0xffff) {
1168  /* Check for duplicates */
1169  duplicate = mac_sequence_is_duplicate();
1170  if(duplicate) {
1171  /* Drop the packet. */
1172  LOG_WARN("! drop dup ll from ");
1173  LOG_WARN_LLADDR(packetbuf_addr(PACKETBUF_ADDR_SENDER));
1174  LOG_WARN_(" seqno %u\n", packetbuf_attr(PACKETBUF_ATTR_MAC_SEQNO));
1175  } else {
1177  }
1178  }
1179 
1180  if(!duplicate) {
1181  LOG_INFO("received from ");
1182  LOG_INFO_LLADDR(packetbuf_addr(PACKETBUF_ADDR_SENDER));
1183  LOG_INFO_(" with seqno %u\n", packetbuf_attr(PACKETBUF_ATTR_MAC_SEQNO));
1184 #if TSCH_WITH_SIXTOP
1185  sixtop_input();
1186 #endif /* TSCH_WITH_SIXTOP */
1187  NETSTACK_NETWORK.input();
1188  }
1189  }
1190 }
1191 /*---------------------------------------------------------------------------*/
1192 static int
1193 turn_on(void)
1194 {
1195  if(tsch_is_initialized == 1 && tsch_is_started == 0) {
1196  tsch_is_started = 1;
1197  /* Process tx/rx callback and log messages whenever polled */
1198  process_start(&tsch_pending_events_process, NULL);
1199  if(TSCH_EB_PERIOD > 0) {
1200  /* periodically send TSCH EBs */
1201  process_start(&tsch_send_eb_process, NULL);
1202  }
1203  /* try to associate to a network or start one if setup as coordinator */
1204  process_start(&tsch_process, NULL);
1205  LOG_INFO("starting as %s\n", tsch_is_coordinator ? "coordinator": "node");
1206  return 1;
1207  }
1208  return 0;
1209 }
1210 /*---------------------------------------------------------------------------*/
1211 static int
1212 turn_off(void)
1213 {
1214  NETSTACK_RADIO.off();
1215  return 1;
1216 }
1217 /*---------------------------------------------------------------------------*/
1218 static int
1219 max_payload(void)
1220 {
1221  int framer_hdrlen;
1222  radio_value_t max_radio_payload_len;
1223  radio_result_t res;
1224 
1225  if(!tsch_is_associated) {
1226  LOG_WARN("Cannot compute max payload size: not associated\n");
1227  return 0;
1228  }
1229 
1230  res = NETSTACK_RADIO.get_value(RADIO_CONST_MAX_PAYLOAD_LEN,
1231  &max_radio_payload_len);
1232 
1233  if(res == RADIO_RESULT_NOT_SUPPORTED) {
1234  LOG_ERR("Failed to retrieve max radio driver payload length\n");
1235  return 0;
1236  }
1237 
1238  /* Set packetbuf security attributes */
1239  tsch_security_set_packetbuf_attr(FRAME802154_DATAFRAME);
1240 
1241  framer_hdrlen = NETSTACK_FRAMER.length();
1242  if(framer_hdrlen < 0) {
1243  return 0;
1244  }
1245 
1246  /* Setup security... before. */
1247  return MIN(max_radio_payload_len, TSCH_PACKET_MAX_LEN)
1248  - framer_hdrlen
1249  - LLSEC802154_PACKETBUF_MIC_LEN();
1250 }
1251 /*---------------------------------------------------------------------------*/
1252 const struct mac_driver tschmac_driver = {
1253  "TSCH",
1254  tsch_init,
1255  send_packet,
1256  packet_input,
1257  turn_on,
1258  turn_off,
1259  max_payload,
1260 };
1261 /*---------------------------------------------------------------------------*/
1262 /** @} */
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:279
struct tsch_neighbor * tsch_queue_get_nbr(const linkaddr_t *addr)
Get a TSCH neighbor.
Definition: tsch-queue.c:110
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.
The parameter is not supported.
Definition: radio.h:473
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:220
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:1502
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:523
#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.
Channel used for radio communication.
Definition: radio.h:134
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:120
#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
The parameter was set/read successfully.
Definition: radio.h:472
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:73
uint8_t(* is_in_leaf_mode)(void)
Tells whether the protocol is in leaf mode.
Definition: routing.h:190
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
A MAC framer for IEEE 802.15.4
const linkaddr_t linkaddr_null
The null link-layer address.
Radio transmission mode determines if the radio has send on CCA (RADIO_TX_MODE_SEND_ON_CCA) enabled o...
Definition: radio.h:180
#define RTIMER_SECOND
Number of rtimer ticks for 1 second.
Definition: rtimer.h:112
Header file for MAC sequence numbers management
void tsch_queue_free_unused_neighbors(void)
Deallocate all neighbors with empty queue.
Definition: tsch-queue.c:385
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:261
#define RTIMER_NOW()
Get the current clock time.
Definition: rtimer.h:185
void sixtop_input(void)
Input a packet stored in packetbuf.
Definition: sixtop.c:204
int tsch_queue_nbr_packet_count(const struct tsch_neighbor *n)
Returns the number of packets currently a given neighbor queue (by pointer)
Definition: tsch-queue.c:286
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
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, uint8_t do_remove)
Adds a link to a slotframe.
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
linkaddr_t * tsch_queue_get_nbr_address(const struct tsch_neighbor *n)
Get the address of a neighbor.
Definition: tsch-queue.c:135
struct tsch_neighbor * tsch_queue_add_nbr(const linkaddr_t *addr)
Add a TSCH neighbor queue.
Definition: tsch-queue.c:81
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:197
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
void tsch_schedule_keepalive(int immediate)
Schedule a keep-alive transmission within [timeout*0.9, timeout[ Can be called from an interrupt...
Definition: tsch.c:333
Radio receiver mode determines if the radio has address filter (RADIO_RX_MODE_ADDRESS_FILTER) and aut...
Definition: radio.h:173
int tsch_queue_update_time_source(const linkaddr_t *new_addr)
Update TSCH time source.
Definition: tsch-queue.c:142
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:202
int etimer_expired(struct etimer *et)
Check if an event timer has expired.
Definition: etimer.c:213
#define TSCH_ASN_INIT(asn, ms1b_, ls4b_)
Initialize ASN.
Definition: tsch-asn.h:62
void tsch_security_set_packetbuf_attr(uint8_t frame_type)
Set packetbuf (or eackbuf) attributes depending on a given frame type.
#define RADIO_RX_MODE_ADDRESS_FILTER
Enable address-based frame filtering.
Definition: radio.h:443
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
enum radio_result_e radio_result_t
Radio return values when setting or getting radio parameters.
A timer.
Definition: etimer.h:76
6TiSCH Operation Sublayer (6top) APIs
#define RADIO_TX_MODE_SEND_ON_CCA
Radio TX mode control / retrieval.
Definition: radio.h:466
#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:367
#define RADIO_RX_MODE_AUTOACK
Enable automatic transmission of ACK frames.
Definition: radio.h:448
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.
#define RADIO_RX_MODE_POLL_MODE
Enable/disable/get the state of radio driver poll mode operation.
Definition: radio.h:453
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:571
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:314
PROCESS_THREAD(cc2538_rf_process, ev, data)
Implementation of the cc2538 RF driver process.
Definition: cc2538-rf.c:1110
Last packet timestamp, of type rtimer_clock_t.
Definition: radio.h:278
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:229
void tsch_adaptive_timesync_reset(void)
Reset the status of the module.
Stores data about an incoming packet.
Definition: tsch-types.h:149
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:387
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