Skip to content

Commit b32a44a

Browse files
maass-hamburgcarlescufi
authored andcommitted
net: config: sntp: add periodic resync option
this adds the option to have the clock periodically resynced with the time from the sntp server, instead of just syncing at startup. Signed-off-by: Fin Maaß <[email protected]>
1 parent 0bec7a2 commit b32a44a

File tree

2 files changed

+40
-2
lines changed

2 files changed

+40
-2
lines changed

subsys/net/lib/config/Kconfig

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -238,4 +238,15 @@ config NET_CONFIG_SNTP_INIT_TIMEOUT
238238
int "SNTP timeout to init system clock (ms)"
239239
default 3000
240240

241+
config NET_CONFIG_SNTP_INIT_RESYNC
242+
bool "Resync system clock using SNTP periodically"
243+
help
244+
Perform an SNTP request over networking periodically to get and
245+
absolute wall clock time, and resync system time from it.
246+
247+
config NET_CONFIG_SNTP_INIT_RESYNC_INTERVAL
248+
int "SNTP resync interval (sec)"
249+
depends on NET_CONFIG_SNTP_INIT_RESYNC
250+
default 3600
251+
241252
endif # NET_CONFIG_CLOCK_SNTP_INIT

subsys/net/lib/config/init_clock_sntp.c

Lines changed: 29 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
* SPDX-License-Identifier: Apache-2.0
55
*/
66

7+
#include <zephyr/kernel.h>
78
#include <zephyr/logging/log.h>
89
LOG_MODULE_DECLARE(net_config, CONFIG_NET_CONFIG_LOG_LEVEL);
910

@@ -12,6 +13,11 @@ LOG_MODULE_DECLARE(net_config, CONFIG_NET_CONFIG_LOG_LEVEL);
1213
#include <zephyr/net/sntp.h>
1314
#include <zephyr/posix/time.h>
1415

16+
#ifdef CONFIG_NET_CONFIG_SNTP_INIT_RESYNC
17+
static void sntp_resync_handler(struct k_work *work);
18+
static K_WORK_DELAYABLE_DEFINE(sntp_resync_work_handle, sntp_resync_handler);
19+
#endif
20+
1521
static int sntp_init_helper(struct sntp_time *tm)
1622
{
1723
#ifdef CONFIG_NET_CONFIG_SNTP_INIT_SERVER_USE_DHCPV4_OPTION
@@ -39,12 +45,33 @@ int net_init_clock_via_sntp(void)
3945

4046
if (res < 0) {
4147
LOG_ERR("Cannot set time using SNTP");
42-
return res;
48+
goto end;
4349
}
4450

4551
tspec.tv_sec = ts.seconds;
4652
tspec.tv_nsec = ((uint64_t)ts.fraction * (1000 * 1000 * 1000)) >> 32;
4753
res = clock_settime(CLOCK_REALTIME, &tspec);
4854

49-
return 0;
55+
end:
56+
#ifdef CONFIG_NET_CONFIG_SNTP_INIT_RESYNC
57+
k_work_reschedule(&sntp_resync_work_handle,
58+
K_SECONDS(CONFIG_NET_CONFIG_SNTP_INIT_RESYNC_INTERVAL));
59+
#endif
60+
return res;
61+
}
62+
63+
#ifdef CONFIG_NET_CONFIG_SNTP_INIT_RESYNC
64+
static void sntp_resync_handler(struct k_work *work)
65+
{
66+
int res;
67+
68+
ARG_UNUSED(work);
69+
70+
res = net_init_clock_via_sntp();
71+
if (res < 0) {
72+
LOG_ERR("Cannot resync time using SNTP");
73+
return;
74+
}
75+
LOG_DBG("Time resynced using SNTP");
5076
}
77+
#endif /* CONFIG_NET_CONFIG_SNTP_INIT_RESYNC */

0 commit comments

Comments
 (0)