|
| 1 | +#include "mongoose.h" |
| 2 | +#include "WiFi.h" |
| 3 | + |
| 4 | +#define LED_PIN LED_BUILTIN |
| 5 | +#define WIFI_SSID "wifi_network_name" // Change this |
| 6 | +#define WIFI_PASS "wifi_password" // And this |
| 7 | + |
| 8 | +struct mg_mgr mgr; |
| 9 | + |
| 10 | +// Crude function to get available RAM, for quick profiling |
| 11 | +size_t getFreeRAM(void) { |
| 12 | + size_t size = 0, increment = 1024; |
| 13 | + void *p; |
| 14 | + while ((p = malloc(size)) != NULL) free(p), size += increment; |
| 15 | + return size; |
| 16 | +} |
| 17 | + |
| 18 | +void http_ev_handler(struct mg_connection *c, int ev, void *ev_data) { |
| 19 | + if (ev == MG_EV_HTTP_MSG) { |
| 20 | + struct mg_http_message *hm = (struct mg_http_message *)ev_data; |
| 21 | + if (mg_match(hm->uri, mg_str("/api/led/on"), NULL)) { |
| 22 | + digitalWrite(LED_PIN, HIGH); |
| 23 | + mg_http_reply(c, 200, "", "{%m: %d}\n", MG_ESC("led"), digitalRead(LED_PIN)); |
| 24 | + } else if (mg_match(hm->uri, mg_str("/api/led/off"), NULL)) { |
| 25 | + digitalWrite(LED_PIN, LOW); |
| 26 | + mg_http_reply(c, 200, "", "{%m: %d}\n", MG_ESC("led"), digitalRead(LED_PIN)); |
| 27 | + } else { |
| 28 | + mg_http_reply(c, 200, "", "ok, free RAM: %u\n", xPortGetFreeHeapSize()); |
| 29 | + } |
| 30 | + } |
| 31 | +} |
| 32 | + |
| 33 | +void setup() { |
| 34 | + pinMode(LED_PIN, OUTPUT); |
| 35 | + Serial.begin(115200); |
| 36 | + while (!Serial) delay(50); |
| 37 | + |
| 38 | + WiFi.mode(WIFI_STA); |
| 39 | + WiFi.begin(WIFI_SSID, WIFI_PASS); |
| 40 | + while(WiFi.status() != WL_CONNECTED) Serial.print("."), delay(100); |
| 41 | + |
| 42 | + Serial.println("\nConnected to the WiFi network"); |
| 43 | + Serial.print("IP Address: "); |
| 44 | + Serial.println(WiFi.localIP()); |
| 45 | + |
| 46 | + mg_mgr_init(&mgr); |
| 47 | + mg_log_set(MG_LL_DEBUG); |
| 48 | + mg_log_set_fn([](char ch, void *) { Serial.print(ch); }, NULL); |
| 49 | + mg_http_listen(&mgr, "http://0.0.0.0", http_ev_handler, NULL); |
| 50 | +} |
| 51 | + |
| 52 | +void loop() { |
| 53 | + mg_mgr_poll(&mgr, 0); |
| 54 | +} |
| 55 | + |
| 56 | +extern "C" int lwip_hook_ip6_input(struct pbuf *p, struct netif *inp) __attribute__((weak)); |
| 57 | +extern "C" int lwip_hook_ip6_input(struct pbuf *p, struct netif *inp) { |
| 58 | + if (ip6_addr_isany_val(inp->ip6_addr[0].u_addr.ip6)) { |
| 59 | + pbuf_free(p); |
| 60 | + return 1; |
| 61 | + } |
| 62 | + return 0; |
| 63 | +} |
0 commit comments