net: sample: Add sntp client sample

This sample demostrates how to use SNTP client library to get the
current time from SNTP/NTP server.

Signed-off-by: Aska Wu <aska.wu@linaro.org>
This commit is contained in:
Aska Wu 2017-09-06 11:40:49 +08:00 committed by Anas Nashif
parent f1e488a488
commit 89f28ac7c8
5 changed files with 124 additions and 0 deletions

View file

@ -0,0 +1,11 @@
# Copyright (c) 2017 Linaro Limited
#
# SPDX-License-Identifier: Apache-2.0
#
BOARD ?= qemu_x86
CONF_FILE ?= prj.conf
include $(ZEPHYR_BASE)/Makefile.inc
include $(ZEPHYR_BASE)/samples/net/common/Makefile.ipstack

View file

@ -0,0 +1,28 @@
# General config
CONFIG_NEWLIB_LIBC=y
# Networking config
CONFIG_NETWORKING=y
CONFIG_NET_IPV4=y
CONFIG_NET_IPV6=y
CONFIG_NET_UDP=y
CONFIG_NET_SHELL=y
# Network driver config
CONFIG_TEST_RANDOM_GENERATOR=y
# Network address config
CONFIG_NET_APP_SETTINGS=y
CONFIG_NET_APP_NEED_IPV4=y
CONFIG_NET_APP_NEED_IPV6=y
CONFIG_NET_APP_MY_IPV4_ADDR="192.0.2.1"
CONFIG_NET_APP_PEER_IPV4_ADDR="192.0.2.2"
CONFIG_NET_APP_MY_IPV6_ADDR="2001:db8::1"
CONFIG_NET_APP_PEER_IPV6_ADDR="2001:db8::2"
# Network debug config
CONFIG_NET_LOG=y
# SNTP
CONFIG_SNTP=y
CONFIG_NET_DEBUG_SNTP=y

View file

@ -0,0 +1,8 @@
sample:
description: SNTP client sample
name: sntp_client
tests:
- test:
build_only: true
platform_whitelist: qemu_x86
tags: net

View file

@ -0,0 +1,6 @@
# Copyright (c) 2017 Linaro Limited
#
# SPDX-License-Identifier: Apache-2.0
#
obj-y += main.o

View file

@ -0,0 +1,71 @@
/*
* Copyright (c) 2017 Linaro Limited
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <zephyr.h>
#include <misc/printk.h>
#include <net/sntp.h>
#define SNTP_PORT 123
struct k_sem sem;
void resp_callback(struct sntp_ctx *ctx,
int status,
u64_t epoch_time,
void *user_data)
{
printk("time: %lld\n", epoch_time);
printk("status: %d\n", status);
printk("user_data: %p\n", user_data);
k_sem_give(&sem);
}
void main(void)
{
struct sntp_ctx ctx;
int rv;
k_sem_init(&sem, 0, 1);
/* ipv4 */
rv = sntp_init(&ctx,
CONFIG_NET_APP_PEER_IPV4_ADDR,
SNTP_PORT,
K_FOREVER);
if (rv < 0) {
printk("Failed to init sntp ctx: %d\n", rv);
return;
}
rv = sntp_request(&ctx, K_FOREVER, resp_callback, NULL);
if (rv < 0) {
printk("Failed to send sntp request: %d\n", rv);
return;
}
k_sem_take(&sem, K_FOREVER);
sntp_close(&ctx);
/* ipv6 */
rv = sntp_init(&ctx,
CONFIG_NET_APP_PEER_IPV6_ADDR,
SNTP_PORT,
K_NO_WAIT);
if (rv < 0) {
printk("Failed to initi sntp ctx: %d\n", rv);
return;
}
rv = sntp_request(&ctx, K_NO_WAIT, resp_callback, NULL);
if (rv < 0) {
printk("Failed to send sntp request: %d\n", rv);
return;
}
k_sem_take(&sem, K_FOREVER);
sntp_close(&ctx);
}