Statistics
| Branch: | Tag: | Revision:

mongoose / examples / connected_device_2 / server.c @ eaef5bd1

History | View | Annotate | Download (2.17 KB)

1
// Copyright (c) 2015 Cesanta Software Limited
2
// All rights reserved
3

    
4
#include "mongoose.h"
5

    
6
struct device_settings {
7
  char setting1[100];
8
  char setting2[100];
9
};
10

    
11
static const char *s_http_port = "8000";
12
static struct mg_serve_http_opts s_http_server_opts;
13
static struct device_settings s_settings = {"value1", "value2"};
14

    
15
static void handle_save(struct mg_connection *nc, struct http_message *hm) {
16
  // Get form variables and store settings values
17
  mg_get_http_var(&hm->body, "setting1", s_settings.setting1,
18
                  sizeof(s_settings.setting1));
19
  mg_get_http_var(&hm->body, "setting2", s_settings.setting2,
20
                  sizeof(s_settings.setting2));
21

    
22
  // Send response
23
  mg_http_send_redirect(nc, 302, mg_mk_str("/"), mg_mk_str(NULL));
24
}
25

    
26
static void handle_ssi_call(struct mg_connection *nc, const char *param) {
27
  if (strcmp(param, "setting1") == 0) {
28
    mg_printf_html_escape(nc, "%s", s_settings.setting1);
29
  } else if (strcmp(param, "setting2") == 0) {
30
    mg_printf_html_escape(nc, "%s", s_settings.setting2);
31
  }
32
}
33

    
34
static void ev_handler(struct mg_connection *nc, int ev, void *ev_data) {
35
  struct http_message *hm = (struct http_message *) ev_data;
36

    
37
  switch (ev) {
38
    case MG_EV_HTTP_REQUEST:
39
      if (mg_vcmp(&hm->uri, "/save") == 0) {
40
        handle_save(nc, hm);
41
      } else {
42
        mg_serve_http(nc, hm, s_http_server_opts);  // Serve static content
43
      }
44
      break;
45
    case MG_EV_SSI_CALL:
46
      handle_ssi_call(nc, ev_data);
47
      break;
48
    default:
49
      break;
50
  }
51
}
52

    
53
int main(void) {
54
  struct mg_mgr mgr;
55
  struct mg_connection *nc;
56
  cs_stat_t st;
57

    
58
  mg_mgr_init(&mgr, NULL);
59
  nc = mg_bind(&mgr, s_http_port, ev_handler);
60
  if (nc == NULL) {
61
    fprintf(stderr, "Cannot bind to %s\n", s_http_port);
62
    exit(1);
63
  }
64

    
65
  // Set up HTTP server parameters
66
  mg_set_protocol_http_websocket(nc);
67
  s_http_server_opts.document_root = "web_root";  // Set up web root directory
68

    
69
  if (mg_stat(s_http_server_opts.document_root, &st) != 0) {
70
    fprintf(stderr, "%s", "Cannot find web_root directory, exiting\n");
71
    exit(1);
72
  }
73

    
74
  printf("Starting web server on port %s\n", s_http_port);
75
  for (;;) {
76
    mg_mgr_poll(&mgr, 1000);
77
  }
78
  mg_mgr_free(&mgr);
79

    
80
  return 0;
81
}