1 /*
2  * Copyright (c) 2024 Nordic Nordic Semiconductor ASA
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include <zephyr/logging/log.h>
8 LOG_MODULE_REGISTER(net_samples_common, LOG_LEVEL_DBG);
9 
10 #include <zephyr/net/conn_mgr_connectivity.h>
11 #include <zephyr/net/conn_mgr_monitor.h>
12 
13 #if defined(CONFIG_NET_CONNECTION_MANAGER)
14 #if defined(CONFIG_NET_SAMPLE_COMMON_WAIT_DNS_SERVER_ADDITION)
15 #define L4_EVENT_MASK (NET_EVENT_DNS_SERVER_ADD | NET_EVENT_L4_DISCONNECTED)
16 #else
17 #define L4_EVENT_MASK (NET_EVENT_L4_CONNECTED | NET_EVENT_L4_DISCONNECTED)
18 #endif
19 
20 static struct net_mgmt_event_callback l4_cb;
21 static K_SEM_DEFINE(network_connected, 0, 1);
22 
l4_event_handler(struct net_mgmt_event_callback * cb,uint64_t event,struct net_if * iface)23 static void l4_event_handler(struct net_mgmt_event_callback *cb, uint64_t event,
24 			     struct net_if *iface)
25 {
26 	switch (event) {
27 #if defined(CONFIG_NET_SAMPLE_COMMON_WAIT_DNS_SERVER_ADDITION)
28 	case NET_EVENT_DNS_SERVER_ADD:
29 #else
30 	case NET_EVENT_L4_CONNECTED:
31 #endif
32 		LOG_INF("Network connectivity established and IP address assigned");
33 		k_sem_give(&network_connected);
34 		break;
35 	case NET_EVENT_L4_DISCONNECTED:
36 		break;
37 	default:
38 		break;
39 	}
40 }
41 
wait_for_network(void)42 void wait_for_network(void)
43 {
44 	net_mgmt_init_event_callback(&l4_cb, l4_event_handler, L4_EVENT_MASK);
45 	net_mgmt_add_event_callback(&l4_cb);
46 	conn_mgr_mon_resend_status();
47 
48 	LOG_INF("Waiting for network...");
49 
50 	k_sem_take(&network_connected, K_FOREVER);
51 }
52 #endif /* CONFIG_NET_CONNECTION_MANAGER */
53