1#include <string.h>
2#include <stdint.h>
3
4#include "net/gcoap.h"
5#include "net/ipv6/addr.h"
6#include "feucht.h"
7
8#include "arpa/inet.h"
9#include "byteorder.h"
10
11/**
12 * CoAP destination endpoint.
13 */
14static sock_udp_ep_t ep;
15
16/**
17 * End point for updating humidity values.
18 */
19#define HUMIDITY_PATH "/humidity"
20
21static void _resp_handler(unsigned req_state, coap_pkt_t* pdu,
22 sock_udp_ep_t *remote)
23{
24 (void)remote;
25
26 if (req_state == GCOAP_MEMO_TIMEOUT) {
27 printf("gcoap: timeout for msg ID %02u\n", coap_get_id(pdu));
28 return;
29 } else if (req_state == GCOAP_MEMO_ERR) {
30 puts("gcoap: error in response");
31 return;
32 }
33
34 if (coap_get_code_class(pdu) == COAP_CLASS_SUCCESS)
35 puts("Humidity has been updated!");
36 else
37 puts("gcoap: error response class");
38}
39
40int
41init_protocol(ipv6_addr_t *remote)
42{
43 ep.family = AF_INET6;
44 ep.netif = SOCK_ADDR_ANY_NETIF;
45 ep.port = FEUCHT_PORT;
46
47 memcpy(&ep.addr.ipv6[0], &remote->u8[0], sizeof(remote->u8));
48 return 0;
49}
50
51void
52free_protocol(void)
53{
54 return;
55}
56
57int
58update_humidity(char *buf, size_t count)
59{
60 ssize_t len;
61 coap_pkt_t pdu;
62 uint8_t pbuf[GCOAP_PDU_BUF_SIZE];
63
64 if (gcoap_req_init(&pdu, pbuf, GCOAP_PDU_BUF_SIZE, 2, HUMIDITY_PATH))
65 return -ENOMEM;
66 memcpy(pdu.payload, buf, count);
67
68 coap_hdr_set_type(pdu.hdr, COAP_TYPE_CON);
69 if ((len = gcoap_finish(&pdu, count, COAP_FORMAT_TEXT)) < 0)
70 return len;
71
72 if (!gcoap_req_send2(pbuf, len, &ep, _resp_handler))
73 return -EIO;
74
75 return 0;
76}