1 /*
2  * Copyright (c) 2018 Intel Corporation
3  * Copyright (c) 2023 Basalte bv
4  *
5  * SPDX-License-Identifier: Apache-2.0
6  */
7 
8 #include <zephyr/logging/log.h>
9 LOG_MODULE_DECLARE(net_coap_service_sample);
10 
11 #include <zephyr/sys/printk.h>
12 #include <zephyr/net/coap_service.h>
13 
location_query_post(struct coap_resource * resource,struct coap_packet * request,struct sockaddr * addr,socklen_t addr_len)14 static int location_query_post(struct coap_resource *resource,
15 			       struct coap_packet *request,
16 			       struct sockaddr *addr, socklen_t addr_len)
17 {
18 	static const char *const location_query[] = { "first=1",
19 						      "second=2",
20 						      NULL };
21 	uint8_t data[CONFIG_COAP_SERVER_MESSAGE_SIZE];
22 	const char * const *p;
23 	struct coap_packet response;
24 	uint8_t token[COAP_TOKEN_MAX_LEN];
25 	uint16_t id;
26 	uint8_t code;
27 	uint8_t type;
28 	uint8_t tkl;
29 	int r;
30 
31 	code = coap_header_get_code(request);
32 	type = coap_header_get_type(request);
33 	id = coap_header_get_id(request);
34 	tkl = coap_header_get_token(request, token);
35 
36 	LOG_INF("*******");
37 	LOG_INF("type: %u code %u id %u", type, code, id);
38 	LOG_INF("*******");
39 
40 	if (type == COAP_TYPE_CON) {
41 		type = COAP_TYPE_ACK;
42 	} else {
43 		type = COAP_TYPE_NON_CON;
44 	}
45 
46 	r = coap_packet_init(&response, data, sizeof(data),
47 			     COAP_VERSION_1, type, tkl, token,
48 			     COAP_RESPONSE_CODE_CREATED, id);
49 	if (r < 0) {
50 		return r;
51 	}
52 
53 	for (p = location_query; *p; p++) {
54 		r = coap_packet_append_option(&response,
55 					      COAP_OPTION_LOCATION_QUERY,
56 					      *p, strlen(*p));
57 		if (r < 0) {
58 			return r;
59 		}
60 	}
61 
62 	r = coap_resource_send(resource, &response, addr, addr_len, NULL);
63 
64 	return r;
65 }
66 
67 static const char * const location_query_path[] = { "location-query", NULL };
68 COAP_RESOURCE_DEFINE(location_query, coap_server,
69 {
70 	.post = location_query_post,
71 	.path = location_query_path,
72 });
73