loragw_sx1302_timestamp.c 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634
  1. /*
  2. / _____) _ | |
  3. ( (____ _____ ____ _| |_ _____ ____| |__
  4. \____ \| ___ | (_ _) ___ |/ ___) _ \
  5. _____) ) ____| | | || |_| ____( (___| | | |
  6. (______/|_____)_|_|_| \__)_____)\____)_| |_|
  7. (C)2019 Semtech
  8. Description:
  9. SX1302 timestamp counter Hardware Abstraction Layer
  10. Handles the conversion of a 32-bits 32MHz counter into a 32-bits 1 MHz counter.
  11. This modules MUST be called regularly by the application to maintain counter
  12. wrapping handling for conversion in 1MHz counter.
  13. Provides function to compute the correction to be applied to the received
  14. timestamp for demodulation processing time.
  15. License: Revised BSD License, see LICENSE.TXT file include in the project
  16. */
  17. /* -------------------------------------------------------------------------- */
  18. /* --- DEPENDANCIES --------------------------------------------------------- */
  19. #include <stdint.h> /* C99 types */
  20. #include <stdbool.h> /* boolean type */
  21. #include <stdio.h> /* printf fprintf */
  22. #include <memory.h> /* memset */
  23. #include <inttypes.h> /* PRIx64, PRIu64... */
  24. #include <assert.h>
  25. #include "loragw_sx1302_timestamp.h"
  26. #include "loragw_reg.h"
  27. #include "loragw_aux.h"
  28. /* -------------------------------------------------------------------------- */
  29. /* --- PRIVATE MACROS ------------------------------------------------------- */
  30. #define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
  31. #if DEBUG_FTIME == 1
  32. #define DEBUG_MSG(str) fprintf(stdout, str)
  33. #define DEBUG_PRINTF(fmt, args...) fprintf(stdout, fmt, args)
  34. #define CHECK_NULL(a) if(a==NULL){fprintf(stderr,"%s:%d: ERROR: NULL POINTER AS ARGUMENT\n", __FUNCTION__, __LINE__);return LGW_REG_ERROR;}
  35. #else
  36. #define DEBUG_MSG(str)
  37. #define DEBUG_PRINTF(fmt, args...)
  38. #define CHECK_NULL(a) if(a==NULL){return LGW_REG_ERROR;}
  39. #endif
  40. /* -------------------------------------------------------------------------- */
  41. /* --- PRIVATE TYPES -------------------------------------------------------- */
  42. #define MAX_TIMESTAMP_PPS_HISTORY 16
  43. struct timestamp_pps_history_s {
  44. uint32_t history[MAX_TIMESTAMP_PPS_HISTORY];
  45. uint8_t idx; /* next slot to be written */
  46. uint8_t size; /* current size */
  47. };
  48. /* -------------------------------------------------------------------------- */
  49. /* --- PRIVATE CONSTANTS ---------------------------------------------------- */
  50. #define PRECISION_TIMESTAMP_TS_METRICS_MAX 32 /* reduce number of metrics to better match GW v2 fine timestamp (max is 255) */
  51. #define PRECISION_TIMESTAMP_NB_SYMBOLS 0
  52. /* -------------------------------------------------------------------------- */
  53. /* --- PRIVATE VARIABLES ---------------------------------------------------- */
  54. /* history of the last PPS timestamps */
  55. static struct timestamp_pps_history_s timestamp_pps_history = {
  56. .history = { 0 },
  57. .idx = 0,
  58. .size = 0
  59. };
  60. /* -------------------------------------------------------------------------- */
  61. /* --- PRIVATE FUNCTIONS DECLARATION ---------------------------------------- */
  62. /**
  63. @brief TODO
  64. @param TODO
  65. @return The correction to be applied to the packet timestamp, in microseconds
  66. */
  67. int32_t legacy_timestamp_correction(uint8_t bandwidth, uint8_t datarate, uint8_t coderate, bool no_crc, uint8_t payload_length, sx1302_rx_dft_peak_mode_t dft_peak_mode);
  68. /**
  69. @brief TODO
  70. @param TODO
  71. @return The correction to be applied to the packet timestamp, in microseconds
  72. */
  73. int32_t precision_timestamp_correction(uint8_t bandwidth, uint8_t datarate, uint8_t coderate, bool crc_en, uint8_t payload_length);
  74. /**
  75. @brief TODO
  76. @param TODO
  77. @return The correction to be applied to the packet timestamp, in microseconds
  78. */
  79. void timestamp_pps_history_save(uint32_t timestamp_pps_reg);
  80. /* -------------------------------------------------------------------------- */
  81. /* --- PRIVATE FUNCTIONS DEFINITION ----------------------------------------- */
  82. int32_t legacy_timestamp_correction(uint8_t bandwidth, uint8_t sf, uint8_t cr, bool crc_en, uint8_t payload_length, sx1302_rx_dft_peak_mode_t dft_peak_mode) {
  83. uint64_t clk_period, filtering_delay, demap_delay, fft_delay_state3, fft_delay, decode_delay, total_delay;
  84. uint32_t nb_nibble, nb_nibble_in_hdr, nb_nibble_in_last_block;
  85. uint8_t nb_iter, bw_pow, dft_peak_en = (dft_peak_mode == RX_DFT_PEAK_MODE_DISABLED) ? 0 : 1;
  86. uint8_t ppm = SET_PPM_ON(bandwidth, sf) ? 1 : 0;
  87. int32_t timestamp_correction;
  88. bool payload_fits_in_header = false;
  89. uint8_t cr_local = cr;
  90. switch (bandwidth)
  91. {
  92. case BW_125KHZ:
  93. bw_pow = 1;
  94. break;
  95. case BW_250KHZ:
  96. bw_pow = 2;
  97. break;
  98. case BW_500KHZ:
  99. bw_pow = 4;
  100. break;
  101. default:
  102. printf("ERROR: UNEXPECTED VALUE %d IN SWITCH STATEMENT - %s\n", bandwidth, __FUNCTION__);
  103. return 0;
  104. }
  105. /* Prepare variables for delay computing */
  106. clk_period = 250E3 / bw_pow;
  107. nb_nibble = (payload_length + 2 * crc_en) * 2 + 5;
  108. if ((sf == 5) || (sf == 6)) {
  109. nb_nibble_in_hdr = sf;
  110. } else {
  111. nb_nibble_in_hdr = sf - 2;
  112. }
  113. nb_nibble_in_last_block = nb_nibble - nb_nibble_in_hdr - (sf - 2 * ppm) * ((nb_nibble - nb_nibble_in_hdr) / (sf - 2 * ppm));
  114. if (nb_nibble_in_last_block == 0) {
  115. nb_nibble_in_last_block = sf - 2 * ppm;
  116. }
  117. nb_iter = (sf + 1) / 2; /* intended to be truncated */
  118. /* Update some variables if payload fits entirely in the header */
  119. if (((int)(2 * (payload_length + 2 * crc_en) - (sf - 7)) <= 0) || ((payload_length == 0) && (crc_en == false))) {
  120. /* Payload fits entirely in first 8 symbols (header):
  121. - not possible for SF5/SF6, unless payload length is 0 and no CRC
  122. */
  123. payload_fits_in_header = true;
  124. /* overwrite some variables accordingly */
  125. dft_peak_en = 0;
  126. cr_local = 4; /* header coding rate is 4 */
  127. if (sf > 6) {
  128. nb_nibble_in_last_block = sf - 2;
  129. } else {
  130. nb_nibble_in_last_block = sf;
  131. }
  132. }
  133. /* Filtering delay : I/Q 32Mhz -> 4Mhz */
  134. filtering_delay = 16000E3 / bw_pow + 2031250;
  135. /* demap delay */
  136. if (payload_fits_in_header == true) {
  137. demap_delay = clk_period + (1 << sf) * clk_period * 3 / 4 + 3 * clk_period + (sf - 2) * clk_period;
  138. } else {
  139. demap_delay = clk_period + (1 << sf) * clk_period * (1 - ppm / 4) + 3 * clk_period + (sf - 2 * ppm) * clk_period;
  140. }
  141. /* FFT delays */
  142. fft_delay_state3 = clk_period * (((1 << sf) - 6) + 2 * ((1 << sf) * (nb_iter - 1) + 6)) + 4 * clk_period;
  143. if (dft_peak_en) {
  144. fft_delay = (5 - 2 * ppm) * ((1 << sf) * clk_period + 7 * clk_period) + 2 * clk_period;
  145. } else {
  146. fft_delay = (1 << sf) * 2 * clk_period + 3 * clk_period;
  147. }
  148. /* Decode delay */
  149. decode_delay = 5 * clk_period + (9 * clk_period + clk_period * cr_local) * nb_nibble_in_last_block + 3 * clk_period;
  150. /* Cumulated delays */
  151. total_delay = (filtering_delay + fft_delay_state3 + fft_delay + demap_delay + decode_delay + 500E3) / 1E6;
  152. if (total_delay > INT32_MAX) {
  153. printf("ERROR: overflow error for timestamp correction (SHOULD NOT HAPPEN)\n");
  154. printf("=> filtering_delay %" PRIu64 "\n", filtering_delay);
  155. printf("=> fft_delay_state3 %" PRIu64 "\n", fft_delay_state3);
  156. printf("=> fft_delay %" PRIu64 "\n", fft_delay);
  157. printf("=> demap_delay %" PRIu64 "\n", demap_delay);
  158. printf("=> decode_delay %" PRIu64 "\n", decode_delay);
  159. printf("=> total_delay %" PRIu64 "\n", total_delay);
  160. assert(0);
  161. }
  162. timestamp_correction = -((int32_t)total_delay); /* compensate all decoding processing delays */
  163. DEBUG_PRINTF("FTIME OFF : filtering_delay %llu \n", filtering_delay);
  164. DEBUG_PRINTF("FTIME OFF : fft_delay_state3 %llu \n", fft_delay_state3);
  165. DEBUG_PRINTF("FTIME OFF : fft_delay %llu \n", fft_delay);
  166. DEBUG_PRINTF("FTIME OFF : demap_delay %llu \n", demap_delay);
  167. DEBUG_PRINTF("FTIME OFF : decode_delay %llu \n", decode_delay);
  168. DEBUG_PRINTF("FTIME OFF : timestamp correction %d \n", timestamp_correction);
  169. return timestamp_correction;
  170. }
  171. /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
  172. int32_t precision_timestamp_correction(uint8_t bandwidth, uint8_t datarate, uint8_t coderate, bool crc_en, uint8_t payload_length) {
  173. uint32_t nb_symbols_payload;
  174. uint16_t t_symbol_us;
  175. int32_t timestamp_correction;
  176. uint8_t bw_pow;
  177. uint32_t filtering_delay;
  178. switch (bandwidth)
  179. {
  180. case BW_125KHZ:
  181. bw_pow = 1;
  182. break;
  183. case BW_250KHZ:
  184. bw_pow = 2;
  185. break;
  186. case BW_500KHZ:
  187. bw_pow = 4;
  188. break;
  189. default:
  190. printf("ERROR: UNEXPECTED VALUE %d IN SWITCH STATEMENT - %s\n", bandwidth, __FUNCTION__);
  191. return 0;
  192. }
  193. filtering_delay = 16000000 / bw_pow + 2031250;
  194. /* NOTE: no need of the preamble size, only the payload duration is needed */
  195. /* WARNING: implicit header not supported */
  196. if (lora_packet_time_on_air(bandwidth, datarate, coderate, 0, false, !crc_en, payload_length, NULL, &nb_symbols_payload, &t_symbol_us) == 0) {
  197. printf("ERROR: failed to compute packet time on air - %s\n", __FUNCTION__);
  198. return 0;
  199. }
  200. timestamp_correction = 0;
  201. timestamp_correction += (nb_symbols_payload * t_symbol_us); /* shift from end of header to end of packet */
  202. timestamp_correction -= (filtering_delay + 500E3) / 1E6; /* compensate the filtering delay */
  203. DEBUG_PRINTF("FTIME ON : timestamp correction %d \n", timestamp_correction);
  204. return timestamp_correction;
  205. }
  206. /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
  207. void timestamp_pps_history_save(uint32_t timestamp_pps_reg) {
  208. /* Store it only if different from the previous one */
  209. if ((timestamp_pps_reg != timestamp_pps_history.history[timestamp_pps_history.idx] || (timestamp_pps_history.size == 0))) {
  210. /* Select next index */
  211. if (timestamp_pps_history.size > 0) {
  212. timestamp_pps_history.idx += 1;
  213. }
  214. if (timestamp_pps_history.idx == MAX_TIMESTAMP_PPS_HISTORY) {
  215. timestamp_pps_history.idx = 0;
  216. }
  217. /* Set PPS counter value */
  218. timestamp_pps_history.history[timestamp_pps_history.idx] = timestamp_pps_reg;
  219. /* Add one entry to the history */
  220. if (timestamp_pps_history.size < MAX_TIMESTAMP_PPS_HISTORY) {
  221. timestamp_pps_history.size += 1;
  222. }
  223. #if 0
  224. printf("---- timestamp PPS history (idx:%u size:%u) ----\n", timestamp_pps_history.idx, timestamp_pps_history.size);
  225. for (int i = 0; i < timestamp_pps_history.size; i++) {
  226. printf(" %u\n", timestamp_pps_history.history[i]);
  227. }
  228. printf("--------------------------------\n");
  229. #endif
  230. }
  231. }
  232. /* -------------------------------------------------------------------------- */
  233. /* --- PUBLIC FUNCTIONS DEFINITION ------------------------------------------ */
  234. void timestamp_counter_new(timestamp_counter_t * self) {
  235. memset(self, 0, sizeof(*self));
  236. }
  237. /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
  238. void timestamp_counter_delete(timestamp_counter_t * self) {
  239. memset(self, 0, sizeof(*self));
  240. }
  241. /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
  242. void timestamp_counter_update(timestamp_counter_t * self, uint32_t pps, uint32_t inst) {
  243. //struct timestamp_info_s* tinfo = (pps == true) ? &self->pps : &self->inst;
  244. /* Check if counter has wrapped, and update wrap status if necessary */
  245. if (pps < self->pps.counter_us_27bits_ref) {
  246. self->pps.counter_us_27bits_wrap += 1;
  247. self->pps.counter_us_27bits_wrap %= 32;
  248. }
  249. if (inst < self->inst.counter_us_27bits_ref) {
  250. self->inst.counter_us_27bits_wrap += 1;
  251. self->inst.counter_us_27bits_wrap %= 32;
  252. }
  253. /* Update counter reference */
  254. self->pps.counter_us_27bits_ref = pps;
  255. self->inst.counter_us_27bits_ref = inst;
  256. }
  257. /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
  258. int timestamp_counter_get(timestamp_counter_t * self, uint32_t * inst, uint32_t * pps) {
  259. int x;
  260. uint8_t buff[8];
  261. uint8_t buff_wa[8];
  262. uint32_t counter_inst_us_raw_27bits_now;
  263. uint32_t counter_pps_us_raw_27bits_now;
  264. /* Get the freerun and pps 32MHz timestamp counters - 8 bytes
  265. 0 -> 3 : PPS counter
  266. 4 -> 7 : Freerun counter (inst)
  267. */
  268. x = lgw_reg_rb(SX1302_REG_TIMESTAMP_TIMESTAMP_PPS_MSB2_TIMESTAMP_PPS, &buff[0], 8);
  269. if (x != LGW_REG_SUCCESS) {
  270. printf("ERROR: Failed to get timestamp counter value\n");
  271. return -1;
  272. }
  273. /* Workaround concentrator chip issue:
  274. - read MSB again
  275. - if MSB changed, read the full counter again
  276. */
  277. x = lgw_reg_rb(SX1302_REG_TIMESTAMP_TIMESTAMP_PPS_MSB2_TIMESTAMP_PPS, &buff_wa[0], 8);
  278. if (x != LGW_REG_SUCCESS) {
  279. printf("ERROR: Failed to get timestamp counter MSB value\n");
  280. return -1;
  281. }
  282. if ((buff[0] != buff_wa[0]) || (buff[4] != buff_wa[4])) {
  283. x = lgw_reg_rb(SX1302_REG_TIMESTAMP_TIMESTAMP_PPS_MSB2_TIMESTAMP_PPS, &buff_wa[0], 8);
  284. if (x != LGW_REG_SUCCESS) {
  285. printf("ERROR: Failed to get timestamp counter MSB value\n");
  286. return -1;
  287. }
  288. memcpy(buff, buff_wa, 8); /* use the new read value */
  289. }
  290. counter_pps_us_raw_27bits_now = (buff[0]<<24) | (buff[1]<<16) | (buff[2]<<8) | buff[3];
  291. counter_inst_us_raw_27bits_now = (buff[4]<<24) | (buff[5]<<16) | (buff[6]<<8) | buff[7];
  292. /* Store PPS counter to history, for fine timestamp calculation */
  293. timestamp_pps_history_save(counter_pps_us_raw_27bits_now);
  294. /* Scale to 1MHz */
  295. counter_pps_us_raw_27bits_now /= 32;
  296. counter_inst_us_raw_27bits_now /= 32;
  297. /* Update counter wrapping status */
  298. timestamp_counter_update(self, counter_pps_us_raw_27bits_now, counter_inst_us_raw_27bits_now);
  299. /* Convert 27-bits counter to 32-bits counter */
  300. *inst = timestamp_counter_expand(self, false, counter_inst_us_raw_27bits_now);
  301. *pps = timestamp_counter_expand(self, true, counter_pps_us_raw_27bits_now);
  302. return 0;
  303. }
  304. /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
  305. uint32_t timestamp_counter_expand(timestamp_counter_t * self, bool pps, uint32_t cnt_us) {
  306. struct timestamp_info_s* tinfo = (pps == true) ? &self->pps : &self->inst;
  307. uint32_t counter_us_32bits;
  308. counter_us_32bits = (tinfo->counter_us_27bits_wrap << 27) | cnt_us;
  309. #if 0
  310. /* DEBUG: to be enabled when running test_loragw_counter test application
  311. This generates a CSV log, and can be plotted with gnuplot:
  312. > set datafile separator comma
  313. > plot for [col=1:2:1] 'log_count.txt' using col with lines
  314. */
  315. printf("%u,%u,%u\n", cnt_us, counter_us_32bits, tinfo->counter_us_27bits_wrap);
  316. #endif
  317. return counter_us_32bits;
  318. }
  319. /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
  320. uint32_t timestamp_pkt_expand(timestamp_counter_t * self, uint32_t pkt_cnt_us) {
  321. struct timestamp_info_s* tinfo = &self->inst;
  322. uint32_t counter_us_32bits;
  323. uint8_t wrap_status;
  324. /* Check if counter has wrapped since the packet has been received in the sx1302 internal FIFO */
  325. /* If the sx1302 counter was greater than the pkt timestamp, it means that the internal counter
  326. hasn't rolled over since the packet has been received by the sx1302
  327. case 1: --|-P--|----|--R-|----|--||-|----|-- : use current wrap status counter
  328. case 2: --|-P-||-|-R--|-- : use previous wrap status counter
  329. P : packet received in sx1302 internal FIFO
  330. R : read packet from sx1302 internal FIFO
  331. | : last update internal counter ref value.
  332. ||: sx1302 internal counter rollover (wrap)
  333. */
  334. /* Use current wrap counter or previous ? */
  335. wrap_status = tinfo->counter_us_27bits_wrap - ((tinfo->counter_us_27bits_ref >= pkt_cnt_us) ? 0 : 1);
  336. wrap_status &= 0x1F; /* [0..31] */
  337. /* Expand packet counter */
  338. counter_us_32bits = (wrap_status << 27) | pkt_cnt_us;
  339. return counter_us_32bits;
  340. }
  341. /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
  342. int timestamp_counter_mode(bool ftime_enable) {
  343. int x = LGW_REG_SUCCESS;
  344. if (ftime_enable == false) {
  345. printf("INFO: using legacy timestamp\n");
  346. /* Latch end-of-packet timestamp (sx1301 compatibility) */
  347. x |= lgw_reg_w(SX1302_REG_RX_TOP_RX_BUFFER_LEGACY_TIMESTAMP, 0x01);
  348. } else {
  349. printf("INFO: using precision timestamp (max_ts_metrics:%u nb_symbols:%u)\n", PRECISION_TIMESTAMP_TS_METRICS_MAX, PRECISION_TIMESTAMP_NB_SYMBOLS);
  350. /* Latch end-of-preamble timestamp */
  351. x |= lgw_reg_w(SX1302_REG_RX_TOP_RX_BUFFER_LEGACY_TIMESTAMP, 0x00);
  352. x |= lgw_reg_w(SX1302_REG_RX_TOP_RX_BUFFER_TIMESTAMP_CFG_MAX_TS_METRICS, (int32_t)PRECISION_TIMESTAMP_TS_METRICS_MAX);
  353. /* LoRa multi-SF modems */
  354. x |= lgw_reg_w(SX1302_REG_RX_TOP_TIMESTAMP_ENABLE, 0x01);
  355. x |= lgw_reg_w(SX1302_REG_RX_TOP_TIMESTAMP_NB_SYMB, (int32_t)PRECISION_TIMESTAMP_NB_SYMBOLS);
  356. }
  357. return x;
  358. }
  359. /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
  360. int32_t timestamp_counter_correction(lgw_context_t * context, uint8_t bandwidth, uint8_t datarate, uint8_t coderate, bool crc_en, uint8_t payload_length, sx1302_rx_dft_peak_mode_t dft_peak_mode) {
  361. /* Check input parameters */
  362. CHECK_NULL(context);
  363. if (IS_LORA_DR(datarate) == false) {
  364. printf("ERROR: wrong datarate (%u) - %s\n", datarate, __FUNCTION__);
  365. return 0;
  366. }
  367. if (IS_LORA_BW(bandwidth) == false) {
  368. printf("ERROR: wrong bandwidth (%u) - %s\n", bandwidth, __FUNCTION__);
  369. return 0;
  370. }
  371. if (IS_LORA_CR(coderate) == false) {
  372. printf("ERROR: wrong coding rate (%u) - %s\n", coderate, __FUNCTION__);
  373. return 0;
  374. }
  375. /* Calculate the correction to be applied */
  376. if (context->ftime_cfg.enable == false) {
  377. return legacy_timestamp_correction(bandwidth, datarate, coderate, crc_en, payload_length, dft_peak_mode);
  378. } else {
  379. return precision_timestamp_correction(bandwidth, datarate, coderate, crc_en, payload_length);
  380. }
  381. }
  382. /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
  383. int precise_timestamp_calculate(uint8_t ts_metrics_nb, const int8_t * ts_metrics, uint32_t timestamp_cnt, uint8_t sf, int32_t if_freq_hz, double pkt_freq_error, uint32_t * result_ftime) {
  384. int i, x, timestamp_pps_idx, timestamp_pps_idx_next, timestamp_pps_idx_prev;
  385. int32_t ftime_sum;
  386. int32_t ftime[256];
  387. float ftime_mean;
  388. uint32_t timestamp_cnt_end_of_preamble;
  389. uint32_t timestamp_pps = 0;
  390. uint32_t timestamp_pps_reg = 0;
  391. uint32_t offset_preamble_hdr;
  392. uint8_t buff[4];
  393. uint32_t diff_pps;
  394. double pkt_ftime;
  395. uint8_t ts_metrics_nb_clipped;
  396. double xtal_correct;
  397. /* Check input parameters */
  398. CHECK_NULL(ts_metrics);
  399. CHECK_NULL(result_ftime);
  400. /* Check if we can calculate a ftime */
  401. if (timestamp_pps_history.size < MAX_TIMESTAMP_PPS_HISTORY) {
  402. printf("INFO: Cannot compute ftime yet, PPS history is too short\n");
  403. return -1;
  404. }
  405. /* Coarse timestamp correction to match with GW v2 (end of header -> end of preamble) */
  406. offset_preamble_hdr = 256 * (1 << sf) * (8 + 4 + (((sf == 5) || (sf == 6)) ? 2 : 0)) +
  407. 256 * ((1 << sf) / 4 - 1); /* 32e6 / 125e3 = 256 */
  408. /* Take the packet frequency error in account in the offset */
  409. offset_preamble_hdr += ((double)offset_preamble_hdr * pkt_freq_error + 0.5);
  410. timestamp_cnt_end_of_preamble = timestamp_cnt - offset_preamble_hdr + 2138; /* 2138 is the number of 32MHz clock cycle offset b/w GW_V2 and SX1303 decimation/filtering group delay */
  411. /* Shift the packet coarse timestamp which is used to get ref PPS counter */
  412. timestamp_cnt = timestamp_cnt_end_of_preamble;
  413. /* Clip the number of metrics depending on Spreading Factor, reduce fine timestamp variation versus packet duration */
  414. switch (sf) {
  415. case 12:
  416. ts_metrics_nb_clipped = MIN(4, ts_metrics_nb);
  417. break;
  418. case 11:
  419. ts_metrics_nb_clipped = MIN(8, ts_metrics_nb);
  420. break;
  421. case 10:
  422. ts_metrics_nb_clipped = MIN(16, ts_metrics_nb);
  423. break;
  424. default:
  425. ts_metrics_nb_clipped = MIN(32, ts_metrics_nb);
  426. break;
  427. }
  428. #if 0
  429. printf("%s\n", __FUNCTION__);
  430. printf("ts_metrics_nb_clipped*2: %u\n", ts_metrics_nb_clipped * 2);
  431. for (i = 0; i < (2 * ts_metrics_nb_clipped); i++) {
  432. printf("%d ", ts_metrics[i]);
  433. }
  434. printf("\n");
  435. #endif
  436. /* Compute the ftime cumulative sum */
  437. ftime[0] = (int32_t)ts_metrics[0];
  438. ftime_sum = ftime[0];
  439. for (i = 1; i < (2 * ts_metrics_nb_clipped); i++) {
  440. ftime[i] = ftime[i-1] + ts_metrics[i];
  441. ftime_sum += ftime[i];
  442. }
  443. /* Compute the mean of the cumulative sum */
  444. ftime_mean = (float)ftime_sum / (float)(2 * ts_metrics_nb_clipped);
  445. /* Find the last timestamp_pps before packet to use as reference for ftime */
  446. x = lgw_reg_rb(SX1302_REG_TIMESTAMP_TIMESTAMP_PPS_MSB2_TIMESTAMP_PPS , &buff[0], 4);
  447. if (x != LGW_REG_SUCCESS) {
  448. printf("ERROR: Failed to get timestamp counter value\n");
  449. return 0;
  450. }
  451. timestamp_pps_reg = (uint32_t)((buff[0] << 24) & 0xFF000000);
  452. timestamp_pps_reg |= (uint32_t)((buff[1] << 16) & 0x00FF0000);
  453. timestamp_pps_reg |= (uint32_t)((buff[2] << 8) & 0x0000FF00);
  454. timestamp_pps_reg |= (uint32_t)((buff[3] << 0) & 0x000000FF);
  455. /* Ensure that the timestamp PPS history is up-to-date */
  456. timestamp_pps_history_save(timestamp_pps_reg);
  457. /* Check if timestamp_pps_reg we just read is the reference to be used to compute ftime or not */
  458. if ((timestamp_cnt - timestamp_pps_reg) > 32e6) {
  459. /* The timestamp_pps_reg we just read is after the packet timestamp, we need to rewind */
  460. for (timestamp_pps_idx = 0; timestamp_pps_idx < timestamp_pps_history.size; timestamp_pps_idx++) {
  461. /* search the pps counter in history */
  462. if ((timestamp_cnt - timestamp_pps_history.history[timestamp_pps_idx]) < 32e6) {
  463. timestamp_pps = timestamp_pps_history.history[timestamp_pps_idx];
  464. DEBUG_PRINTF("==> timestamp_pps found at history[%d] => %u\n", timestamp_pps_idx, timestamp_pps);
  465. break;
  466. }
  467. }
  468. if (timestamp_pps_idx == timestamp_pps_history.size) {
  469. printf("ERROR: failed to find the reference timestamp_pps, cannot compute ftime\n");
  470. return -1;
  471. }
  472. /* Calculate the Xtal error between the reference PPS we just found and the next one */
  473. timestamp_pps_idx_next = (timestamp_pps_idx == (MAX_TIMESTAMP_PPS_HISTORY - 1)) ? 0 : timestamp_pps_idx + 1;
  474. diff_pps = timestamp_pps_history.history[timestamp_pps_idx_next] - timestamp_pps_history.history[timestamp_pps_idx];
  475. xtal_correct = (double)32e6 / (double)(diff_pps);
  476. } else {
  477. /* The timestamp_pps_reg we just read is the reference we use to calculate the fine timestamp */
  478. timestamp_pps = timestamp_pps_reg;
  479. DEBUG_PRINTF("==> timestamp_pps => %u\n", timestamp_pps);
  480. /* Calculate the Xtal error between the reference PPS we just found and the previous one */
  481. timestamp_pps_idx = timestamp_pps_history.idx;
  482. timestamp_pps_idx_prev = (timestamp_pps_idx == 0) ? (MAX_TIMESTAMP_PPS_HISTORY - 1) : (timestamp_pps_idx - 1);
  483. diff_pps = timestamp_pps_history.history[timestamp_pps_idx] - timestamp_pps_history.history[timestamp_pps_idx_prev];
  484. xtal_correct = (double)32e6 / (double)(diff_pps);
  485. }
  486. /* Sanity Check on xtal_correct */
  487. if ((xtal_correct > 1.2) || (xtal_correct < 0.8)) {
  488. printf("ERROR: xtal_error is invalid (%.15lf)\n", xtal_correct);
  489. return -1;
  490. }
  491. /* Coarse timestamp based on PPS reference */
  492. diff_pps = timestamp_cnt - timestamp_pps;
  493. DEBUG_PRINTF("timestamp_cnt : %u\n", timestamp_cnt);
  494. DEBUG_PRINTF("timestamp_pps : %u\n", timestamp_pps);
  495. DEBUG_PRINTF("diff_pps : %d\n", diff_pps);
  496. /* Compute the fine timestamp */
  497. pkt_ftime = (double)diff_pps + (double)ftime_mean;
  498. DEBUG_PRINTF("pkt_ftime = %f\n", pkt_ftime);
  499. /* Add the DC notch filtering delay if necessary */
  500. pkt_ftime += sx1302_dc_notch_delay((double)if_freq_hz / 1E3);
  501. /* Convert fine timestamp from 32 Mhz clock to nanoseconds */
  502. pkt_ftime *= 31.25;
  503. /* Apply current XTAL error correction */
  504. pkt_ftime *= xtal_correct;
  505. *result_ftime = (uint32_t)pkt_ftime;
  506. if (*result_ftime > 1E9) {
  507. printf("ERROR: fine timestamp is out of range (%u)\n", *result_ftime);
  508. return -1;
  509. }
  510. DEBUG_PRINTF("==> ftime = %u ns since last PPS (%.15lf)\n", *result_ftime, pkt_ftime);
  511. return 0;
  512. }
  513. /* --- EOF ------------------------------------------------------------------ */