forked from 1248/microcoap
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main-posix.c
71 lines (59 loc) · 1.68 KB
/
main-posix.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdbool.h>
#include <strings.h>
#include "coap.h"
#define PORT 5683
int main(int argc, char **argv)
{
int fd;
struct sockaddr_in servaddr, cliaddr;
uint8_t buf[4096];
uint8_t scratch_raw[4096];
coap_rw_buffer_t scratch_buf = {scratch_raw, sizeof(scratch_raw)};
fd = socket(AF_INET,SOCK_DGRAM,0);
bzero(&servaddr,sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(PORT);
bind(fd,(struct sockaddr *)&servaddr, sizeof(servaddr));
endpoint_setup();
while(1)
{
int n, rc;
socklen_t len = sizeof(cliaddr);
coap_packet_t pkt;
n = recvfrom(fd, buf, sizeof(buf), 0, (struct sockaddr *)&cliaddr, &len);
#ifdef DEBUG
printf("Received: ");
coap_dump(buf, n, true);
printf("\n");
#endif
if (0 != (rc = coap_parse(&pkt, buf, n)))
printf("Bad packet rc=%d\n", rc);
else
{
size_t rsplen = sizeof(buf);
coap_packet_t rsppkt;
#ifdef DEBUG
coap_dumpPacket(&pkt);
#endif
coap_handle_req(&scratch_buf, &pkt, &rsppkt);
if (0 != (rc = coap_build(buf, &rsplen, &rsppkt)))
printf("coap_build failed rc=%d\n", rc);
else
{
#ifdef DEBUG
printf("Sending: ");
coap_dump(buf, rsplen, true);
printf("\n");
#endif
#ifdef DEBUG
coap_dumpPacket(&rsppkt);
#endif
sendto(fd, buf, rsplen, 0, (struct sockaddr *)&cliaddr, sizeof(cliaddr));
}
}
}
}