From 372bb5314181e2ff22d4db160134691f1e933c78 Mon Sep 17 00:00:00 2001
From: stier2 <stier2@illinois.edu>
Date: Sat, 25 Sep 2021 15:37:46 -0500
Subject: [PATCH] Icra 2022

---
 DecaRanging.coproj                        |  30 +++---
 src/application/application_definitions.h |   2 +-
 src/application/dw_main.c                 |  22 ++--
 src/application/instance.c                | 123 +++++++++++++---------
 src/application/instance.h                |   6 +-
 src/application/instance_common.c         |   9 +-
 src/application/tdma_handler.c            |  91 ++++++++--------
 src/application/tdma_handler.h            |   1 +
 8 files changed, 159 insertions(+), 125 deletions(-)

diff --git a/DecaRanging.coproj b/DecaRanging.coproj
index bb7059c..098c2b1 100644
--- a/DecaRanging.coproj
+++ b/DecaRanging.coproj
@@ -104,22 +104,22 @@
     <File name="src/platform/deca_spi.h" path="src/platform/deca_spi.h" type="1"/>
     <File name="Libraries/STM32_USB_Device_Library/Core/src/usbd_ioreq.c" path="Libraries/STM32_USB_Device_Library/Core/src/usbd_ioreq.c" type="1"/>
     <File name="Libraries/STM32_USB_Device_Library/Class/cdc/src/usbd_cdc_core.c" path="Libraries/STM32_USB_Device_Library/Class/cdc/src/usbd_cdc_core.c" type="1"/>
-    <File name="Libraries/STM32_USB_Device_Library/Class/cdc/inc/usbd_cdc_core.h" path="Libraries/STM32_USB_Device_Library/Class/cdc/inc/usbd_cdc_core.h" type="1"/>
     <File name="src/usb/usbd_desc.h" path="src/usb/usbd_desc.h" type="1"/>
+    <File name="Libraries/STM32_USB_Device_Library/Class/cdc/inc/usbd_cdc_core.h" path="Libraries/STM32_USB_Device_Library/Class/cdc/inc/usbd_cdc_core.h" type="1"/>
     <File name="src/platform/deca_spi.c" path="src/platform/deca_spi.c" type="1"/>
     <File name="src/usb" path="" type="2"/>
     <File name="src/decadriver/deca_version.h" path="src/decadriver/deca_version.h" type="1"/>
     <File name="Libraries/STM32F10x_StdPeriph_Driver/src/stm32f10x_flash.c" path="Libraries/STM32F10x_StdPeriph_Driver/src/stm32f10x_flash.c" type="1"/>
-    <File name="src/application/instance.c" path="src/application/instance.c" type="1"/>
     <File name="Libraries/STM32F10x_StdPeriph_Driver/src/stm32f10x_wwdg.c" path="Libraries/STM32F10x_StdPeriph_Driver/src/stm32f10x_wwdg.c" type="1"/>
+    <File name="src/application/instance.c" path="src/application/instance.c" type="1"/>
     <File name="Libraries/STM32F10x_StdPeriph_Driver/inc/stm32f10x_dbgmcu.h" path="Libraries/STM32F10x_StdPeriph_Driver/inc/stm32f10x_dbgmcu.h" type="1"/>
-    <File name="src/decadriver/deca_device_api.h" path="src/decadriver/deca_device_api.h" type="1"/>
     <File name="Libraries/STM32F10x_StdPeriph_Driver/src/stm32f10x_sdio.c" path="Libraries/STM32F10x_StdPeriph_Driver/src/stm32f10x_sdio.c" type="1"/>
+    <File name="src/decadriver/deca_device_api.h" path="src/decadriver/deca_device_api.h" type="1"/>
     <File name="Libraries/CMSIS/CM3/DeviceSupport/ST/STM32F10x" path="" type="2"/>
-    <File name="Libraries/STM32F10x_StdPeriph_Driver/inc/stm32f10x_bkp.h" path="Libraries/STM32F10x_StdPeriph_Driver/inc/stm32f10x_bkp.h" type="1"/>
     <File name="Libraries/STM32F10x_StdPeriph_Driver/src/stm32f10x_iwdg.c" path="Libraries/STM32F10x_StdPeriph_Driver/src/stm32f10x_iwdg.c" type="1"/>
-    <File name="src/compiler/compiler.h" path="src/compiler/compiler.h" type="1"/>
+    <File name="Libraries/STM32F10x_StdPeriph_Driver/inc/stm32f10x_bkp.h" path="Libraries/STM32F10x_StdPeriph_Driver/inc/stm32f10x_bkp.h" type="1"/>
     <File name="src/application/tdma_handler.h" path="src/application/tdma_handler.h" type="1"/>
+    <File name="src/compiler/compiler.h" path="src/compiler/compiler.h" type="1"/>
     <File name="Libraries/STM32_USB_OTG_Driver" path="" type="2"/>
     <File name="src/platform/deca_mutex.c" path="src/platform/deca_mutex.c" type="1"/>
     <File name="Libraries/STM32F10x_StdPeriph_Driver/src/stm32f10x_crc.c" path="Libraries/STM32F10x_StdPeriph_Driver/src/stm32f10x_crc.c" type="1"/>
@@ -132,23 +132,23 @@
     <File name="src/application/tdma_handler.c" path="src/application/tdma_handler.c" type="1"/>
     <File name="Libraries/STM32_USB_OTG_Driver/src/usb_hcd_int.c" path="Libraries/STM32_USB_OTG_Driver/src/usb_hcd_int.c" type="1"/>
     <File name="src/platform/port.c" path="src/platform/port.c" type="1"/>
-    <File name="Libraries/CMSIS/CM3/DeviceSupport/ST/STM32F10x/system_stm32f10x.h" path="Libraries/CMSIS/CM3/DeviceSupport/ST/STM32F10x/system_stm32f10x.h" type="1"/>
     <File name="Libraries/STM32F10x_StdPeriph_Driver/inc/stm32f10x_wwdg.h" path="Libraries/STM32F10x_StdPeriph_Driver/inc/stm32f10x_wwdg.h" type="1"/>
+    <File name="Libraries/CMSIS/CM3/DeviceSupport/ST/STM32F10x/system_stm32f10x.h" path="Libraries/CMSIS/CM3/DeviceSupport/ST/STM32F10x/system_stm32f10x.h" type="1"/>
     <File name="src/decadriver/deca_device.c" path="src/decadriver/deca_device.c" type="1"/>
     <File name="Libraries/STM32F10x_StdPeriph_Driver/src/stm32f10x_exti.c" path="Libraries/STM32F10x_StdPeriph_Driver/src/stm32f10x_exti.c" type="1"/>
+    <File name="Libraries/STM32F10x_StdPeriph_Driver/src/stm32f10x_rtc.c" path="Libraries/STM32F10x_StdPeriph_Driver/src/stm32f10x_rtc.c" type="1"/>
     <File name="Libraries/STM32_USB_Device_Library/Core/inc/usbd_req.h" path="Libraries/STM32_USB_Device_Library/Core/inc/usbd_req.h" type="1"/>
     <File name="Libraries/STM32F10x_StdPeriph_Driver/inc/stm32f10x_adc.h" path="Libraries/STM32F10x_StdPeriph_Driver/inc/stm32f10x_adc.h" type="1"/>
-    <File name="Libraries/STM32F10x_StdPeriph_Driver/src/stm32f10x_rtc.c" path="Libraries/STM32F10x_StdPeriph_Driver/src/stm32f10x_rtc.c" type="1"/>
     <File name="Libraries/STM32F10x_StdPeriph_Driver/src/stm32f10x_fsmc.c" path="Libraries/STM32F10x_StdPeriph_Driver/src/stm32f10x_fsmc.c" type="1"/>
     <File name="src/usb/usb_conf.h" path="src/usb/usb_conf.h" type="1"/>
     <File name="Libraries/STM32_USB_OTG_Driver/inc/usb_otg.h" path="Libraries/STM32_USB_OTG_Driver/inc/usb_otg.h" type="1"/>
     <File name="Libraries/STM32F10x_StdPeriph_Driver/src/stm32f10x_rcc.c" path="Libraries/STM32F10x_StdPeriph_Driver/src/stm32f10x_rcc.c" type="1"/>
     <File name="Libraries/STM32_USB_Device_Library/Core/src/usbd_req.c" path="Libraries/STM32_USB_Device_Library/Core/src/usbd_req.c" type="1"/>
     <File name="src/usb/usbd_conf.h" path="src/usb/usbd_conf.h" type="1"/>
-    <File name="src/usb/deca_usb.c" path="src/usb/deca_usb.c" type="1"/>
     <File name="src/application/application_definitions.h" path="src/application/application_definitions.h" type="1"/>
-    <File name="src/application/lib.h" path="src/application/lib.h" type="1"/>
+    <File name="src/usb/deca_usb.c" path="src/usb/deca_usb.c" type="1"/>
     <File name="src/platform/deca_range_tables.c" path="src/platform/deca_range_tables.c" type="1"/>
+    <File name="src/application/lib.h" path="src/application/lib.h" type="1"/>
     <File name="Libraries/STM32_USB_OTG_Driver/src" path="" type="2"/>
     <File name="Libraries/STM32F10x_StdPeriph_Driver/src/stm32f10x_dma.c" path="Libraries/STM32F10x_StdPeriph_Driver/src/stm32f10x_dma.c" type="1"/>
     <File name="Libraries/STM32F10x_StdPeriph_Driver/src/stm32f10x_pwr.c" path="Libraries/STM32F10x_StdPeriph_Driver/src/stm32f10x_pwr.c" type="1"/>
@@ -165,22 +165,22 @@
     <File name="Libraries/STM32F10x_StdPeriph_Driver/inc/stm32f10x_cec.h" path="Libraries/STM32F10x_StdPeriph_Driver/inc/stm32f10x_cec.h" type="1"/>
     <File name="Libraries/STM32_USB_OTG_Driver/src/usb_hcd.c" path="Libraries/STM32_USB_OTG_Driver/src/usb_hcd.c" type="1"/>
     <File name="src/platform/deca_sleep.c" path="src/platform/deca_sleep.c" type="1"/>
-    <File name="Libraries/CMSIS/CM3/CoreSupport" path="" type="2"/>
     <File name="Libraries/STM32_USB_OTG_Driver/inc/usb_defines.h" path="Libraries/STM32_USB_OTG_Driver/inc/usb_defines.h" type="1"/>
-    <File name="src/decadriver/deca_param_types.h" path="src/decadriver/deca_param_types.h" type="1"/>
-    <File name="src/compiler" path="" type="2"/>
+    <File name="Libraries/CMSIS/CM3/CoreSupport" path="" type="2"/>
     <File name="Libraries/STM32_USB_OTG_Driver/src/usb_dcd_int.c" path="Libraries/STM32_USB_OTG_Driver/src/usb_dcd_int.c" type="1"/>
+    <File name="src/compiler" path="" type="2"/>
+    <File name="src/decadriver/deca_param_types.h" path="src/decadriver/deca_param_types.h" type="1"/>
     <File name="src/usb/deca_usb_bsp_evk1000.c" path="src/usb/deca_usb_bsp_evk1000.c" type="1"/>
     <File name="Libraries/CMSIS/CM3/DeviceSupport/ST/STM32F10x/startup/startup_stm32f10x_cl.S" path="Libraries/CMSIS/CM3/DeviceSupport/ST/STM32F10x/startup/startup_stm32f10x_cl.S" type="1"/>
-    <File name="src/platform/stm32f10x_conf.h" path="src/platform/stm32f10x_conf.h" type="1"/>
     <File name="Libraries/STM32_USB_OTG_Driver/inc/usb_bsp.h" path="Libraries/STM32_USB_OTG_Driver/inc/usb_bsp.h" type="1"/>
+    <File name="src/platform/stm32f10x_conf.h" path="src/platform/stm32f10x_conf.h" type="1"/>
     <File name="Libraries/CMSIS/CM3" path="" type="2"/>
     <File name="Libraries" path="" type="2"/>
     <File name="src/decadriver/deca_types.h" path="src/decadriver/deca_types.h" type="1"/>
     <File name="src/usb/deca_usb.h" path="src/usb/deca_usb.h" type="1"/>
     <File name="Libraries/STM32F10x_StdPeriph_Driver/inc" path="" type="2"/>
-    <File name="Libraries/STM32_USB_Device_Library/Core/inc/usbd_def.h" path="Libraries/STM32_USB_Device_Library/Core/inc/usbd_def.h" type="1"/>
     <File name="Libraries/STM32F10x_StdPeriph_Driver/inc/stm32f10x_spi.h" path="Libraries/STM32F10x_StdPeriph_Driver/inc/stm32f10x_spi.h" type="1"/>
+    <File name="Libraries/STM32_USB_Device_Library/Core/inc/usbd_def.h" path="Libraries/STM32_USB_Device_Library/Core/inc/usbd_def.h" type="1"/>
     <File name="Libraries/STM32F10x_StdPeriph_Driver/inc/stm32f10x_iwdg.h" path="Libraries/STM32F10x_StdPeriph_Driver/inc/stm32f10x_iwdg.h" type="1"/>
     <File name="src/platform/stm32f10x_it.c" path="src/platform/stm32f10x_it.c" type="1"/>
     <File name="Libraries/CMSIS/CM3/DeviceSupport/ST/STM32F10x/system_stm32f10x.c" path="Libraries/CMSIS/CM3/DeviceSupport/ST/STM32F10x/system_stm32f10x.c" type="1"/>
@@ -214,8 +214,8 @@
     <File name="Libraries/CMSIS/CM3/DeviceSupport/ST/STM32F10x/startup" path="" type="2"/>
     <File name="Libraries/STM32_USB_OTG_Driver/inc/usb_core.h" path="Libraries/STM32_USB_OTG_Driver/inc/usb_core.h" type="1"/>
     <File name="Libraries/STM32F10x_StdPeriph_Driver/src/stm32f10x_bkp.c" path="Libraries/STM32F10x_StdPeriph_Driver/src/stm32f10x_bkp.c" type="1"/>
-    <File name="Libraries/STM32F10x_StdPeriph_Driver/src/stm32f10x_gpio.c" path="Libraries/STM32F10x_StdPeriph_Driver/src/stm32f10x_gpio.c" type="1"/>
     <File name="src/application/dw_main.c" path="src/application/dw_main.c" type="1"/>
+    <File name="Libraries/STM32F10x_StdPeriph_Driver/src/stm32f10x_gpio.c" path="Libraries/STM32F10x_StdPeriph_Driver/src/stm32f10x_gpio.c" type="1"/>
     <File name="src/platform" path="" type="2"/>
     <File name="Libraries/STM32F10x_StdPeriph_Driver/src/stm32f10x_tim.c" path="Libraries/STM32F10x_StdPeriph_Driver/src/stm32f10x_tim.c" type="1"/>
     <File name="Libraries/STM32F10x_StdPeriph_Driver/inc/stm32f10x_i2c.h" path="Libraries/STM32F10x_StdPeriph_Driver/inc/stm32f10x_i2c.h" type="1"/>
diff --git a/src/application/application_definitions.h b/src/application/application_definitions.h
index d7f882a..4ca8249 100644
--- a/src/application/application_definitions.h
+++ b/src/application/application_definitions.h
@@ -237,7 +237,7 @@ enum
 #define SLOT_BUFFER_EXP_TO_POLL_CMD_US		3*UWB_LIST_SIZE + 108 //found experimentally
 #define MEASURED_SLOT_DURATIONS_US			(float)(1.7814f*(float)(UWB_LIST_SIZE)*(float)(UWB_LIST_SIZE) + 29.39f*(float)(UWB_LIST_SIZE) + 1848.5f)	//found experimentally
 #define LCD_ENABLE_BUFFER_US				5000
-#define SLOT_END_BUFFER_US					0		          //increase if all messages do not fit into a slot
+#define SLOT_END_BUFFER_US					0 					  //increase if all messages do not fit into a slot //TODO set back to zero!
 #define BLINK_RX_CB_TO_RESP_TX_CMD_DLY_US	1450				  //found experimentally
 
 
diff --git a/src/application/dw_main.c b/src/application/dw_main.c
index 37c2732..03b0a25 100644
--- a/src/application/dw_main.c
+++ b/src/application/dw_main.c
@@ -30,7 +30,7 @@ extern void send_usbmessage(uint8*, int);
 
 extern double dwt_getrangebias(uint8 chan, float range, uint8 prf);
 
-#define SOFTWARE_VER_STRING    "TDMA Version 1.0" //
+#define SOFTWARE_VER_STRING    "TDMA Version 1.1" //
 
 int instance_mode = DISCOVERY;
 
@@ -85,6 +85,7 @@ uint32 inittestapplication(uint8 mode_switch)
     instance_init_s();
 	int dr_mode = decarangingmode(mode_switch);
 	instance_data_t* inst = instance_get_local_structure_ptr(0);
+	
 
     chan = inst->chConfig[dr_mode].channelNumber ;
     prf = (inst->chConfig[dr_mode].pulseRepFreq == DWT_PRF_16M)? 16 : 64 ;
@@ -139,7 +140,7 @@ void configure_continuous_txspectrum_mode(uint8 mode_switch)
 		writetoLCD(1, 0,  &command);
 		sprintf((char*)&dataseq[0], "Conti TX %s:%d:%d ", (mode_switch & SWS1_SHF_MODE) ? "S" : "L", chan, prf);
 		writetoLCD(LCD_BUFF_LEN, 1, dataseq); //send some data
-		memcpy(dataseq, (const uint8 *) "Spectrum Test   ", LCD_BUFF_LEN);
+		memcpy(dataseq, (const uint8 *) "Spectrum Test   ", 17);
 		writetoLCD(LCD_BUFF_LEN, 1, dataseq); //send some data
 	}
 
@@ -308,9 +309,9 @@ int dw_main(void)
 
 		memset(dataseq, 0x0, sizeof(dataseq));
 		writetoLCD(1, 0, dataseq);
-		memcpy(dataseq, (const uint8 *) "GGRG UWB RANGING", LCD_BUFF_LEN);
+		memcpy(dataseq, (const uint8 *) "GGRG UWB RANGING", 17);
 		writetoLCD(40, 1, dataseq); //send some data
-		memcpy(dataseq, (const uint8 *) SOFTWARE_VER_STRING, LCD_BUFF_LEN);
+		memcpy(dataseq, (const uint8 *) SOFTWARE_VER_STRING, 17);
 		writetoLCD(16, 1, dataseq); //send some data
 	}
 
@@ -343,9 +344,9 @@ int dw_main(void)
 			dataseq[0] = 0x2 ;  //return cursor home
 			writetoLCD(1, 0,  &dataseq[0]);
 			memset(dataseq, ' ', LCD_BUFF_LEN);
-			memcpy(dataseq, (const uint8 *) "ERROR           ", LCD_BUFF_LEN);
+			memcpy(dataseq, (const uint8 *) "ERROR           ", 17);
 			writetoLCD( 40, 1, dataseq); //send some data
-			memcpy(dataseq, (const uint8 *) "INIT FAIL       ", LCD_BUFF_LEN);
+			memcpy(dataseq, (const uint8 *) "INIT FAIL       ", 17);
 			writetoLCD( 16, 1, dataseq); //send some data
 		}
 		return 0; //error
@@ -358,7 +359,7 @@ int dw_main(void)
 		dataseq[0] = 0x2 ;  //return cursor home
 		writetoLCD( 1, 0,  dataseq);
 		memset(dataseq, ' ', LCD_BUFF_LEN);
-		memcpy(dataseq, (const uint8 *) "MAX NETWORK SIZE", LCD_BUFF_LEN);
+		memcpy(dataseq, (const uint8 *) "MAX NETWORK SIZE", 17);
 		writetoLCD(40, 1, dataseq); //send some data
 		memset(dataseq, ' ', LCD_BUFF_LEN);
 		sprintf((char*)&dataseq[0], "%d", UWB_LIST_SIZE);
@@ -369,7 +370,7 @@ int dw_main(void)
 		dataseq[0] = 0x2 ;  //return cursor home
 		writetoLCD( 1, 0,  dataseq);
 		memset(dataseq, ' ', LCD_BUFF_LEN);
-		memcpy(dataseq, (const uint8 *) "SLOT DURATION   ", LCD_BUFF_LEN);
+		memcpy(dataseq, (const uint8 *) "SLOT DURATION   ", 17);
 		writetoLCD(40, 1, dataseq); //send some data
 		memset(dataseq, ' ', LCD_BUFF_LEN);
 		sprintf((char*)&dataseq[0], "%llu us", inst->durationSlotMax_us);
@@ -431,6 +432,8 @@ int dw_main(void)
 
     last_toggle = portGetTickCnt();
 
+	//TODO remove? struct TDMAHandler* tdma_handler =  tdma_get_local_structure_ptr();
+
     // main loop
     while(1)
     {
@@ -482,6 +485,9 @@ int dw_main(void)
 
 				}
 
+
+
+
 //				n = sprintf((char*)&dataseq[0], "%08i, %08i, %08i, %08f", rng_rng, rng_rsl, rng_raw, rsl/1000.0);
 				n = sprintf((char*)&dataseq[0], "%016llX %016llX %016llX %08X %08X %08X %08X", saddr, aaddr, taddr, rng_rng, rng_rsl, rng_raw, rsl);
 
diff --git a/src/application/instance.c b/src/application/instance.c
index db1bad9..6690238 100644
--- a/src/application/instance.c
+++ b/src/application/instance.c
@@ -534,6 +534,7 @@ int testapprun(instance_data_t *inst, struct TDMAHandler *tdma_handler, int mess
 				uint64 margin_us = 1000;
 				uint64 framelength_us = instance_getmessageduration_us(psduLength);
 				inst->txDoneTimeoutDuration = CEIL_DIV(TX_CMD_TO_TX_CB_DLY_US + framelength_us + margin_us, 1000);			//tx cmd to tx cb
+
 			}
 
 			break;
@@ -575,6 +576,7 @@ int testapprun(instance_data_t *inst, struct TDMAHandler *tdma_handler, int mess
 				inst->canPrintLCD = FALSE;
 
 				inst->timeofTx = portGetTickCnt();
+				inst->timeofTxPoll = portGetTickCnt();
 				inst->txDoneTimeoutDuration = inst->durationPollTxDoneTimeout_ms;
 			}
 
@@ -1036,6 +1038,7 @@ int testapprun(instance_data_t *inst, struct TDMAHandler *tdma_handler, int mess
 
 							if(tag_index == 0)
 							{
+								tdma_handler->nthOldest = 1;
 								tdma_handler->uwbListTDMAInfo[inst->uwbToRangeWith].lastRange = portGetTickCnt();
 								tdma_handler->firstPollComplete = TRUE;
 								inst->testAppState = TA_TX_SELECT;
@@ -1085,6 +1088,29 @@ int testapprun(instance_data_t *inst, struct TDMAHandler *tdma_handler, int mess
                 case 0:
                 default:
                 {
+                	if(inst->mode == TAG){
+                		//get the message FCODE
+						uint8 fcode;
+						memcpy(&fcode, &inst->msg.messageData[FCODE], sizeof(uint8));
+
+						if(fcode == RTLS_DEMO_MSG_TAG_POLL)
+						{
+							uint32 dt = get_dt32(inst->timeofTxPoll, portGetTickCnt());
+							if(dt > inst->durationPollTimeout_ms)
+							{
+								inst_processtxrxtimeout(inst);
+							}
+						}
+						else if(fcode == RTLS_DEMO_MSG_TAG_FINAL)
+						{
+							uint32 dt = get_dt32(inst->timeofTxFinal, portGetTickCnt());
+							if(dt > inst->durationFinalTimeout_ms)
+							{
+								inst_processtxrxtimeout(inst);
+							}
+						}
+                	}
+
                 	//check if RX is on every so often. Turn it on if it isn't.
                 	uint32 time_now = portGetTickCnt();
 					uint32 timeSinceRxCheck = get_dt32(inst->rxCheckOnTime, time_now);
@@ -1243,57 +1269,79 @@ void instance_init_timings(void)
     	inst->frameLengths_us[i] = instance_getmessageduration_us(data_len_bytes[i]);
     }
 
-    //rx timeout durations (units are 1.0256us)
+    //delayed tx durations
+    uint8 reply_margin_us = 25;
     uint64 duration = 0;
-    duration += inst->frameLengths_us[POLL] - inst->storedPreLen_us; 					//poll tx ts to poll tx cb
-    duration += RX_TO_CB_DLY_US + RX_CB_TO_TX_CMD_DLY_US;			  					//poll tx cb to resp tx cmd
-    duration += TX_CMD_TO_TX_CB_DLY_US + inst->frameLengths_us[RESP] + RX_TO_CB_DLY_US; //resp tx cmd to resp rx cb
-    duration += margin_us;
-    inst->durationPollTimeout_nus = (uint16)(duration/1.0256) + 1;
-
-	//delayed tx durations
-	duration = 0;
-	duration += inst->frameLengths_us[POLL] - inst->storedPreLen_us;						//poll tx ts to poll tx cb
-	duration += RX_TO_CB_DLY_US + RX_CB_TO_TX_CMD_DLY_US; 									//poll tx cb to resp tx cmd
-	duration += TX_CMD_TO_TX_CB_DLY_US + inst->frameLengths_us[RESP] + RX_TO_CB_DLY_US;		//resp tx cmd to resp rx cb
-	duration += RX_CB_TO_TX_CMD_DLY_US + MIN_DELAYED_TX_DLY_US + inst->storedPreLen_us;		//resp rx cb to final tx timestamp
-	inst->finalReplyDelay_us = duration + margin_us;
-	inst->finalReplyDelay = convertmicrosectodevicetimeu(duration);
-    // Delay between blink reception and ranging init message transmission.
-	inst->rnginitReplyDelay = convertmicrosectodevicetimeu(MIN_DELAYED_TX_DLY_US + inst->storedPreLen_us); //rng_init tx cmd to rng_init tx ts
-
-	uint8 reply_margin_us = 25;
-	duration = 0;
-	duration += inst->frameLengths_us[POLL] - inst->storedPreLen_us + RX_TO_CB_DLY_US;		//resp rx timestamp to resp rx cb
-	duration += RX_CB_TO_TX_CMD_DLY_US + MIN_DELAYED_TX_DLY_US + inst->storedPreLen_us;		//resp rx cb to final tx timestamp
-	uint64 respDelay = convertmicrosectodevicetimeu(duration + reply_margin_us);
+	duration += inst->frameLengths_us[POLL] - inst->storedPreLen_us + RX_TO_CB_DLY_US;		//poll rx timestamp to poll rx cb
+	duration += RX_CB_TO_TX_CMD_DLY_US + MIN_DELAYED_TX_DLY_US + inst->storedPreLen_us;		//poll rx cb to resp tx timestamp
+	uint64 respDelay_us = duration + reply_margin_us;
+	uint64 respDelay = convertmicrosectodevicetimeu(respDelay_us);
 
 	duration = 0;
 	duration += inst->frameLengths_us[RESP] - inst->storedPreLen_us + RX_TO_CB_DLY_US;		//resp rx timestamp to resp rx cb
 	duration += RX_CB_TO_TX_CMD_DLY_US + MIN_DELAYED_TX_DLY_US + inst->storedPreLen_us;		//resp rx cb to final tx timestamp
-	uint64 finalDelay = convertmicrosectodevicetimeu(duration + reply_margin_us);
+	uint64 finalDelay_us = duration + reply_margin_us;
+	uint64 finalDelay = convertmicrosectodevicetimeu(finalDelay_us);
 
 	//make reply times the same to minimize clock drift error. See Application Note APS011 for more information
 	inst->respReplyDelay = inst->finalReplyDelay = MAX(respDelay, finalDelay);
+	uint64 replyDelay_us = MAX(respDelay_us, finalDelay_us);
+
+
+	//POLL TX TS TO FINAL TX TS
+	duration = 0;
+	duration += respDelay_us + finalDelay_us;												//poll tx ts to final tx ts
+	uint64 pollTxToFinalTx = duration;
+
+    // Delay between blink reception and ranging init message transmission.
+	inst->rnginitReplyDelay = convertmicrosectodevicetimeu(MIN_DELAYED_TX_DLY_US + inst->storedPreLen_us); //rng_init tx cmd to rng_init tx ts
 
+	margin_us = 1000;
+    //rx timeout durations (_nus units are 1.0256us)
+    duration = 0;
+    duration +=	TX_CMD_TO_TX_CB_DLY_US + replyDelay_us;						//poll tx cmd to resp tx ts
+    duration +=	inst->frameLengths_us[RESP] - inst->storedPreLen_us;		//resp tx ts to resp tx cb
+    duration += RX_TO_CB_DLY_US + RX_CB_TO_TX_CMD_DLY_US;					//resp tx cb to final tx cmd
+    duration += margin_us;
+    inst->durationPollTimeout_nus = (uint16)(duration/1.0256) + 1;
+	inst->durationPollTimeout_ms = (uint16)CEIL_DIV(duration, 1000);
+
+	duration = 0;
+	duration += TX_CMD_TO_TX_CB_DLY_US + inst->frameLengths_us[FINAL]; 	                                           //final tx cmd to final tx cb
+	duration += RX_TO_CB_DLY_US + RX_CB_TO_TX_CMD_DLY_US;			  	                                           //final tx cb to place final
+	duration += (uint64)MEASURED_SLOT_DURATIONS_US/2;                                   						   //place final to report tx cmd
+	duration += TX_CMD_TO_TX_CB_DLY_US + inst->frameLengths_us[REPORT] + RX_TO_CB_DLY_US + RX_CB_TO_TX_CMD_DLY_US; //report tx cmd to place report
+	duration += margin_us;
+	inst->durationFinalTimeout_ms = (uint16)CEIL_DIV(duration, 1000);
 
 	margin_us = 1000;
     //tx conf timeout durations
     inst->durationBlinkTxDoneTimeout_ms = CEIL_DIV(TX_CMD_TO_TX_CB_DLY_US + inst->frameLengths_us[BLINK] + margin_us, 1000);			//tx cmd to tx cb
     inst->durationRngInitTxDoneTimeout_ms = CEIL_DIV(TX_CMD_TO_TX_CB_DLY_US + inst->frameLengths_us[RNG_INIT] + margin_us, 1000);		//tx cmd to tx cb
     inst->durationPollTxDoneTimeout_ms = CEIL_DIV(TX_CMD_TO_TX_CB_DLY_US + inst->frameLengths_us[POLL] + margin_us, 1000);				//tx cmd to tx cb
-    inst->durationRespTxDoneTimeout_ms = CEIL_DIV(TX_CMD_TO_TX_CB_DLY_US + inst->frameLengths_us[RESP] + margin_us, 1000);				//tx cmd to tx cb
-    inst->durationFinalTxDoneTimeout_ms = CEIL_DIV(TX_CMD_TO_TX_CB_DLY_US + inst->frameLengths_us[FINAL] + margin_us, 1000);			//tx cmd to tx cb
     inst->durationReportTxDoneTimeout_ms = CEIL_DIV(TX_CMD_TO_TX_CB_DLY_US + inst->frameLengths_us[REPORT] + margin_us, 1000);			//tx cmd to tx cb
     inst->durationSyncTxDoneTimeout_ms = CEIL_DIV(TX_CMD_TO_TX_CB_DLY_US + inst->frameLengths_us[SYNC] + margin_us, 1000);				//tx cmd to tx cb
 
-
+    uint32 fl = 0;
+    if(inst->frameLengths_us[RESP] < inst->frameLengths_us[FINAL])
+    {
+    	fl = inst->frameLengths_us[RESP] - inst->storedPreLen_us;
+    }
+    else
+    {
+    	fl = inst->frameLengths_us[FINAL] - inst->storedPreLen_us;
+    }
+    duration = 0;
+    duration += replyDelay_us - fl;
+    duration -= RX_TO_CB_DLY_US + RX_CB_TO_TX_CMD_DLY_US;
+    inst->durationRespTxDoneTimeout_ms = CEIL_DIV(duration + inst->frameLengths_us[RESP] - inst->storedPreLen_us + margin_us, 1000);	//tx cmd to tx cb
+    inst->durationFinalTxDoneTimeout_ms = CEIL_DIV(duration + inst->frameLengths_us[FINAL] - inst->storedPreLen_us + margin_us, 1000);	//tx cmd to tx cb
 
     //figure maximum duration of a TDMA slot in microseconds
     duration = 0;
     duration += SLOT_START_BUFFER_US;	//frame start buffer
     duration += SLOT_BUFFER_EXP_TO_POLL_CMD_US; //buffer expiration to cmd poll
-    duration += TX_CMD_TO_TX_CB_DLY_US + inst->finalReplyDelay_us + inst->frameLengths_us[FINAL] + RX_TO_CB_DLY_US + RX_CB_TO_TX_CMD_DLY_US;//poll cmd to place final
+    duration += TX_CMD_TO_TX_CB_DLY_US + pollTxToFinalTx + inst->frameLengths_us[FINAL] + RX_TO_CB_DLY_US + RX_CB_TO_TX_CMD_DLY_US;//poll cmd to place final
     //duration += B //place final to cmd report
     duration += TX_CMD_TO_TX_CB_DLY_US + inst->frameLengths_us[REPORT] + RX_TO_CB_DLY_US + RX_CB_TO_TX_CMD_DLY_US; //cmd report to place report
     //duration += C //place report to cmd inf
@@ -1330,25 +1378,6 @@ void instance_init_timings(void)
     inst->durationWaitRangeInit_ms = CEIL_DIV(duration, 1000);
 
 
-    duration = 0;
-    //get max FL
-    uint8 maxFramelength = (uint8)MIN_FRAMELENGTH;
-	while(maxFramelength < (int)UWB_LIST_SIZE + 1)
-	{
-		maxFramelength *= 2;
-	}
-
-	uint8 numExchanges = 0;
-	for(int i = 1; i < UWB_LIST_SIZE; i++)
-	{
-		numExchanges += i;
-	}
-
-	uint8 numZero = numExchanges/(maxFramelength-1);
-
-    inst->durationUwbCommTimeout_ms = (numExchanges + numZero + 1)*CEIL_DIV(inst->durationSlotMax_us,1000)*2;
-
-
     // Smart Power is automatically applied by DW chip for frame of which length
 	// is < 1 ms. Let the application know if it will be used depending on the
 	// length of the longest frame.
diff --git a/src/application/instance.h b/src/application/instance.h
index 3a10da4..5933389 100644
--- a/src/application/instance.h
+++ b/src/application/instance.h
@@ -57,8 +57,10 @@ typedef struct
 	uint64 finalReplyDelay_us;
 	uint64 respReplyDelay;
 
-	//Receive Frame Wait Timeout Periods, units are 1.0256us (aus stands for near microsecond)
+	//Receive Frame Wait Timeout Periods, units are 1.0256us (nus stands for near microsecond)
 	uint16 durationPollTimeout_nus;		//rx timeout duration after tx poll
+	uint16 durationPollTimeout_ms;		//rx timeout duration after tx poll
+	uint16 durationFinalTimeout_ms;     //rx timeout duration after tx final
 
 	uint32 durationBlinkTxDoneTimeout_ms;   	//tx done timeout after tx blink
 	uint32 durationRngInitTxDoneTimeout_ms;   	//tx done timeout after tx rng_init
@@ -150,6 +152,8 @@ typedef struct
 	uint8 uwbList[UWB_LIST_SIZE][8];		//index 0 reserved for self, rest for other tracked uwbs
 
 	uint32 timeofTx;						//used to calculate tx done callback timeouts
+	uint32 timeofTxPoll;                    //used to calculate rx timeout after poll
+	uint32 timeofTxFinal;                   //used to calculate rx timeout after final
 	uint32 txDoneTimeoutDuration;			//duration used for tx done callback timeouts. (set differently for each tx message)
 
 	bool tx_poll;							//was the last tx message a POLL message?
diff --git a/src/application/instance_common.c b/src/application/instance_common.c
index 9005a6f..58303fd 100644
--- a/src/application/instance_common.c
+++ b/src/application/instance_common.c
@@ -1329,6 +1329,11 @@ void instance_rxgoodcallback(const dwt_cb_data_t *rxd)
 			}
 			else if(dw_event.msgu.frame[fcode_index] == RTLS_DEMO_MSG_ANCH_RESP)
 			{
+				//if we have received a response, it's too late in the slot to try and poll with someone else in case we dont finish the exchange
+				//however, if the full exchange doesn't complete, we still want to broadcast an INF message
+				//set a flag here to indicate that we are past the point of no return
+				tdma_handler.firstPollResponse = TRUE;
+
 				// Embed into Final message: 40-bit pollTXTime,  40-bit respRxTime,  40-bit finalTxTime
 				uint64 tagCalculatedFinalTxTime; // time we should send the response
 				uint64 finalReplyDelay = instance_data[0].respReplyDelay;
@@ -1374,6 +1379,7 @@ void instance_rxgoodcallback(const dwt_cb_data_t *rxd)
 					instance_data[0].tx_final = TRUE;
 					dw_event.typePend = DWT_SIG_TX_PENDING ; // exit this interrupt and notify the application/instance that TX is in progress.
 					instance_data[instance].timeofTx = time_now;
+					instance_data[instance].timeofTxFinal = portGetTickCnt();
 					instance_data[instance].txDoneTimeoutDuration = instance_data[instance].durationFinalTxDoneTimeout_ms;
 				}
 			}
@@ -1458,9 +1464,6 @@ void instance_rxgoodcallback(const dwt_cb_data_t *rxd)
 				instance_data[instance].dwt_final_rx = dw_event.timeStamp;
 			}
 
-			//we received response to our POLL, select oldest range UWB next poll
-			tdma_handler.nthOldest = 1;
-
 			place_event = 1;
 		}
 		else if (rxd_event == DWT_SIG_RX_BLINK)
diff --git a/src/application/tdma_handler.c b/src/application/tdma_handler.c
index 430a95e..f4acbf8 100644
--- a/src/application/tdma_handler.c
+++ b/src/application/tdma_handler.c
@@ -1,7 +1,7 @@
 #include "tdma_handler.h"
 #include "port.h"
 #include "instance.h"
-//#include "lib.h"
+#include "lib.h"
 
 
 extern void usb_run(void);
@@ -24,6 +24,7 @@ static bool slot_transition(struct TDMAHandler *this)
 		{
 			transition = TRUE;
 			this->firstPollSentThisSlot = FALSE;
+			this->firstPollResponse = FALSE;
 			this->firstPollComplete = FALSE;
 			this->secondPollSentThisSlot = FALSE;
 			this->infSentThisSlot = FALSE;
@@ -70,6 +71,7 @@ static bool slot_transition(struct TDMAHandler *this)
 	{
 		this->infSentThisSlot = FALSE;
 		this->firstPollSentThisSlot = FALSE;
+		this->firstPollResponse = FALSE;
 		this->firstPollComplete = FALSE;
 		this->secondPollSentThisSlot = FALSE;
 	}
@@ -431,7 +433,7 @@ static bool tx_select(struct TDMAHandler *this)
 			this->firstPollSentThisSlot = TRUE;
 			inst->testAppState = TA_TXPOLL_WAIT_SEND;
 		}
-		else if(this->secondPollSentThisSlot == FALSE && this->firstPollComplete == FALSE)
+		else if(this->secondPollSentThisSlot == FALSE && this->firstPollComplete == FALSE && this->firstPollResponse == FALSE)
 		{
 			this->secondPollSentThisSlot = TRUE;
 			inst->testAppState = TA_TXPOLL_WAIT_SEND;
@@ -596,19 +598,15 @@ static void update_inf_tsfs(struct TDMAHandler *this)
 
 
 //General procedure for processing INF SUG, INF REG, and INF UPDATE (NOTE: slightly different for each INF_PROCESS_MODE)
-//1. Check for differences with locally stored TDMA assignment information
+//1. Check for differences with stored assignments
 //		(a) exit if none exist
-//2. Drop all slot assignments for self, neighbor, hidden, and twice hidden nodes that appear
+//2. Drop stored assignments for self, neighbor, hidden, and twice hidden nodes that appear
 //	 in the INF message
 //3. Copy all assignments for self, neighbors, hidden, and twice hidden nodes that appear
 //	 in the INF message
-//4. Check for conflicts with slot assignments for nodes not contained in the INF message.
-//		(a) if conflicts exist and self node is one of the conflicts, release all slot assignments
-//			from self and follow the procedure for a new node (Section 1.1), skipping the
-//			collect INF REG step.
-//		(b) if conflicts exist and node is not one of the conflicts, deconflict according to 1.2
-//5. Send INF UPDATE message at beginning of allocated slot (handled elsewhere)
-//process types... 1.) clear all and copy 2.) clear mentioned, copy 3.) copy
+//4. Check for conflicts between nodes in the INF message and nodes not in the INF message (excluding self) and deconflict using PDS
+//5. Release self slot assignments and follow PSA
+//6. Send INF message at beginning of allocated slot (handled elsewhere)
 //returns TRUE if a change was made to the TDMA assingments, FALSE if invalid message FCODE or process mode or if no TDMA changes made
 static bool process_inf_msg(struct TDMAHandler *this, uint8 *messageData, uint8 srcIndex, INF_PROCESS_MODE mode)
 {
@@ -884,16 +882,14 @@ static bool process_inf_msg(struct TDMAHandler *this, uint8 *messageData, uint8
 			}
 		}
 
-		//check if self has any conflicts
-		if(this->self_conflict(this))
+		if(tdma_modified == TRUE)
 		{
+
 			//if so, release all assignments from self
 			this->free_slots(&this->uwbListTDMAInfo[0]);
 
 			//find self a new slot assignment
 			this->find_assign_slot(this);
-
-			tdma_modified = TRUE;
 		}
 	}
 
@@ -985,10 +981,6 @@ static bool assign_slot(struct TDMAInfo *info, uint8 slot, bool safeAssign)
 //4.) Double the Frame (DF)
 //		applicable if 2.) and 3.) not applicable
 //		double own framelength and go back to 2.)
-
-//procedure above doesn't seem to alwasy work, even for 3 UWBs... each assigned a slot out of four
-//1,2,3 find no slots to assign and 4 wont change that... will just double the frame forever...
-//actually it should work, because when we have double the framelength, the other uwbs virtually have two slots...
 static void find_assign_slot(struct TDMAHandler *this)
 {
 
@@ -1743,6 +1735,7 @@ static void set_discovery_mode(struct TDMAHandler *this, DISCOVERY_MODE discover
 			this->discovery_mode_duration = (uint32)(get_dt64(time_now_us, latest_tnext)/1000);
 			this->discovery_mode_expires = TRUE;
 
+			this->free_slots(&this->uwbListTDMAInfo[0]);
 			this->deconflict_slot_assignments(this);
 			//assign self slot
 			this->find_assign_slot(this);
@@ -1828,37 +1821,42 @@ static bool check_timeouts(struct TDMAHandler *this)
 	bool updateINF = FALSE;
 	bool noNeighbors = FALSE;
 
+	uint8 max_framelength = 4;
+	for(int i=0; i < inst->uwbListLen; i++)
+	{
+		struct TDMAInfo *info = &this->uwbListTDMAInfo[i];
+		if (info->connectionType != UWB_LIST_SELF && info->connectionType != UWB_LIST_INACTIVE)
+		{
+			if(info->framelength > max_framelength)
+			{
+				max_framelength = info->framelength;
+			}
+		}
+	}
+	inst->durationUwbCommTimeout_ms = 2*max_framelength*CEIL_DIV(inst->durationSlotMax_us,1000);
 
 
 	for(int i=1; i < inst->uwbListLen; i++)//0 reserved for self, timeout not applicable
 	{
 		struct TDMAInfo *info = &this->uwbListTDMAInfo[i];
+		if(info->connectionType == UWB_LIST_INACTIVE)
+		{
+			continue;
+		}
 
 		switch (info->connectionType)
 		{
 			case UWB_LIST_NEIGHBOR:
 			{
+
+
+
 				delta_t = get_dt32(info->lastCommNeighbor, portGetTickCnt()); //get time now here in case rx interrupt occurs before get_dt call
 
 				if(delta_t > inst->durationUwbCommTimeout_ms)
 				{
-					if(info->lastCommHidden != 0)
-					{
-						info->connectionType = UWB_LIST_HIDDEN;
-						updateINF = TRUE;
-					}
-					else if(info->lastCommTwiceHidden != 0)
-					{
-						info->connectionType = UWB_LIST_TWICE_HIDDEN;
-						updateINF = TRUE;
-					}
-					else
-					{
-						info->connectionType = UWB_LIST_INACTIVE;
-						updateINF = TRUE;
-						setInactive = TRUE;
-						this->free_slots(info);
-					}
+					info->connectionType = UWB_LIST_HIDDEN;
+					updateINF = TRUE;
 
 					if(instfindnumneighbors(inst) <= 0)
 					{
@@ -1879,18 +1877,8 @@ static bool check_timeouts(struct TDMAHandler *this)
 
 				if(delta_t > inst->durationUwbCommTimeout_ms)
 				{
-					if(info->lastCommTwiceHidden != 0)
-					{
-						info->connectionType = UWB_LIST_TWICE_HIDDEN;
-						updateINF = TRUE;
-					}
-					else
-					{
-						info->connectionType = UWB_LIST_INACTIVE;
-						this->free_slots(info);
-						setInactive = TRUE;
-						updateINF = TRUE;
-					}
+					info->connectionType = UWB_LIST_TWICE_HIDDEN;
+					updateINF = TRUE;
 				}
 
 				break;
@@ -1905,6 +1893,9 @@ static bool check_timeouts(struct TDMAHandler *this)
 					this->free_slots(info);
 					setInactive = TRUE;
 					updateINF = TRUE;
+					info->lastCommNeighbor = 0;
+					info->lastCommHidden = 0;
+					info->lastCommTwiceHidden = 0;
 				}
 
 				break;
@@ -1935,7 +1926,6 @@ static bool check_timeouts(struct TDMAHandler *this)
 		this->populate_inf_msg(this, RTLS_DEMO_MSG_INF_UPDATE);
 	}
 
-
 	if(rangingUWBTimeout == TRUE)
 	{
 		inst->uwbToRangeWith = 255;
@@ -2017,6 +2007,7 @@ static struct TDMAHandler new(uint64 slot_duration){
     ret.lastSlotStartTime64 = time_now_us;
     ret.infSentThisSlot = FALSE;
     ret.firstPollSentThisSlot = FALSE;
+    ret.firstPollResponse = FALSE;
     ret.firstPollComplete = FALSE;
     ret.secondPollSentThisSlot = FALSE;
     ret.nthOldest = 1;
@@ -2026,7 +2017,7 @@ static struct TDMAHandler new(uint64 slot_duration){
     ret.infMessageLength = 0;
 
     ret.enter_discovery_mode(&ret);
-    ret.collectInfDuration = ret.maxFramelength*ret.slotDuration_ms*2;
+    ret.collectInfDuration = ret.maxFramelength*ret.slotDuration_ms;
 	ret.waitInfDuration = ret.collectInfDuration;
 	ret.blinkPeriodRand = (uint32)rand()%BLINK_PERIOD_RAND_MS;
 
diff --git a/src/application/tdma_handler.h b/src/application/tdma_handler.h
index 51b2333..bda68eb 100644
--- a/src/application/tdma_handler.h
+++ b/src/application/tdma_handler.h
@@ -48,6 +48,7 @@ struct TDMAHandler
 	uint32 slotDuration_us;
 	bool infSentThisSlot;
 	bool firstPollSentThisSlot;
+	bool firstPollResponse;
 	bool firstPollComplete;
 	bool secondPollSentThisSlot;
 	uint8 nthOldest;
-- 
GitLab