uncouple generic web stuff into api plugin

This commit is contained in:
2018-10-28 03:21:26 +01:00
parent a8d5cae284
commit 7fa3683ca6
8 changed files with 237 additions and 85 deletions

74
src/WebApi.cpp Normal file
View File

@@ -0,0 +1,74 @@
#ifndef __WEBAPI_PLUGIN__
#define __WEBAPI_PLUGIN__
#include <TaskSchedulerDeclarations.h>
#include <Sprocket.h>
#include "config.h"
#include "utils_print.h"
#include "utils_web.h"
#include <plugins/WebServerPlugin.cpp>
#include <plugins/WebConfigPlugin.cpp>
using namespace std;
using namespace std::placeholders;
// TODO headerfile
class WebApi : public Plugin {
private:
Network* network;
public:
AsyncWebServer* server;
AsyncWebSocket* ws;
SprocketMessage currentMessage;
int broadcast;
WebApi(AsyncWebServer* _server, int _broadcast = 0){
server = _server;
broadcast = _broadcast;
}
void activate(Scheduler* _scheduler, Network* _network) {
network = _network;
ws = new AsyncWebSocket("/ws"); // FIXME constant /ws
ws->onEvent(bind(&WebApi::onWsEvent, this, _1, _2, _3, _4, _5, _6));
server->addHandler(ws);
server->on("/api", HTTP_POST, bind(&WebApi::postRequestHandler, this, _1));
}
void postRequestHandler(AsyncWebServerRequest *request) {
PRINT_MSG(Serial, SPROCKET_TYPE, "POST WebApi");
currentMessage.topic = WebUtils::getRequestParameterOrDefault(request, "topic", "");
currentMessage.payload = WebUtils::getRequestParameterOrDefault(request, "payload", "");
currentMessage.broadcast = atoi(WebUtils::getRequestParameterOrDefault(request, "broadcast", "0").c_str());
String msg = currentMessage.toJsonString();
publish(currentMessage.topic, currentMessage.payload);
if(currentMessage.broadcast){
network->broadcast(msg);
}
request->send(200, "text/plain", msg);
}
void onWsEvent(AsyncWebSocket * server, AsyncWebSocketClient * client, AwsEventType type, void * arg, uint8_t *data, size_t len) {
// FIXME to limitted
if(type == WS_EVT_DATA){
String frame = WebUtils::parseFrameAsString(type, arg, data, len, 0);
dispatch(0, frame);
}
}
void dispatch( uint32_t from, String &msg ) {
currentMessage.fromJsonString(msg);
if(currentMessage.valid){
currentMessage.from = from;
publish(currentMessage.topic, currentMessage.payload);
if(broadcast){
network->broadcast(msg);
}
}
}
};
#endif