Exemplo n.º 1
0
/**
 * Initialize web server and add requests
 */
void webserver_start()
{
  // not found
  g_server.onNotFound(handleNotFound);

#ifdef CAPTIVE_PORTAL
  // handle captive requests
  g_server.addHandler(new CaptiveRequestHandler()).setFilter(ON_AP_FILTER);
#endif

  // CDN
  g_server.on("/js/jquery-2.1.4.min.js", HTTP_GET, [](AsyncWebServerRequest *request) {
    request->redirect(F("http://code.jquery.com/jquery-2.1.4.min.js"));
  }).setFilter(ON_STA_FILTER);
  g_server.on("/css/foundation.min.css", HTTP_GET, [](AsyncWebServerRequest *request) {
    request->redirect(F("http://cdnjs.cloudflare.com/ajax/libs/foundation/6.2.3/foundation.min.css"));
  }).setFilter(ON_STA_FILTER);

  // GET
  g_server.on("/api/status", HTTP_GET, handleGetStatus);
  g_server.on("/api/plugins", HTTP_GET, handleGetPlugins);
  g_server.on("/api/scan", HTTP_GET, handleWifiScan);

  // POST
  g_server.on("/settings", HTTP_POST, handleSettings);
  g_server.on("/restart", HTTP_POST, [](AsyncWebServerRequest *request) {
    // AsyncWebServerResponse *response = request->beginResponse(302);
    // response->addHeader("Location", net_hostname + ".local");
    // request->send(response);

    request->send(200, F(CONTENT_TYPE_HTML), F("<!DOCTYPE html><html><head><meta http-equiv=\"refresh\" content=\"5; url=/\"></head><body>Restarting...<br/><img src=\"/img/loading.gif\"></body></html>"));
    requestRestart();
  });

  // make sure config.json is not served!
  g_server.on("/config.json", HTTP_GET, [](AsyncWebServerRequest *request) {
    request->send(400);
  });

  // catch-all
  g_server.serveStatic("/", SPIFFS, "/", CACHE_HEADER).setDefaultFile("index.html");

  // sensor api
  registerPlugins();

#ifdef SPIFFS_EDITOR
  g_server.addHandler(new SPIFFSEditor());
#endif

#ifdef BROWSER_EVENTS
  g_server.addHandler(&g_events);
#endif

  // start server
  g_server.begin();
}
Exemplo n.º 2
0
/**
 * Setup handlers for each plugin and sensor
 * Structure is /api/<plugin>/<sensor>
 */
void registerPlugins()
{
  Plugin::each([](Plugin* plugin) {
    DEBUG_MSG(SERVER, "register plugin: %s\n", plugin->getName().c_str());

    // register one handler per sensor
    String baseUri = "/api/" + plugin->getName() + "/";
    for (int8_t sensor=0; sensor<plugin->getSensors(); sensor++) {
      String uri = String(baseUri);
      char addr_c[20];
      plugin->getAddr(addr_c, sensor);
      uri += addr_c;
      DEBUG_MSG(SERVER, "register sensor: %s\n", uri.c_str());

      g_server.addHandler(new PluginRequestHandler(uri.c_str(), plugin, sensor));
    }
  });
}