coap_client.c 1.53 KB
Newer Older
1 2 3 4
/*
 * Copyright (c) 2015 Cesanta Software Limited
 * All rights reserved
 *
5
 * This program sends CoAP CON-message to server (coap.me by default)
6 7 8 9 10 11
 * and waits for answer.
 */

#include "mongoose.h"

static int s_time_to_exit = 0;
12
static char *s_default_address = "udp://coap.me:5683";
13 14 15

static void coap_handler(struct mg_connection *nc, int ev, void *p) {
  switch (ev) {
16
    case MG_EV_CONNECT: {
17 18 19 20 21
      struct mg_coap_message cm;
      uint32_t res;

      memset(&cm, 0, sizeof(cm));
      cm.msg_id = 1;
22
      cm.msg_type = MG_COAP_MSG_CON;
23 24 25 26 27 28 29 30 31 32
      printf("Sending CON...\n");
      res = mg_coap_send_message(nc, &cm);
      if (res == 0) {
        printf("Sent CON with msg_id = %d\n", cm.msg_id);
      } else {
        printf("Error: %d\n", res);
        s_time_to_exit = 1;
      }
      break;
    }
33
    case MG_EV_COAP_ACK:
34 35 36
    case MG_EV_COAP_RST: {
      struct mg_coap_message *cm = (struct mg_coap_message *) p;
      printf("ACK/RST for message with msg_id = %d received\n", cm->msg_id);
37 38 39 40 41 42
      s_time_to_exit = 1;
      break;
    }
  }
}

43
int main(int argc, char *argv[]) {
44 45 46 47 48 49 50 51
  struct mg_mgr mgr;
  struct mg_connection *nc;
  char *address = s_default_address;

  if (argc > 1) {
    address = argv[1];
  }

52
  printf("Using %s as CoAP server\n", address);
53 54 55 56 57 58 59 60 61 62 63 64

  mg_mgr_init(&mgr, 0);

  nc = mg_connect(&mgr, address, coap_handler);
  if (nc == NULL) {
    printf("Unable to connect to %s\n", address);
    return -1;
  }

  mg_set_protocol_coap(nc);

  while (!s_time_to_exit) {
65
    mg_mgr_poll(&mgr, 1000000);
66 67 68
  }

  mg_mgr_free(&mgr);
69

70 71
  return 0;
}