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