Statistics
| Branch: | Tag: | Revision:

mongoose / examples / coap_client / coap_client.c @ eaef5bd1

History | View | Annotate | Download (1.72 KB)

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

    
9
#include "mongoose.h"
10

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

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

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

    
51
int main(int argc, char *argv[]) {
52
  struct mg_mgr mgr;
53
  struct mg_connection *nc;
54
  char *address = s_default_address;
55

    
56
  if (argc > 1) {
57
    address = argv[1];
58
  }
59

    
60
  printf("Using %s as CoAP server\n", address);
61

    
62
  mg_mgr_init(&mgr, 0);
63

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

    
70
  mg_set_protocol_coap(nc);
71

    
72
  while (!s_time_to_exit) {
73
    mg_mgr_poll(&mgr, 1000000);
74
  }
75

    
76
  mg_mgr_free(&mgr);
77

    
78
  return 0;
79
}