1 /*
2  * Copyright (c) 2023 Basalte bv
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include <zephyr/logging/log.h>
8 LOG_MODULE_REGISTER(net_coap_service_sample, LOG_LEVEL_DBG);
9 
10 #include <zephyr/net/coap_service.h>
11 #include <zephyr/net/mld.h>
12 
13 #ifdef CONFIG_NET_IPV6
14 #include "net_private.h"
15 #include "ipv6.h"
16 #endif
17 
18 #include "net_sample_common.h"
19 
20 static const uint16_t coap_port = 5683;
21 
22 #ifdef CONFIG_NET_IPV6
23 
24 #define ALL_NODES_LOCAL_COAP_MCAST \
25 	{ { { 0xff, 0x02, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xfd } } }
26 
27 #define MY_IP6ADDR \
28 	{ { { 0x20, 0x01, 0x0d, 0xb8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x1 } } }
29 
join_coap_multicast_group(void)30 static int join_coap_multicast_group(void)
31 {
32 	static struct in6_addr my_addr = MY_IP6ADDR;
33 	static struct sockaddr_in6 mcast_addr = {
34 		.sin6_family = AF_INET6,
35 		.sin6_addr = ALL_NODES_LOCAL_COAP_MCAST,
36 		.sin6_port = htons(coap_port) };
37 	struct net_if_addr *ifaddr;
38 	struct net_if *iface;
39 	int ret;
40 
41 	iface = net_if_get_default();
42 	if (!iface) {
43 		LOG_ERR("Could not get the default interface");
44 		return -ENOENT;
45 	}
46 
47 #if defined(CONFIG_NET_CONFIG_SETTINGS)
48 	if (net_addr_pton(AF_INET6,
49 			  CONFIG_NET_CONFIG_MY_IPV6_ADDR,
50 			  &my_addr) < 0) {
51 		LOG_ERR("Invalid IPv6 address %s",
52 			CONFIG_NET_CONFIG_MY_IPV6_ADDR);
53 	}
54 #endif
55 
56 	ifaddr = net_if_ipv6_addr_add(iface, &my_addr, NET_ADDR_MANUAL, 0);
57 	if (!ifaddr) {
58 		LOG_ERR("Could not add unicast address to interface");
59 		return -EINVAL;
60 	}
61 
62 	ifaddr->addr_state = NET_ADDR_PREFERRED;
63 
64 	ret = net_ipv6_mld_join(iface, &mcast_addr.sin6_addr);
65 	if (ret < 0) {
66 		LOG_ERR("Cannot join %s IPv6 multicast group (%d)",
67 			net_sprint_ipv6_addr(&mcast_addr.sin6_addr), ret);
68 		return ret;
69 	}
70 
71 	return 0;
72 }
73 
main(void)74 int main(void)
75 {
76 	wait_for_network();
77 
78 	return join_coap_multicast_group();
79 }
80 
81 #else /* CONFIG_NET_IPV6 */
82 
main(void)83 int main(void)
84 {
85 	wait_for_network();
86 
87 	return 0;
88 }
89 
90 #endif /* CONFIG_NET_IPV6 */
91 
92 COAP_SERVICE_DEFINE(coap_server, NULL, &coap_port, COAP_SERVICE_AUTOSTART);
93