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 
separate_get(struct coap_resource * resource,struct coap_packet * request,struct sockaddr * addr,socklen_t addr_len)14 static int separate_get(struct coap_resource *resource,
15 			struct coap_packet *request,
16 			struct sockaddr *addr, socklen_t addr_len)
17 {
18 	uint8_t data[CONFIG_COAP_SERVER_MESSAGE_SIZE];
19 	struct coap_packet response;
20 	uint8_t payload[40];
21 	uint8_t token[COAP_TOKEN_MAX_LEN];
22 	uint16_t id;
23 	uint8_t code;
24 	uint8_t type;
25 	uint8_t tkl;
26 	int r;
27 
28 	code = coap_header_get_code(request);
29 	type = coap_header_get_type(request);
30 	id = coap_header_get_id(request);
31 	tkl = coap_header_get_token(request, token);
32 
33 	LOG_INF("*******");
34 	LOG_INF("type: %u code %u id %u", type, code, id);
35 	LOG_INF("*******");
36 
37 	if (type == COAP_TYPE_ACK) {
38 		return 0;
39 	}
40 
41 	r = coap_ack_init(&response, request, data, sizeof(data), 0);
42 	if (r < 0) {
43 		return r;
44 	}
45 
46 	r = coap_resource_send(resource, &response, addr, addr_len, NULL);
47 	if (r < 0) {
48 		return r;
49 	}
50 
51 	if (type == COAP_TYPE_CON) {
52 		type = COAP_TYPE_CON;
53 	} else {
54 		type = COAP_TYPE_NON_CON;
55 	}
56 
57 	/* Re-use the buffer */
58 	r = coap_packet_init(&response, data, sizeof(data),
59 			     COAP_VERSION_1, type, tkl, token,
60 			     COAP_RESPONSE_CODE_CONTENT, coap_next_id());
61 	if (r < 0) {
62 		return r;
63 	}
64 
65 	r = coap_append_option_int(&response, COAP_OPTION_CONTENT_FORMAT,
66 				   COAP_CONTENT_FORMAT_TEXT_PLAIN);
67 	if (r < 0) {
68 		return r;
69 	}
70 
71 	r = coap_packet_append_payload_marker(&response);
72 	if (r < 0) {
73 		return r;
74 	}
75 
76 	/* The response that coap-client expects */
77 	r = snprintk((char *) payload, sizeof(payload),
78 		     "Type: %u\nCode: %u\nMID: %u\n", type, code, id);
79 	if (r < 0) {
80 		return r;
81 	}
82 
83 	r = coap_packet_append_payload(&response, (uint8_t *)payload,
84 				       strlen(payload));
85 	if (r < 0) {
86 		return r;
87 	}
88 
89 	r = coap_resource_send(resource, &response, addr, addr_len, NULL);
90 
91 	return r;
92 }
93 
94 static const char * const separate_path[] = { "separate", NULL };
95 COAP_RESOURCE_DEFINE(separate, coap_server,
96 {
97 	.get = separate_get,
98 	.path = separate_path,
99 });
100