diff --git a/samples/net/sockets/sntp_client/prj.conf b/samples/net/sockets/sntp_client/prj.conf index d1b1568dab5..4b94923895b 100644 --- a/samples/net/sockets/sntp_client/prj.conf +++ b/samples/net/sockets/sntp_client/prj.conf @@ -11,6 +11,7 @@ CONFIG_NET_SHELL=y # Sockets CONFIG_NET_SOCKETS=y +CONFIG_NET_SOCKETS_SERVICE=y CONFIG_ZVFS_POLL_MAX=4 # Network driver config diff --git a/samples/net/sockets/sntp_client/src/main.c b/samples/net/sockets/sntp_client/src/main.c index 7d50bdf7de4..3725f46d91a 100644 --- a/samples/net/sockets/sntp_client/src/main.c +++ b/samples/net/sockets/sntp_client/src/main.c @@ -8,11 +8,18 @@ #include LOG_MODULE_REGISTER(net_sntp_client_sample, LOG_LEVEL_DBG); +#include +#include #include #include #include "net_sample_common.h" +static K_SEM_DEFINE(sntp_async_received, 0, 1); +static void sntp_service_handler(struct net_socket_service_event *pev); + +NET_SOCKET_SERVICE_SYNC_DEFINE_STATIC(service_sntp_async, sntp_service_handler, 1); + int dns_query(const char *host, uint16_t port, int family, int socktype, struct sockaddr *addr, socklen_t *addrlen) { @@ -43,6 +50,27 @@ int dns_query(const char *host, uint16_t port, int family, int socktype, struct return 0; } +static void sntp_service_handler(struct net_socket_service_event *pev) +{ + struct sntp_time s_time; + int rc; + + /* Read the response from the socket */ + rc = sntp_read_async(pev, &s_time); + if (rc != 0) { + LOG_ERR("Failed to read SNTP response (%d)", rc); + return; + } + + /* Close the service */ + sntp_close_async(&service_sntp_async); + + LOG_INF("SNTP Time: %llu (async)", s_time.seconds); + + /* Notify test thread */ + k_sem_give(&sntp_async_received); +} + static void do_sntp(int family) { char *family_str = family == AF_INET ? "IPv4" : "IPv6"; @@ -75,6 +103,26 @@ static void do_sntp(int family) LOG_INF("SNTP Time: %llu", s_time.seconds); + sntp_close(&ctx); + + rv = sntp_init_async(&ctx, &addr, addrlen, &service_sntp_async); + if (rv < 0) { + LOG_ERR("Failed to initialise SNTP context (%d)", rv); + goto end; + } + + rv = sntp_send_async(&ctx); + if (rv < 0) { + LOG_ERR("Failed to send SNTP query (%d)", rv); + goto end; + } + + /* Wait for the response to be received asynchronously */ + rv = k_sem_take(&sntp_async_received, K_MSEC(CONFIG_NET_SAMPLE_SNTP_SERVER_TIMEOUT_MS)); + if (rv < 0) { + LOG_INF("SNTP response timed out (%d)", rv); + } + end: sntp_close(&ctx); }