Statistics
| Branch: | Tag: | Revision:

mongoose / examples / coap_server / coap_server.c @ eaef5bd1

History | View | Annotate | Download (1.73 KB)

1
/*
2
 * Copyright (c) 2015 Cesanta Software Limited
3
 * All rights reserved
4
 *
5
 * This program listens on 5683 for CoAP messages,
6
 * sends ACK is nessesary and dump everything received.
7
 * It is possible to use ../coap_client to send message.
8
 */
9

    
10
#include "mongoose.h"
11

    
12
static char *s_default_address = "udp://:5683";
13
static int s_sig_received = 0;
14

    
15
static void signal_handler(int sig_num) {
16
  signal(sig_num, signal_handler);
17
  s_sig_received = sig_num;
18
}
19

    
20
static void coap_handler(struct mg_connection *nc, int ev, void *p) {
21
  switch (ev) {
22
    case MG_EV_COAP_CON: {
23
      uint32_t res;
24
      struct mg_coap_message *cm = (struct mg_coap_message *) p;
25
      printf("CON with msg_id = %d received\n", cm->msg_id);
26
      res = mg_coap_send_ack(nc, cm->msg_id);
27
      if (res == 0) {
28
        printf("Successfully sent ACK for message with msg_id = %d\n",
29
               cm->msg_id);
30
      } else {
31
        printf("Error: %d\n", res);
32
      }
33
      break;
34
    }
35
    case MG_EV_COAP_NOC:
36
    case MG_EV_COAP_ACK:
37
    case MG_EV_COAP_RST: {
38
      struct mg_coap_message *cm = (struct mg_coap_message *) p;
39
      printf("ACK/RST/NOC with msg_id = %d received\n", cm->msg_id);
40
      break;
41
    }
42
  }
43
}
44

    
45
int main(void) {
46
  struct mg_mgr mgr;
47
  struct mg_connection *nc;
48

    
49
  signal(SIGTERM, signal_handler);
50
  signal(SIGINT, signal_handler);
51

    
52
  mg_mgr_init(&mgr, 0);
53

    
54
  nc = mg_bind(&mgr, s_default_address, coap_handler);
55
  if (nc == NULL) {
56
    printf("Unable to start listener at %s\n", s_default_address);
57
    return -1;
58
  }
59

    
60
  printf("Listening for CoAP messages at %s\n", s_default_address);
61

    
62
  mg_set_protocol_coap(nc);
63

    
64
  while (!s_sig_received) {
65
    mg_mgr_poll(&mgr, 1000000);
66
  }
67

    
68
  printf("Exiting on signal %d\n", s_sig_received);
69

    
70
  mg_mgr_free(&mgr);
71
  return 0;
72
}