|
12 | 12 |
|
13 | 13 | #include <openthread/link_raw.h> |
14 | 14 |
|
| 15 | +#include <zephyr/kernel.h> |
| 16 | + |
| 17 | +#define RADIO_TIME_REFRESH_PERIOD (CONFIG_OPENTHREAD_RPC_CLIENT_RADIO_TIME_REFRESH_PERIOD * 1000000) |
| 18 | + |
| 19 | +static bool sync_radio_time_valid; |
| 20 | +static uint64_t sync_local_time; |
| 21 | +static uint64_t sync_radio_time; |
| 22 | + |
| 23 | +static inline uint64_t get_local_time(void) |
| 24 | +{ |
| 25 | + return k_ticks_to_us_floor64(k_uptime_ticks()); |
| 26 | +} |
| 27 | + |
15 | 28 | uint64_t otLinkRawGetRadioTime(otInstance *aInstance) |
16 | 29 | { |
17 | 30 | struct nrf_rpc_cbor_ctx ctx; |
18 | | - uint64_t time; |
| 31 | + uint64_t now; |
19 | 32 |
|
20 | 33 | ARG_UNUSED(aInstance); |
21 | 34 |
|
22 | | - NRF_RPC_CBOR_ALLOC(&ot_group, ctx, 0); |
23 | | - nrf_rpc_cbor_cmd_rsp_no_err(&ot_group, OT_RPC_CMD_LINK_RAW_GET_RADIO_TIME, &ctx); |
24 | | - |
25 | | - time = nrf_rpc_decode_uint64(&ctx); |
26 | | - |
27 | | - if (!nrf_rpc_decoding_done_and_check(&ot_group, &ctx)) { |
28 | | - ot_rpc_report_rsp_decoding_error(OT_RPC_CMD_LINK_RAW_GET_RADIO_TIME); |
| 35 | + now = get_local_time(); |
| 36 | + |
| 37 | + if (!sync_radio_time_valid || now >= sync_local_time + RADIO_TIME_REFRESH_PERIOD) { |
| 38 | + NRF_RPC_CBOR_ALLOC(&ot_group, ctx, 0); |
| 39 | + nrf_rpc_cbor_cmd_rsp_no_err(&ot_group, OT_RPC_CMD_LINK_RAW_GET_RADIO_TIME, &ctx); |
| 40 | + |
| 41 | + /* |
| 42 | + * Calculate sync_local_time as if the radio time was read by the peer exactly |
| 43 | + * halfway between constructing a request and receiving the response. |
| 44 | + */ |
| 45 | + sync_radio_time_valid = true; |
| 46 | + sync_local_time = now / 2; |
| 47 | + now = get_local_time(); |
| 48 | + sync_local_time += now / 2; |
| 49 | + sync_radio_time = nrf_rpc_decode_uint64(&ctx); |
| 50 | + |
| 51 | + if (!nrf_rpc_decoding_done_and_check(&ot_group, &ctx)) { |
| 52 | + ot_rpc_report_rsp_decoding_error(OT_RPC_CMD_LINK_RAW_GET_RADIO_TIME); |
| 53 | + } |
29 | 54 | } |
30 | 55 |
|
31 | | - return time; |
| 56 | + return sync_radio_time + (now - sync_local_time); |
32 | 57 | } |
0 commit comments