1 /*
2  * Copyright (c) 2020 Linumiz
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include <zephyr/logging/log.h>
8 
9 #include <zephyr/kernel.h>
10 
11 #include <zephyr/net/net_if.h>
12 #include <zephyr/net/net_core.h>
13 #include <zephyr/net/net_context.h>
14 #include <zephyr/net/net_mgmt.h>
15 
16 static struct net_mgmt_event_callback mgmt_cb;
17 
18 /* Semaphore to indicate a lease has been acquired */
19 static K_SEM_DEFINE(got_address, 0, 1);
20 
handler(struct net_mgmt_event_callback * cb,uint32_t mgmt_event,struct net_if * iface)21 static void handler(struct net_mgmt_event_callback *cb,
22 		    uint32_t mgmt_event,
23 		    struct net_if *iface)
24 {
25 	int i;
26 	bool notified = false;
27 
28 	if (mgmt_event != NET_EVENT_IPV4_ADDR_ADD) {
29 		return;
30 	}
31 
32 	for (i = 0; i < NET_IF_MAX_IPV4_ADDR; i++) {
33 		if (iface->config.ip.ipv4->unicast[i].addr_type !=
34 		    NET_ADDR_DHCP) {
35 			continue;
36 		}
37 
38 		if (!notified) {
39 			k_sem_give(&got_address);
40 			notified = true;
41 		}
42 		break;
43 	}
44 }
45 
46 /**
47  * Start a DHCP client, and wait for a lease to be acquired.
48  */
app_dhcpv4_startup(void)49 void app_dhcpv4_startup(void)
50 {
51 	struct net_if *iface;
52 
53 	net_mgmt_init_event_callback(&mgmt_cb, handler,
54 				     NET_EVENT_IPV4_ADDR_ADD);
55 	net_mgmt_add_event_callback(&mgmt_cb);
56 
57 	iface = net_if_get_default();
58 
59 	net_dhcpv4_start(iface);
60 
61 	/* Wait for a lease */
62 	k_sem_take(&got_address, K_FOREVER);
63 }
64