samples: net: sntp_client: demonstrate async SNTP

Demonstrate asynchronous SNTP querying in the sample.

Signed-off-by: Jordan Yates <jordan@embeint.com>
This commit is contained in:
Jordan Yates 2025-02-17 22:37:19 +10:00 committed by Carles Cufí
parent 1bc795f8ed
commit 89c4902fb7
2 changed files with 49 additions and 0 deletions

View File

@ -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

View File

@ -8,11 +8,18 @@
#include <zephyr/logging/log.h>
LOG_MODULE_REGISTER(net_sntp_client_sample, LOG_LEVEL_DBG);
#include <zephyr/net/socket.h>
#include <zephyr/net/socket_service.h>
#include <zephyr/net/sntp.h>
#include <arpa/inet.h>
#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);
}