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:
parent
1bc795f8ed
commit
89c4902fb7
@ -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
|
||||
|
||||
@ -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);
|
||||
}
|
||||
|
||||
Loading…
Reference in New Issue
Block a user