Contiki-NG
tsch-slot-operation.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  * TSCH slot operation implementation, running from interrupt.
36  * \author
37  * Simon Duquennoy <simonduq@sics.se>
38  * Beshr Al Nahas <beshr@sics.se>
39  * Atis Elsts <atis.elsts@bristol.ac.uk>
40  *
41  */
42 
43 /**
44  * \addtogroup tsch
45  * @{
46 */
47 
48 #include "dev/radio.h"
49 #include "contiki.h"
50 #include "net/netstack.h"
51 #include "net/packetbuf.h"
52 #include "net/queuebuf.h"
54 #include "net/mac/tsch/tsch.h"
55 
56 #include "sys/log.h"
57 /* TSCH debug macros, i.e. to set LEDs or GPIOs on various TSCH
58  * timeslot events */
59 #ifndef TSCH_DEBUG_INIT
60 #define TSCH_DEBUG_INIT()
61 #endif
62 #ifndef TSCH_DEBUG_INTERRUPT
63 #define TSCH_DEBUG_INTERRUPT()
64 #endif
65 #ifndef TSCH_DEBUG_RX_EVENT
66 #define TSCH_DEBUG_RX_EVENT()
67 #endif
68 #ifndef TSCH_DEBUG_TX_EVENT
69 #define TSCH_DEBUG_TX_EVENT()
70 #endif
71 #ifndef TSCH_DEBUG_SLOT_START
72 #define TSCH_DEBUG_SLOT_START()
73 #endif
74 #ifndef TSCH_DEBUG_SLOT_END
75 #define TSCH_DEBUG_SLOT_END()
76 #endif
77 
78 /* Check if TSCH_MAX_INCOMING_PACKETS is power of two */
79 #if (TSCH_MAX_INCOMING_PACKETS & (TSCH_MAX_INCOMING_PACKETS - 1)) != 0
80 #error TSCH_MAX_INCOMING_PACKETS must be power of two
81 #endif
82 
83 /* Check if TSCH_DEQUEUED_ARRAY_SIZE is power of two and greater or equal to QUEUEBUF_NUM */
84 #if TSCH_DEQUEUED_ARRAY_SIZE < QUEUEBUF_NUM
85 #error TSCH_DEQUEUED_ARRAY_SIZE must be greater or equal to QUEUEBUF_NUM
86 #endif
87 #if (TSCH_DEQUEUED_ARRAY_SIZE & (TSCH_DEQUEUED_ARRAY_SIZE - 1)) != 0
88 #error TSCH_DEQUEUED_ARRAY_SIZE must be power of two
89 #endif
90 
91 /* Truncate received drift correction information to maximum half
92  * of the guard time (one fourth of TSCH_DEFAULT_TS_RX_WAIT) */
93 #define SYNC_IE_BOUND ((int32_t)US_TO_RTIMERTICKS(tsch_timing_us[tsch_ts_rx_wait] / 4))
94 
95 /* By default: check that rtimer runs at >=32kHz and use a guard time of 10us */
96 #if RTIMER_SECOND < (32 * 1024)
97 #error "TSCH: RTIMER_SECOND < (32 * 1024)"
98 #endif
99 #if CONTIKI_TARGET_COOJA
100 /* Use 0 usec guard time for Cooja Mote with a 1 MHz Rtimer*/
101 #define RTIMER_GUARD 0u
102 #elif RTIMER_SECOND >= 200000
103 #define RTIMER_GUARD (RTIMER_SECOND / 100000)
104 #else
105 #define RTIMER_GUARD 2u
106 #endif
107 
108 enum tsch_radio_state_on_cmd {
109  TSCH_RADIO_CMD_ON_START_OF_TIMESLOT,
110  TSCH_RADIO_CMD_ON_WITHIN_TIMESLOT,
111  TSCH_RADIO_CMD_ON_FORCE,
112 };
113 
114 enum tsch_radio_state_off_cmd {
115  TSCH_RADIO_CMD_OFF_END_OF_TIMESLOT,
116  TSCH_RADIO_CMD_OFF_WITHIN_TIMESLOT,
117  TSCH_RADIO_CMD_OFF_FORCE,
118 };
119 
120 /* A ringbuf storing outgoing packets after they were dequeued.
121  * Will be processed layer by tsch_tx_process_pending */
122 struct ringbufindex dequeued_ringbuf;
123 struct tsch_packet *dequeued_array[TSCH_DEQUEUED_ARRAY_SIZE];
124 /* A ringbuf storing incoming packets.
125  * Will be processed layer by tsch_rx_process_pending */
126 struct ringbufindex input_ringbuf;
127 struct input_packet input_array[TSCH_MAX_INCOMING_PACKETS];
128 
129 /* Last time we received Sync-IE (ACK or data packet from a time source) */
130 static struct tsch_asn_t last_sync_asn;
131 clock_time_t last_sync_time; /* Same info, in clock_time_t units */
132 
133 /* A global lock for manipulating data structures safely from outside of interrupt */
134 static volatile int tsch_locked = 0;
135 /* As long as this is set, skip all slot operation */
136 static volatile int tsch_lock_requested = 0;
137 
138 /* Last estimated drift in RTIMER ticks
139  * (Sky: 1 tick = 30.517578125 usec exactly) */
140 static int32_t drift_correction = 0;
141 /* Is drift correction used? (Can be true even if drift_correction == 0) */
142 static uint8_t is_drift_correction_used;
143 
144 /* The neighbor last used as our time source */
146 
147 /* Used from tsch_slot_operation and sub-protothreads */
148 static rtimer_clock_t volatile current_slot_start;
149 
150 /* Are we currently inside a slot? */
151 static volatile int tsch_in_slot_operation = 0;
152 
153 /* If we are inside a slot, this tells the current channel */
154 uint8_t tsch_current_channel;
155 
156 /* Info about the link, packet and neighbor of
157  * the current (or next) slot */
158 struct tsch_link *current_link = NULL;
159 /* A backup link with Rx flag, overlapping with current_link.
160  * If the current link is Tx-only and the Tx queue
161  * is empty while executing the link, fallback to the backup link. */
162 static struct tsch_link *backup_link = NULL;
163 static struct tsch_packet *current_packet = NULL;
164 static struct tsch_neighbor *current_neighbor = NULL;
165 
166 /* Indicates whether an extra link is needed to handle the current burst */
167 static int burst_link_scheduled = 0;
168 /* Counts the length of the current burst */
169 int tsch_current_burst_count = 0;
170 
171 /* Protothread for association */
172 PT_THREAD(tsch_scan(struct pt *pt));
173 /* Protothread for slot operation, called from rtimer interrupt
174  * and scheduled from tsch_schedule_slot_operation */
175 static PT_THREAD(tsch_slot_operation(struct rtimer *t, void *ptr));
176 static struct pt slot_operation_pt;
177 /* Sub-protothreads of tsch_slot_operation */
178 static PT_THREAD(tsch_tx_slot(struct pt *pt, struct rtimer *t));
179 static PT_THREAD(tsch_rx_slot(struct pt *pt, struct rtimer *t));
180 
181 /*---------------------------------------------------------------------------*/
182 /* TSCH locking system. TSCH is locked during slot operations */
183 
184 /* Is TSCH locked? */
185 int
187 {
188  return tsch_locked;
189 }
190 
191 /* Lock TSCH (no slot operation) */
192 int
194 {
195  if(!tsch_locked) {
196  rtimer_clock_t busy_wait_time;
197  int busy_wait = 0; /* Flag used for logging purposes */
198  /* Make sure no new slot operation will start */
199  tsch_lock_requested = 1;
200  /* Wait for the end of current slot operation. */
201  if(tsch_in_slot_operation) {
202  busy_wait = 1;
203  busy_wait_time = RTIMER_NOW();
204  while(tsch_in_slot_operation) {
206  }
207  busy_wait_time = RTIMER_NOW() - busy_wait_time;
208  }
209  if(!tsch_locked) {
210  /* Take the lock if it is free */
211  tsch_locked = 1;
212  tsch_lock_requested = 0;
213  if(busy_wait) {
214  /* Issue a log whenever we had to busy wait until getting the lock */
215  TSCH_LOG_ADD(tsch_log_message,
216  snprintf(log->message, sizeof(log->message),
217  "!get lock delay %u", (unsigned)busy_wait_time);
218  );
219  }
220  return 1;
221  }
222  }
223  TSCH_LOG_ADD(tsch_log_message,
224  snprintf(log->message, sizeof(log->message),
225  "!failed to lock");
226  );
227  return 0;
228 }
229 
230 /* Release TSCH lock */
231 void
233 {
234  tsch_locked = 0;
235 }
236 
237 /*---------------------------------------------------------------------------*/
238 /* Channel hopping utility functions */
239 
240 /* Return channel from ASN and channel offset */
241 uint8_t
242 tsch_calculate_channel(struct tsch_asn_t *asn, uint8_t channel_offset)
243 {
244  uint16_t index_of_0 = TSCH_ASN_MOD(*asn, tsch_hopping_sequence_length);
245  uint16_t index_of_offset = (index_of_0 + channel_offset) % tsch_hopping_sequence_length.val;
246  return tsch_hopping_sequence[index_of_offset];
247 }
248 
249 /*---------------------------------------------------------------------------*/
250 /* Timing utility functions */
251 
252 /* Checks if the current time has passed a ref time + offset. Assumes
253  * a single overflow and ref time prior to now. */
254 static uint8_t
255 check_timer_miss(rtimer_clock_t ref_time, rtimer_clock_t offset, rtimer_clock_t now)
256 {
257  rtimer_clock_t target = ref_time + offset;
258  int now_has_overflowed = now < ref_time;
259  int target_has_overflowed = target < ref_time;
260 
261  if(now_has_overflowed == target_has_overflowed) {
262  /* Both or none have overflowed, just compare now to the target */
263  return target <= now;
264  } else {
265  /* Either now or target of overflowed.
266  * If it is now, then it has passed the target.
267  * If it is target, then we haven't reached it yet.
268  * */
269  return now_has_overflowed;
270  }
271 }
272 /*---------------------------------------------------------------------------*/
273 /* Schedule a wakeup at a specified offset from a reference time.
274  * Provides basic protection against missed deadlines and timer overflows
275  * A return value of zero signals a missed deadline: no rtimer was scheduled. */
276 static uint8_t
277 tsch_schedule_slot_operation(struct rtimer *tm, rtimer_clock_t ref_time, rtimer_clock_t offset, const char *str)
278 {
279  rtimer_clock_t now = RTIMER_NOW();
280  int r;
281  /* Subtract RTIMER_GUARD before checking for deadline miss
282  * because we can not schedule rtimer less than RTIMER_GUARD in the future */
283  int missed = check_timer_miss(ref_time, offset - RTIMER_GUARD, now);
284 
285  if(missed) {
286  TSCH_LOG_ADD(tsch_log_message,
287  snprintf(log->message, sizeof(log->message),
288  "!dl-miss %s %d %d",
289  str, (int)(now-ref_time), (int)offset);
290  );
291  } else {
292  r = rtimer_set(tm, ref_time + offset, 1, (void (*)(struct rtimer *, void *))tsch_slot_operation, NULL);
293  if(r == RTIMER_OK) {
294  return 1;
295  }
296  }
297 
298  /* block until the time to schedule comes */
299  RTIMER_BUSYWAIT_UNTIL_ABS(0, ref_time, offset);
300  return 0;
301 }
302 /*---------------------------------------------------------------------------*/
303 /* Schedule slot operation conditionally, and YIELD if success only.
304  * Always attempt to schedule RTIMER_GUARD before the target to make sure to wake up
305  * ahead of time and then busy wait to exactly hit the target. */
306 #define TSCH_SCHEDULE_AND_YIELD(pt, tm, ref_time, offset, str) \
307  do { \
308  if(tsch_schedule_slot_operation(tm, ref_time, offset - RTIMER_GUARD, str)) { \
309  PT_YIELD(pt); \
310  RTIMER_BUSYWAIT_UNTIL_ABS(0, ref_time, offset); \
311  } \
312  } while(0);
313 /*---------------------------------------------------------------------------*/
314 /* Get EB, broadcast or unicast packet to be sent, and target neighbor. */
315 static struct tsch_packet *
316 get_packet_and_neighbor_for_link(struct tsch_link *link, struct tsch_neighbor **target_neighbor)
317 {
318  struct tsch_packet *p = NULL;
319  struct tsch_neighbor *n = NULL;
320 
321  /* Is this a Tx link? */
322  if(link->link_options & LINK_OPTION_TX) {
323  /* is it for advertisement of EB? */
324  if(link->link_type == LINK_TYPE_ADVERTISING || link->link_type == LINK_TYPE_ADVERTISING_ONLY) {
325  /* fetch EB packets */
326  n = n_eb;
327  p = tsch_queue_get_packet_for_nbr(n, link);
328  }
329  if(link->link_type != LINK_TYPE_ADVERTISING_ONLY) {
330  /* NORMAL link or no EB to send, pick a data packet */
331  if(p == NULL) {
332  /* Get neighbor queue associated to the link and get packet from it */
333  n = tsch_queue_get_nbr(&link->addr);
334  p = tsch_queue_get_packet_for_nbr(n, link);
335  /* if it is a broadcast slot and there were no broadcast packets, pick any unicast packet */
336  if(p == NULL && n == n_broadcast) {
338  }
339  }
340  }
341  }
342  /* return nbr (by reference) */
343  if(target_neighbor != NULL) {
344  *target_neighbor = n;
345  }
346 
347  return p;
348 }
349 /*---------------------------------------------------------------------------*/
350 /**
351  * This function turns on the radio. Its semantics is dependent on
352  * the value of TSCH_RADIO_ON_DURING_TIMESLOT constant:
353  * - if enabled, the radio is turned on at the start of the slot
354  * - if disabled, the radio is turned on within the slot,
355  * directly before the packet Rx guard time and ACK Rx guard time.
356  */
357 static void
358 tsch_radio_on(enum tsch_radio_state_on_cmd command)
359 {
360  int do_it = 0;
361  switch(command) {
362  case TSCH_RADIO_CMD_ON_START_OF_TIMESLOT:
363  if(TSCH_RADIO_ON_DURING_TIMESLOT) {
364  do_it = 1;
365  }
366  break;
367  case TSCH_RADIO_CMD_ON_WITHIN_TIMESLOT:
368  if(!TSCH_RADIO_ON_DURING_TIMESLOT) {
369  do_it = 1;
370  }
371  break;
372  case TSCH_RADIO_CMD_ON_FORCE:
373  do_it = 1;
374  break;
375  }
376  if(do_it) {
377  NETSTACK_RADIO.on();
378  }
379 }
380 /*---------------------------------------------------------------------------*/
381 /**
382  * This function turns off the radio. In the same way as for tsch_radio_on(),
383  * it depends on the value of TSCH_RADIO_ON_DURING_TIMESLOT constant:
384  * - if enabled, the radio is turned off at the end of the slot
385  * - if disabled, the radio is turned off within the slot,
386  * directly after Tx'ing or Rx'ing a packet or Tx'ing an ACK.
387  */
388 static void
389 tsch_radio_off(enum tsch_radio_state_off_cmd command)
390 {
391  int do_it = 0;
392  switch(command) {
393  case TSCH_RADIO_CMD_OFF_END_OF_TIMESLOT:
394  if(TSCH_RADIO_ON_DURING_TIMESLOT) {
395  do_it = 1;
396  }
397  break;
398  case TSCH_RADIO_CMD_OFF_WITHIN_TIMESLOT:
399  if(!TSCH_RADIO_ON_DURING_TIMESLOT) {
400  do_it = 1;
401  }
402  break;
403  case TSCH_RADIO_CMD_OFF_FORCE:
404  do_it = 1;
405  break;
406  }
407  if(do_it) {
408  NETSTACK_RADIO.off();
409  }
410 }
411 /*---------------------------------------------------------------------------*/
412 static
413 PT_THREAD(tsch_tx_slot(struct pt *pt, struct rtimer *t))
414 {
415  /**
416  * TX slot:
417  * 1. Copy packet to radio buffer
418  * 2. Perform CCA if enabled
419  * 3. Sleep until it is time to transmit
420  * 4. Wait for ACK if it is a unicast packet
421  * 5. Extract drift if we received an E-ACK from a time source neighbor
422  * 6. Update CSMA parameters according to TX status
423  * 7. Schedule mac_call_sent_callback
424  **/
425 
426  /* tx status */
427  static uint8_t mac_tx_status;
428  /* is the packet in its neighbor's queue? */
429  uint8_t in_queue;
430  static int dequeued_index;
431  static int packet_ready = 1;
432 
433  PT_BEGIN(pt);
434 
435  TSCH_DEBUG_TX_EVENT();
436 
437  /* First check if we have space to store a newly dequeued packet (in case of
438  * successful Tx or Drop) */
439  dequeued_index = ringbufindex_peek_put(&dequeued_ringbuf);
440  if(dequeued_index != -1) {
441  if(current_packet == NULL || current_packet->qb == NULL) {
442  mac_tx_status = MAC_TX_ERR_FATAL;
443  } else {
444  /* packet payload */
445  static void *packet;
446 #if LLSEC802154_ENABLED
447  /* encrypted payload */
448  static uint8_t encrypted_packet[TSCH_PACKET_MAX_LEN];
449 #endif /* LLSEC802154_ENABLED */
450  /* packet payload length */
451  static uint8_t packet_len;
452  /* packet seqno */
453  static uint8_t seqno;
454  /* is this a broadcast packet? (wait for ack?) */
455  static uint8_t is_broadcast;
456  static rtimer_clock_t tx_start_time;
457  /* Did we set the frame pending bit to request an extra burst link? */
458  static int burst_link_requested;
459 
460 #if TSCH_CCA_ENABLED
461  static uint8_t cca_status;
462 #endif /* TSCH_CCA_ENABLED */
463 
464  /* get payload */
465  packet = queuebuf_dataptr(current_packet->qb);
466  packet_len = queuebuf_datalen(current_packet->qb);
467  /* is this a broadcast packet? (wait for ack?) */
468  is_broadcast = current_neighbor->is_broadcast;
469  /* Unicast. More packets in queue for the neighbor? */
470  burst_link_requested = 0;
471  if(!is_broadcast
472  && tsch_current_burst_count + 1 < TSCH_BURST_MAX_LEN
473  && tsch_queue_packet_count(&current_neighbor->addr) > 1) {
474  burst_link_requested = 1;
475  tsch_packet_set_frame_pending(packet, packet_len);
476  }
477  /* read seqno from payload */
478  seqno = ((uint8_t *)(packet))[2];
479  /* if this is an EB, then update its Sync-IE */
480  if(current_neighbor == n_eb) {
481  packet_ready = tsch_packet_update_eb(packet, packet_len, current_packet->tsch_sync_ie_offset);
482  } else {
483  packet_ready = 1;
484  }
485 
486 #if LLSEC802154_ENABLED
487  if(tsch_is_pan_secured) {
488  /* If we are going to encrypt, we need to generate the output in a separate buffer and keep
489  * the original untouched. This is to allow for future retransmissions. */
490  int with_encryption = queuebuf_attr(current_packet->qb, PACKETBUF_ATTR_SECURITY_LEVEL) & 0x4;
491  packet_len += tsch_security_secure_frame(packet, with_encryption ? encrypted_packet : packet, current_packet->header_len,
492  packet_len - current_packet->header_len, &tsch_current_asn);
493  if(with_encryption) {
494  packet = encrypted_packet;
495  }
496  }
497 #endif /* LLSEC802154_ENABLED */
498 
499  /* prepare packet to send: copy to radio buffer */
500  if(packet_ready && NETSTACK_RADIO.prepare(packet, packet_len) == 0) { /* 0 means success */
501  static rtimer_clock_t tx_duration;
502 
503 #if TSCH_CCA_ENABLED
504  cca_status = 1;
505  /* delay before CCA */
506  TSCH_SCHEDULE_AND_YIELD(pt, t, current_slot_start, tsch_timing[tsch_ts_cca_offset], "cca");
507  TSCH_DEBUG_TX_EVENT();
508  tsch_radio_on(TSCH_RADIO_CMD_ON_WITHIN_TIMESLOT);
509  /* CCA */
510  RTIMER_BUSYWAIT_UNTIL_ABS(!(cca_status &= NETSTACK_RADIO.channel_clear()),
511  current_slot_start, tsch_timing[tsch_ts_cca_offset] + tsch_timing[tsch_ts_cca]);
512  TSCH_DEBUG_TX_EVENT();
513  /* there is not enough time to turn radio off */
514  /* NETSTACK_RADIO.off(); */
515  if(cca_status == 0) {
516  mac_tx_status = MAC_TX_COLLISION;
517  } else
518 #endif /* TSCH_CCA_ENABLED */
519  {
520  /* delay before TX */
521  TSCH_SCHEDULE_AND_YIELD(pt, t, current_slot_start, tsch_timing[tsch_ts_tx_offset] - RADIO_DELAY_BEFORE_TX, "TxBeforeTx");
522  TSCH_DEBUG_TX_EVENT();
523  /* send packet already in radio tx buffer */
524  mac_tx_status = NETSTACK_RADIO.transmit(packet_len);
525  tx_count++;
526  /* Save tx timestamp */
527  tx_start_time = current_slot_start + tsch_timing[tsch_ts_tx_offset];
528  /* calculate TX duration based on sent packet len */
529  tx_duration = TSCH_PACKET_DURATION(packet_len);
530  /* limit tx_time to its max value */
531  tx_duration = MIN(tx_duration, tsch_timing[tsch_ts_max_tx]);
532  /* turn tadio off -- will turn on again to wait for ACK if needed */
533  tsch_radio_off(TSCH_RADIO_CMD_OFF_WITHIN_TIMESLOT);
534 
535  if(mac_tx_status == RADIO_TX_OK) {
536  if(!is_broadcast) {
537  uint8_t ackbuf[TSCH_PACKET_MAX_LEN];
538  int ack_len;
539  rtimer_clock_t ack_start_time;
540  int is_time_source;
541  struct ieee802154_ies ack_ies;
542  uint8_t ack_hdrlen;
543  frame802154_t frame;
544 
545 #if TSCH_HW_FRAME_FILTERING
546  radio_value_t radio_rx_mode;
547  /* Entering promiscuous mode so that the radio accepts the enhanced ACK */
548  NETSTACK_RADIO.get_value(RADIO_PARAM_RX_MODE, &radio_rx_mode);
549  NETSTACK_RADIO.set_value(RADIO_PARAM_RX_MODE, radio_rx_mode & (~RADIO_RX_MODE_ADDRESS_FILTER));
550 #endif /* TSCH_HW_FRAME_FILTERING */
551  /* Unicast: wait for ack after tx: sleep until ack time */
552  TSCH_SCHEDULE_AND_YIELD(pt, t, current_slot_start,
553  tsch_timing[tsch_ts_tx_offset] + tx_duration + tsch_timing[tsch_ts_rx_ack_delay] - RADIO_DELAY_BEFORE_RX, "TxBeforeAck");
554  TSCH_DEBUG_TX_EVENT();
555  tsch_radio_on(TSCH_RADIO_CMD_ON_WITHIN_TIMESLOT);
556  /* Wait for ACK to come */
557  RTIMER_BUSYWAIT_UNTIL_ABS(NETSTACK_RADIO.receiving_packet(),
558  tx_start_time, tx_duration + tsch_timing[tsch_ts_rx_ack_delay] + tsch_timing[tsch_ts_ack_wait] + RADIO_DELAY_BEFORE_DETECT);
559  TSCH_DEBUG_TX_EVENT();
560 
561  ack_start_time = RTIMER_NOW() - RADIO_DELAY_BEFORE_DETECT;
562 
563  /* Wait for ACK to finish */
564  RTIMER_BUSYWAIT_UNTIL_ABS(!NETSTACK_RADIO.receiving_packet(),
565  ack_start_time, tsch_timing[tsch_ts_max_ack]);
566  TSCH_DEBUG_TX_EVENT();
567  tsch_radio_off(TSCH_RADIO_CMD_OFF_WITHIN_TIMESLOT);
568 
569 #if TSCH_HW_FRAME_FILTERING
570  /* Leaving promiscuous mode */
571  NETSTACK_RADIO.get_value(RADIO_PARAM_RX_MODE, &radio_rx_mode);
572  NETSTACK_RADIO.set_value(RADIO_PARAM_RX_MODE, radio_rx_mode | RADIO_RX_MODE_ADDRESS_FILTER);
573 #endif /* TSCH_HW_FRAME_FILTERING */
574 
575  /* Read ack frame */
576  ack_len = NETSTACK_RADIO.read((void *)ackbuf, sizeof(ackbuf));
577 
578  is_time_source = 0;
579  /* The radio driver should return 0 if no valid packets are in the rx buffer */
580  if(ack_len > 0) {
581  is_time_source = current_neighbor != NULL && current_neighbor->is_time_source;
582  if(tsch_packet_parse_eack(ackbuf, ack_len, seqno,
583  &frame, &ack_ies, &ack_hdrlen) == 0) {
584  ack_len = 0;
585  }
586 
587 #if LLSEC802154_ENABLED
588  if(ack_len != 0) {
589  if(!tsch_security_parse_frame(ackbuf, ack_hdrlen, ack_len - ack_hdrlen - tsch_security_mic_len(&frame),
590  &frame, &current_neighbor->addr, &tsch_current_asn)) {
591  TSCH_LOG_ADD(tsch_log_message,
592  snprintf(log->message, sizeof(log->message),
593  "!failed to authenticate ACK"));
594  ack_len = 0;
595  }
596  } else {
597  TSCH_LOG_ADD(tsch_log_message,
598  snprintf(log->message, sizeof(log->message),
599  "!failed to parse ACK"));
600  }
601 #endif /* LLSEC802154_ENABLED */
602  }
603 
604  if(ack_len != 0) {
605  if(is_time_source) {
606  int32_t eack_time_correction = US_TO_RTIMERTICKS(ack_ies.ie_time_correction);
607  int32_t since_last_timesync = TSCH_ASN_DIFF(tsch_current_asn, last_sync_asn);
608  if(eack_time_correction > SYNC_IE_BOUND) {
609  drift_correction = SYNC_IE_BOUND;
610  } else if(eack_time_correction < -SYNC_IE_BOUND) {
611  drift_correction = -SYNC_IE_BOUND;
612  } else {
613  drift_correction = eack_time_correction;
614  }
615  if(drift_correction != eack_time_correction) {
616  TSCH_LOG_ADD(tsch_log_message,
617  snprintf(log->message, sizeof(log->message),
618  "!truncated dr %d %d", (int)eack_time_correction, (int)drift_correction);
619  );
620  }
621  tsch_stats_on_time_synchronization(eack_time_correction);
622  is_drift_correction_used = 1;
623  tsch_timesync_update(current_neighbor, since_last_timesync, drift_correction);
624  /* Keep track of sync time */
625  last_sync_asn = tsch_current_asn;
626  last_sync_time = clock_time();
628  }
629  mac_tx_status = MAC_TX_OK;
630 
631  /* We requested an extra slot and got an ack. This means
632  the extra slot will be scheduled at the received */
633  if(burst_link_requested) {
634  burst_link_scheduled = 1;
635  }
636  } else {
637  mac_tx_status = MAC_TX_NOACK;
638  }
639  } else {
640  mac_tx_status = MAC_TX_OK;
641  }
642  } else {
643  mac_tx_status = MAC_TX_ERR;
644  }
645  }
646  } else {
647  mac_tx_status = MAC_TX_ERR;
648  }
649  }
650 
651  tsch_radio_off(TSCH_RADIO_CMD_OFF_END_OF_TIMESLOT);
652 
653  current_packet->transmissions++;
654  current_packet->ret = mac_tx_status;
655 
656  /* Post TX: Update neighbor queue state */
657  in_queue = tsch_queue_packet_sent(current_neighbor, current_packet, current_link, mac_tx_status);
658 
659  /* The packet was dequeued, add it to dequeued_ringbuf for later processing */
660  if(in_queue == 0) {
661  dequeued_array[dequeued_index] = current_packet;
662  ringbufindex_put(&dequeued_ringbuf);
663  }
664 
665  /* If this is an unicast packet to timesource, update stats */
666  if(current_neighbor != NULL && current_neighbor->is_time_source) {
667  tsch_stats_tx_packet(current_neighbor, mac_tx_status, tsch_current_channel);
668  }
669 
670  /* Log every tx attempt */
671  TSCH_LOG_ADD(tsch_log_tx,
672  log->tx.mac_tx_status = mac_tx_status;
673  log->tx.num_tx = current_packet->transmissions;
674  log->tx.datalen = queuebuf_datalen(current_packet->qb);
675  log->tx.drift = drift_correction;
676  log->tx.drift_used = is_drift_correction_used;
677  log->tx.is_data = ((((uint8_t *)(queuebuf_dataptr(current_packet->qb)))[0]) & 7) == FRAME802154_DATAFRAME;
678 #if LLSEC802154_ENABLED
679  log->tx.sec_level = queuebuf_attr(current_packet->qb, PACKETBUF_ATTR_SECURITY_LEVEL);
680 #else /* LLSEC802154_ENABLED */
681  log->tx.sec_level = 0;
682 #endif /* LLSEC802154_ENABLED */
683  linkaddr_copy(&log->tx.dest, queuebuf_addr(current_packet->qb, PACKETBUF_ADDR_RECEIVER));
684  log->tx.seqno = queuebuf_attr(current_packet->qb, PACKETBUF_ATTR_MAC_SEQNO);
685  );
686 
687  /* Poll process for later processing of packet sent events and logs */
688  process_poll(&tsch_pending_events_process);
689  }
690 
691  TSCH_DEBUG_TX_EVENT();
692 
693  PT_END(pt);
694 }
695 /*---------------------------------------------------------------------------*/
696 static
697 PT_THREAD(tsch_rx_slot(struct pt *pt, struct rtimer *t))
698 {
699  /**
700  * RX slot:
701  * 1. Check if it is used for TIME_KEEPING
702  * 2. Sleep and wake up just before expected RX time (with a guard time: TS_LONG_GT)
703  * 3. Check for radio activity for the guard time: TS_LONG_GT
704  * 4. Prepare and send ACK if needed
705  * 5. Drift calculated in the ACK callback registered with the radio driver. Use it if receiving from a time source neighbor.
706  **/
707 
708  struct tsch_neighbor *n;
709  static linkaddr_t source_address;
710  static linkaddr_t destination_address;
711  static int16_t input_index;
712  static int input_queue_drop = 0;
713 
714  PT_BEGIN(pt);
715 
716  TSCH_DEBUG_RX_EVENT();
717 
718  input_index = ringbufindex_peek_put(&input_ringbuf);
719  if(input_index == -1) {
720  input_queue_drop++;
721  } else {
722  static struct input_packet *current_input;
723  /* Estimated drift based on RX time */
724  static int32_t estimated_drift;
725  /* Rx timestamps */
726  static rtimer_clock_t rx_start_time;
727  static rtimer_clock_t expected_rx_time;
728  static rtimer_clock_t packet_duration;
729  uint8_t packet_seen;
730 
731  expected_rx_time = current_slot_start + tsch_timing[tsch_ts_tx_offset];
732  /* Default start time: expected Rx time */
733  rx_start_time = expected_rx_time;
734 
735  current_input = &input_array[input_index];
736 
737  /* Wait before starting to listen */
738  TSCH_SCHEDULE_AND_YIELD(pt, t, current_slot_start, tsch_timing[tsch_ts_rx_offset] - RADIO_DELAY_BEFORE_RX, "RxBeforeListen");
739  TSCH_DEBUG_RX_EVENT();
740 
741  /* Start radio for at least guard time */
742  tsch_radio_on(TSCH_RADIO_CMD_ON_WITHIN_TIMESLOT);
743  packet_seen = NETSTACK_RADIO.receiving_packet() || NETSTACK_RADIO.pending_packet();
744  if(!packet_seen) {
745  /* Check if receiving within guard time */
746  RTIMER_BUSYWAIT_UNTIL_ABS((packet_seen = NETSTACK_RADIO.receiving_packet()),
747  current_slot_start, tsch_timing[tsch_ts_rx_offset] + tsch_timing[tsch_ts_rx_wait] + RADIO_DELAY_BEFORE_DETECT);
748  }
749  if(!packet_seen) {
750  /* no packets on air */
751  tsch_radio_off(TSCH_RADIO_CMD_OFF_FORCE);
752  } else {
753  TSCH_DEBUG_RX_EVENT();
754  /* Save packet timestamp */
755  rx_start_time = RTIMER_NOW() - RADIO_DELAY_BEFORE_DETECT;
756 
757  /* Wait until packet is received, turn radio off */
758  RTIMER_BUSYWAIT_UNTIL_ABS(!NETSTACK_RADIO.receiving_packet(),
759  current_slot_start, tsch_timing[tsch_ts_rx_offset] + tsch_timing[tsch_ts_rx_wait] + tsch_timing[tsch_ts_max_tx]);
760  TSCH_DEBUG_RX_EVENT();
761  tsch_radio_off(TSCH_RADIO_CMD_OFF_WITHIN_TIMESLOT);
762 
763  if(NETSTACK_RADIO.pending_packet()) {
764  static int frame_valid;
765  static int header_len;
766  static frame802154_t frame;
767  radio_value_t radio_last_rssi;
768  radio_value_t radio_last_lqi;
769 
770  /* Read packet */
771  current_input->len = NETSTACK_RADIO.read((void *)current_input->payload, TSCH_PACKET_MAX_LEN);
772  NETSTACK_RADIO.get_value(RADIO_PARAM_LAST_RSSI, &radio_last_rssi);
773  current_input->rx_asn = tsch_current_asn;
774  current_input->rssi = (signed)radio_last_rssi;
775  current_input->channel = tsch_current_channel;
776  header_len = frame802154_parse((uint8_t *)current_input->payload, current_input->len, &frame);
777  frame_valid = header_len > 0 &&
778  frame802154_check_dest_panid(&frame) &&
779  frame802154_extract_linkaddr(&frame, &source_address, &destination_address);
780 
781 #if TSCH_RESYNC_WITH_SFD_TIMESTAMPS
782  /* At the end of the reception, get an more accurate estimate of SFD arrival time */
783  NETSTACK_RADIO.get_object(RADIO_PARAM_LAST_PACKET_TIMESTAMP, &rx_start_time, sizeof(rtimer_clock_t));
784 #endif
785 
786  packet_duration = TSCH_PACKET_DURATION(current_input->len);
787  /* limit packet_duration to its max value */
788  packet_duration = MIN(packet_duration, tsch_timing[tsch_ts_max_tx]);
789 
790  if(!frame_valid) {
791  TSCH_LOG_ADD(tsch_log_message,
792  snprintf(log->message, sizeof(log->message),
793  "!failed to parse frame %u %u", header_len, current_input->len));
794  }
795 
796  if(frame_valid) {
797  if(frame.fcf.frame_type != FRAME802154_DATAFRAME
798  && frame.fcf.frame_type != FRAME802154_BEACONFRAME) {
799  TSCH_LOG_ADD(tsch_log_message,
800  snprintf(log->message, sizeof(log->message),
801  "!discarding frame with type %u, len %u", frame.fcf.frame_type, current_input->len));
802  frame_valid = 0;
803  }
804  }
805 
806 #if LLSEC802154_ENABLED
807  /* Decrypt and verify incoming frame */
808  if(frame_valid) {
810  current_input->payload, header_len, current_input->len - header_len - tsch_security_mic_len(&frame),
811  &frame, &source_address, &tsch_current_asn)) {
812  current_input->len -= tsch_security_mic_len(&frame);
813  } else {
814  TSCH_LOG_ADD(tsch_log_message,
815  snprintf(log->message, sizeof(log->message),
816  "!failed to authenticate frame %u", current_input->len));
817  frame_valid = 0;
818  }
819  }
820 #endif /* LLSEC802154_ENABLED */
821 
822  if(frame_valid) {
823  if(linkaddr_cmp(&destination_address, &linkaddr_node_addr)
824  || linkaddr_cmp(&destination_address, &linkaddr_null)) {
825  int do_nack = 0;
826  rx_count++;
827  estimated_drift = RTIMER_CLOCK_DIFF(expected_rx_time, rx_start_time);
828  tsch_stats_on_time_synchronization(estimated_drift);
829 
830 #if TSCH_TIMESYNC_REMOVE_JITTER
831  /* remove jitter due to measurement errors */
832  if(ABS(estimated_drift) <= TSCH_TIMESYNC_MEASUREMENT_ERROR) {
833  estimated_drift = 0;
834  } else if(estimated_drift > 0) {
835  estimated_drift -= TSCH_TIMESYNC_MEASUREMENT_ERROR;
836  } else {
837  estimated_drift += TSCH_TIMESYNC_MEASUREMENT_ERROR;
838  }
839 #endif
840 
841 #ifdef TSCH_CALLBACK_DO_NACK
842  if(frame.fcf.ack_required) {
843  do_nack = TSCH_CALLBACK_DO_NACK(current_link,
844  &source_address, &destination_address);
845  }
846 #endif
847 
848  if(frame.fcf.ack_required) {
849  static uint8_t ack_buf[TSCH_PACKET_MAX_LEN];
850  static int ack_len;
851 
852  /* Build ACK frame */
853  ack_len = tsch_packet_create_eack(ack_buf, sizeof(ack_buf),
854  &source_address, frame.seq, (int16_t)RTIMERTICKS_TO_US(estimated_drift), do_nack);
855 
856  if(ack_len > 0) {
857 #if LLSEC802154_ENABLED
858  if(tsch_is_pan_secured) {
859  /* Secure ACK frame. There is only header and header IEs, therefore data len == 0. */
860  ack_len += tsch_security_secure_frame(ack_buf, ack_buf, ack_len, 0, &tsch_current_asn);
861  }
862 #endif /* LLSEC802154_ENABLED */
863 
864  /* Copy to radio buffer */
865  NETSTACK_RADIO.prepare((const void *)ack_buf, ack_len);
866 
867  /* Wait for time to ACK and transmit ACK */
868  TSCH_SCHEDULE_AND_YIELD(pt, t, rx_start_time,
869  packet_duration + tsch_timing[tsch_ts_tx_ack_delay] - RADIO_DELAY_BEFORE_TX, "RxBeforeAck");
870  TSCH_DEBUG_RX_EVENT();
871  NETSTACK_RADIO.transmit(ack_len);
872  tsch_radio_off(TSCH_RADIO_CMD_OFF_WITHIN_TIMESLOT);
873 
874  /* Schedule a burst link iff the frame pending bit was set */
875  burst_link_scheduled = tsch_packet_get_frame_pending(current_input->payload, current_input->len);
876  }
877  }
878 
879  /* If the sender is a time source, proceed to clock drift compensation */
880  n = tsch_queue_get_nbr(&source_address);
881  if(n != NULL && n->is_time_source) {
882  int32_t since_last_timesync = TSCH_ASN_DIFF(tsch_current_asn, last_sync_asn);
883  /* Keep track of last sync time */
884  last_sync_asn = tsch_current_asn;
885  last_sync_time = clock_time();
886  /* Save estimated drift */
887  drift_correction = -estimated_drift;
888  is_drift_correction_used = 1;
889  sync_count++;
890  tsch_timesync_update(n, since_last_timesync, -estimated_drift);
892  }
893 
894  /* Add current input to ringbuf */
895  ringbufindex_put(&input_ringbuf);
896 
897  /* If the neighbor is known, update its stats */
898  if(n != NULL) {
899  NETSTACK_RADIO.get_value(RADIO_PARAM_LAST_LINK_QUALITY, &radio_last_lqi);
900  tsch_stats_rx_packet(n, current_input->rssi, radio_last_lqi, tsch_current_channel);
901  }
902 
903  /* Log every reception */
904  TSCH_LOG_ADD(tsch_log_rx,
905  linkaddr_copy(&log->rx.src, (linkaddr_t *)&frame.src_addr);
906  log->rx.is_unicast = frame.fcf.ack_required;
907  log->rx.datalen = current_input->len;
908  log->rx.drift = drift_correction;
909  log->rx.drift_used = is_drift_correction_used;
910  log->rx.is_data = frame.fcf.frame_type == FRAME802154_DATAFRAME;
911  log->rx.sec_level = frame.aux_hdr.security_control.security_level;
912  log->rx.estimated_drift = estimated_drift;
913  log->rx.seqno = frame.seq;
914  );
915  }
916 
917  /* Poll process for processing of pending input and logs */
918  process_poll(&tsch_pending_events_process);
919  }
920  }
921 
922  tsch_radio_off(TSCH_RADIO_CMD_OFF_END_OF_TIMESLOT);
923  }
924 
925  if(input_queue_drop != 0) {
926  TSCH_LOG_ADD(tsch_log_message,
927  snprintf(log->message, sizeof(log->message),
928  "!queue full skipped %u", input_queue_drop);
929  );
930  input_queue_drop = 0;
931  }
932  }
933 
934  TSCH_DEBUG_RX_EVENT();
935 
936  PT_END(pt);
937 }
938 /*---------------------------------------------------------------------------*/
939 /* Protothread for slot operation, called from rtimer interrupt
940  * and scheduled from tsch_schedule_slot_operation */
941 static
942 PT_THREAD(tsch_slot_operation(struct rtimer *t, void *ptr))
943 {
944  TSCH_DEBUG_INTERRUPT();
945  PT_BEGIN(&slot_operation_pt);
946 
947  /* Loop over all active slots */
948  while(tsch_is_associated) {
949 
950  if(current_link == NULL || tsch_lock_requested) { /* Skip slot operation if there is no link
951  or if there is a pending request for getting the lock */
952  /* Issue a log whenever skipping a slot */
953  TSCH_LOG_ADD(tsch_log_message,
954  snprintf(log->message, sizeof(log->message),
955  "!skipped slot %u %u %u",
956  tsch_locked,
957  tsch_lock_requested,
958  current_link == NULL);
959  );
960 
961  } else {
962  int is_active_slot;
963  TSCH_DEBUG_SLOT_START();
964  tsch_in_slot_operation = 1;
965  /* Measure on-air noise level while TSCH is idle */
966  tsch_stats_sample_rssi();
967  /* Reset drift correction */
968  drift_correction = 0;
969  is_drift_correction_used = 0;
970  /* Get a packet ready to be sent */
971  current_packet = get_packet_and_neighbor_for_link(current_link, &current_neighbor);
972  /* There is no packet to send, and this link does not have Rx flag. Instead of doing
973  * nothing, switch to the backup link (has Rx flag) if any. */
974  if(current_packet == NULL && !(current_link->link_options & LINK_OPTION_RX) && backup_link != NULL) {
975  current_link = backup_link;
976  current_packet = get_packet_and_neighbor_for_link(current_link, &current_neighbor);
977  }
978  is_active_slot = current_packet != NULL || (current_link->link_options & LINK_OPTION_RX);
979  if(is_active_slot) {
980  /* If we are in a burst, we stick to current channel instead of
981  * doing channel hopping, as per IEEE 802.15.4-2015 */
982  if(burst_link_scheduled) {
983  /* Reset burst_link_scheduled flag. Will be set again if burst continue. */
984  burst_link_scheduled = 0;
985  } else {
986  /* Hop channel */
987  tsch_current_channel = tsch_calculate_channel(&tsch_current_asn, current_link->channel_offset);
988  }
989  NETSTACK_RADIO.set_value(RADIO_PARAM_CHANNEL, tsch_current_channel);
990  /* Turn the radio on already here if configured so; necessary for radios with slow startup */
991  tsch_radio_on(TSCH_RADIO_CMD_ON_START_OF_TIMESLOT);
992  /* Decide whether it is a TX/RX/IDLE or OFF slot */
993  /* Actual slot operation */
994  if(current_packet != NULL) {
995  /* We have something to transmit, do the following:
996  * 1. send
997  * 2. update_backoff_state(current_neighbor)
998  * 3. post tx callback
999  **/
1000  static struct pt slot_tx_pt;
1001  PT_SPAWN(&slot_operation_pt, &slot_tx_pt, tsch_tx_slot(&slot_tx_pt, t));
1002  } else {
1003  /* Listen */
1004  static struct pt slot_rx_pt;
1005  PT_SPAWN(&slot_operation_pt, &slot_rx_pt, tsch_rx_slot(&slot_rx_pt, t));
1006  }
1007  } else {
1008  /* Make sure to end the burst in cast, for some reason, we were
1009  * in a burst but now without any more packet to send. */
1010  burst_link_scheduled = 0;
1011  }
1012  TSCH_DEBUG_SLOT_END();
1013  }
1014 
1015  /* End of slot operation, schedule next slot or resynchronize */
1016 
1017  /* Do we need to resynchronize? i.e., wait for EB again */
1018  if(!tsch_is_coordinator && (TSCH_ASN_DIFF(tsch_current_asn, last_sync_asn) >
1019  (100 * TSCH_CLOCK_TO_SLOTS(TSCH_DESYNC_THRESHOLD / 100, tsch_timing[tsch_ts_timeslot_length])))) {
1020  TSCH_LOG_ADD(tsch_log_message,
1021  snprintf(log->message, sizeof(log->message),
1022  "! leaving the network, last sync %u",
1023  (unsigned)TSCH_ASN_DIFF(tsch_current_asn, last_sync_asn));
1024  );
1025  last_timesource_neighbor = NULL;
1027  } else {
1028  /* backup of drift correction for printing debug messages */
1029  /* int32_t drift_correction_backup = drift_correction; */
1030  uint16_t timeslot_diff = 0;
1031  rtimer_clock_t prev_slot_start;
1032  /* Time to next wake up */
1033  rtimer_clock_t time_to_next_active_slot;
1034  /* Schedule next wakeup skipping slots if missed deadline */
1035  do {
1036  if(current_link != NULL
1037  && current_link->link_options & LINK_OPTION_TX
1038  && current_link->link_options & LINK_OPTION_SHARED) {
1039  /* Decrement the backoff window for all neighbors able to transmit over
1040  * this Tx, Shared link. */
1041  tsch_queue_update_all_backoff_windows(&current_link->addr);
1042  }
1043 
1044  /* A burst link was scheduled. Replay the current link at the
1045  next time offset */
1046  if(burst_link_scheduled) {
1047  timeslot_diff = 1;
1048  backup_link = NULL;
1049  /* Keep track of the number of repetitions */
1050  tsch_current_burst_count++;
1051  } else {
1052  /* Get next active link */
1053  current_link = tsch_schedule_get_next_active_link(&tsch_current_asn, &timeslot_diff, &backup_link);
1054  if(current_link == NULL) {
1055  /* There is no next link. Fall back to default
1056  * behavior: wake up at the next slot. */
1057  timeslot_diff = 1;
1058  } else {
1059  /* Reset burst index now that the link was scheduled from
1060  normal schedule (as opposed to from ongoing burst) */
1061  tsch_current_burst_count = 0;
1062  }
1063  }
1064 
1065  /* Update ASN */
1066  TSCH_ASN_INC(tsch_current_asn, timeslot_diff);
1067  /* Time to next wake up */
1068  time_to_next_active_slot = timeslot_diff * tsch_timing[tsch_ts_timeslot_length] + drift_correction;
1069  time_to_next_active_slot += tsch_timesync_adaptive_compensate(time_to_next_active_slot);
1070  drift_correction = 0;
1071  is_drift_correction_used = 0;
1072  /* Update current slot start */
1073  prev_slot_start = current_slot_start;
1074  current_slot_start += time_to_next_active_slot;
1075  } while(!tsch_schedule_slot_operation(t, prev_slot_start, time_to_next_active_slot, "main"));
1076  }
1077 
1078  tsch_in_slot_operation = 0;
1079  PT_YIELD(&slot_operation_pt);
1080  }
1081 
1082  PT_END(&slot_operation_pt);
1083 }
1084 /*---------------------------------------------------------------------------*/
1085 /* Set global time before starting slot operation,
1086  * with a rtimer time and an ASN */
1087 void
1089 {
1090  static struct rtimer slot_operation_timer;
1091  rtimer_clock_t time_to_next_active_slot;
1092  rtimer_clock_t prev_slot_start;
1093  TSCH_DEBUG_INIT();
1094  do {
1095  uint16_t timeslot_diff;
1096  /* Get next active link */
1097  current_link = tsch_schedule_get_next_active_link(&tsch_current_asn, &timeslot_diff, &backup_link);
1098  if(current_link == NULL) {
1099  /* There is no next link. Fall back to default
1100  * behavior: wake up at the next slot. */
1101  timeslot_diff = 1;
1102  }
1103  /* Update ASN */
1104  TSCH_ASN_INC(tsch_current_asn, timeslot_diff);
1105  /* Time to next wake up */
1106  time_to_next_active_slot = timeslot_diff * tsch_timing[tsch_ts_timeslot_length];
1107  /* Update current slot start */
1108  prev_slot_start = current_slot_start;
1109  current_slot_start += time_to_next_active_slot;
1110  } while(!tsch_schedule_slot_operation(&slot_operation_timer, prev_slot_start, time_to_next_active_slot, "assoc"));
1111 }
1112 /*---------------------------------------------------------------------------*/
1113 /* Start actual slot operation */
1114 void
1115 tsch_slot_operation_sync(rtimer_clock_t next_slot_start,
1116  struct tsch_asn_t *next_slot_asn)
1117 {
1118  current_slot_start = next_slot_start;
1119  tsch_current_asn = *next_slot_asn;
1120  last_sync_asn = tsch_current_asn;
1121  last_sync_time = clock_time();
1122  current_link = NULL;
1123 }
1124 /*---------------------------------------------------------------------------*/
1125 /** @} */
TSCH packet information.
Definition: tsch-types.h:97
#define TSCH_LOG_ADD(log_type, init_code)
Use this macro to add a log to the queue (will be printed out later, after leaving interrupt context)...
Definition: tsch-log.h:140
frame802154_scf_t security_control
Security control bitfield.
Definition: frame802154.h:188
struct tsch_neighbor * tsch_queue_get_nbr(const linkaddr_t *addr)
Get a TSCH neighbor.
Definition: tsch-queue.c:108
static void tsch_radio_off(enum tsch_radio_state_off_cmd command)
This function turns off the radio.
int rtimer_set(struct rtimer *rtimer, rtimer_clock_t time, rtimer_clock_t duration, rtimer_callback_t func, void *ptr)
Post a real-time task.
Definition: rtimer.c:67
frame802154_fcf_t fcf
Frame control field.
Definition: frame802154.h:204
Representation of a real-time task.
Definition: rtimer.h:111
struct tsch_neighbor * last_timesource_neighbor
The neighbor last used as our time source.
The MAC layer transmission could not be performed because of a fatal error.
Definition: mac.h:98
int tsch_get_lock(void)
Takes the TSCH lock.
Header file for the radio API
uint8_t security_level
3 bit.
Definition: frame802154.h:168
void tsch_release_lock(void)
Releases the TSCH lock.
int frame802154_parse(uint8_t *data, int len, frame802154_t *pf)
Parses an input frame.
Definition: frame802154.c:500
TSCH neighbor information.
Definition: tsch-types.h:109
void tsch_queue_update_all_backoff_windows(const linkaddr_t *dest_addr)
Decrement backoff window for the queue(s) able to Tx to a given address.
Definition: tsch-queue.c:503
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.
#define PT_BEGIN(pt)
Declare the start of a protothread inside the C function implementing the protothread.
Definition: pt.h:114
void tsch_timesync_update(struct tsch_neighbor *n, uint16_t time_delta_asn, int32_t drift_correction)
Updates timesync information for a given neighbor.
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:307
A MAC framer for IEEE 802.15.4
const linkaddr_t linkaddr_null
The null link-layer address.
#define PT_SPAWN(pt, child, thread)
Spawn a child protothread and wait until it exits.
Definition: pt.h:205
int tsch_packet_update_eb(uint8_t *buf, int buf_size, uint8_t tsch_sync_ie_offset)
Update ASN in EB packet.
Definition: tsch-packet.c:391
linkaddr_t linkaddr_node_addr
The link-layer address of the node.
Definition: linkaddr.c:48
uint8_t tsch_calculate_channel(struct tsch_asn_t *asn, uint8_t channel_offset)
Returns a 802.15.4 channel from an ASN and channel offset.
#define RTIMER_NOW()
Get the current clock time.
Definition: rtimer.h:160
int32_t tsch_timesync_adaptive_compensate(rtimer_clock_t delta_ticks)
Computes time compensation for a given point in the future.
unsigned int tsch_security_mic_len(const frame802154_t *frame)
Return MIC length.
#define PT_END(pt)
Declare the end of a protothread.
Definition: pt.h:126
Header file for the Packet queue buffer management
The MAC layer did not get an acknowledgement for the packet.
Definition: mac.h:88
void process_poll(struct process *p)
Request a process to be polled.
Definition: process.c:371
struct tsch_link * tsch_schedule_get_next_active_link(struct tsch_asn_t *asn, uint16_t *time_offset, struct tsch_link **backup_link)
Returns the next active link after a given ASN, and a backup link (for the same ASN, with Rx flag)
The MAC layer transmission was OK.
Definition: mac.h:84
#define TSCH_ASN_MOD(asn, div)
Returns the result (16 bits) of a modulo operation on ASN, with divisor being a struct asn_divisor_t...
Definition: tsch-asn.h:93
#define PT_YIELD(pt)
Yield from the current protothread.
Definition: pt.h:289
int tsch_packet_parse_eack(const uint8_t *buf, int buf_size, uint8_t seqno, frame802154_t *frame, struct ieee802154_ies *ies, uint8_t *hdr_len)
Parse enhanced ACK packet.
Definition: tsch-packet.c:162
Main API declarations for TSCH.
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:192
struct tsch_packet * tsch_queue_get_packet_for_nbr(const struct tsch_neighbor *n, struct tsch_link *link)
Returns the first packet that can be sent from a queue on a given link.
Definition: tsch-queue.c:410
#define RADIO_RX_MODE_ADDRESS_FILTER
The radio reception mode controls address filtering and automatic transmission of acknowledgements in...
Definition: radio.h:214
int tsch_is_locked(void)
Checks if the TSCH lock is set.
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:91
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
void tsch_packet_set_frame_pending(uint8_t *buf, int buf_size)
Set frame pending bit in a packet (whose header was already build)
Definition: tsch-packet.c:467
int tsch_queue_packet_sent(struct tsch_neighbor *n, struct tsch_packet *p, struct tsch_link *link, uint8_t mac_tx_status)
Updates neighbor queue state after a transmission.
Definition: tsch-queue.c:322
#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
static void tsch_radio_on(enum tsch_radio_state_on_cmd command)
This function turns on the radio.
int tsch_queue_packet_count(const linkaddr_t *addr)
Returns the number of packets currently a given neighbor queue.
Definition: tsch-queue.c:280
#define TSCH_ASN_INC(asn, inc)
Increment an ASN by inc (32 bits)
Definition: tsch-asn.h:68
uint8_t seq
Sequence number.
Definition: frame802154.h:205
int tsch_packet_get_frame_pending(uint8_t *buf, int buf_size)
Get frame pending bit from a packet.
Definition: tsch-packet.c:474
int ringbufindex_peek_put(const struct ringbufindex *r)
Check if there is space to put an element.
Definition: ringbufindex.c:78
void tsch_disassociate(void)
Leave the TSCH network we are currently in.
Definition: tsch.c:510
Header file for the Packet buffer (packetbuf) management
Include file for the Contiki low-layer network stack (NETSTACK)
void watchdog_periodic(void)
Writes the WDT clear sequence.
Definition: watchdog.c:85
struct tsch_packet * tsch_queue_get_unicast_packet_for_any(struct tsch_neighbor **n, struct tsch_link *link)
Gets the head packet of any neighbor queue with zero backoff counter.
Definition: tsch-queue.c:449
unsigned int tsch_security_secure_frame(uint8_t *hdr, uint8_t *outbuf, int hdrlen, int datalen, struct tsch_asn_t *asn)
Protect a frame with encryption and/or MIC.
Stores data about an incoming packet.
Definition: tsch-types.h:146
Header file for the logging system
uint8_t ack_required
1 bit.
Definition: frame802154.h:156
int ringbufindex_put(struct ringbufindex *r)
Put one element to the ring buffer.
Definition: ringbufindex.c:58
void tsch_slot_operation_start(void)
Start actual slot operation.
The ASN is an absolute slot number over 5 bytes.
Definition: tsch-asn.h:48
frame802154_aux_hdr_t aux_hdr
Aux security header.
Definition: frame802154.h:208
int tsch_packet_create_eack(uint8_t *buf, uint16_t buf_len, const linkaddr_t *dest_addr, uint8_t seqno, int16_t drift, int nack)
Construct Enhanced ACK packet.
Definition: tsch-packet.c:93