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

#include "mongoose.h"

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

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

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

45
int main(void) {
46 47 48 49 50 51 52 53 54 55 56 57 58 59
  struct mg_mgr mgr;
  struct mg_connection *nc;

  signal(SIGTERM, signal_handler);
  signal(SIGINT, signal_handler);

  mg_mgr_init(&mgr, 0);

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

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

  mg_set_protocol_coap(nc);

  while (!s_sig_received) {
65
    mg_mgr_poll(&mgr, 1000000);
66 67 68 69 70 71 72
  }

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

  mg_mgr_free(&mgr);
  return 0;
}