Created
March 2, 2017 13:52
-
-
Save rojer/88d5e551359c31c4fd98722f0eaf2773 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include "lwip/tcp.h" | |
#include "common/platform.h" | |
#include "fw/src/mgos_app.h" | |
#include "fw/src/mgos_gpio.h" | |
#include "fw/src/mgos_mongoose.h" | |
#include "fw/src/mgos_sys_config.h" | |
#include "fw/src/mgos_hal.h" | |
#define LISTENER_SPEC "8910" | |
static void lc_handler(struct mg_connection *nc, int ev, void *ev_data) { | |
switch (ev) { | |
case MG_EV_ACCEPT: { | |
char addr[32]; | |
mg_sock_addr_to_str(&nc->sa, addr, sizeof(addr), | |
MG_SOCK_STRINGIFY_IP | MG_SOCK_STRINGIFY_PORT); | |
LOG(LL_INFO, ("%p Connection from %s", nc, addr)); | |
mg_printf(nc, "Hello, %s!\r\n", addr); | |
nc->flags |= MG_F_SEND_AND_CLOSE; | |
break; | |
} | |
case MG_EV_SEND: { | |
LOG(LL_INFO, ("%p Data sent", nc)); | |
break; | |
} | |
case MG_EV_CLOSE: { | |
LOG(LL_INFO, ("%p Connection closed", nc)); | |
break; | |
} | |
} | |
(void) ev_data; | |
} | |
static int init_listener(struct mg_mgr *mgr) { | |
struct mg_bind_opts bopts; | |
memset(&bopts, 0, sizeof(bopts)); | |
LOG(LL_INFO, ("Listening on %s", LISTENER_SPEC)); | |
struct mg_connection *lc = mg_bind_opt(mgr, LISTENER_SPEC, lc_handler, bopts); | |
if (lc == NULL) { | |
LOG(LL_ERROR, ("Failed to create listener")); | |
return 0; | |
} | |
return 1; | |
} | |
struct tcp_pcb *tcp_active_pcbs; | |
struct tcp_pcb *tcp_tw_pcbs; | |
static void handle_index(struct mg_connection *nc, int ev, void *ev_data) { | |
struct http_message *hm = (struct http_message *) ev_data; | |
nc->flags |= MG_F_SEND_AND_CLOSE; | |
char addr[32]; | |
mg_sock_addr_to_str(&nc->sa, addr, sizeof(addr), | |
MG_SOCK_STRINGIFY_IP | MG_SOCK_STRINGIFY_PORT); | |
mg_printf(nc, | |
"HTTP/1.0 200 OK\r\n" | |
"Content-Type: text/plain\r\n" | |
"\r\n" | |
"Hello %s!\r\n" | |
"You asked for %.*s\r\n\r\n", | |
addr, (int) hm->uri.len, hm->uri.p); | |
struct tcp_pcb *p; | |
int na = 0, ntw = 0; | |
for (p = tcp_active_pcbs; p != NULL; p = p->next) { | |
na++; | |
} | |
for (p = tcp_tw_pcbs; p != NULL; p = p->next) { | |
ntw++; | |
} | |
mg_printf(nc, "{\"ram_free\":%d} %d %d", mgos_get_free_heap_size(), na, ntw); | |
(void) ev; | |
} | |
enum mgos_app_init_result mgos_app_init(void) { | |
if (!init_listener(mgos_get_mgr())) return MGOS_APP_INIT_ERROR; | |
mgos_register_http_endpoint("/*" /* Handle all requests */, handle_index); | |
return MGOS_APP_INIT_SUCCESS; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment