Hello everybody,
I'm writting a project in c++ for an ESP8266 with objects.
I create a class WebServer wich create ESP8266WebServer object. The idea is to create classes with function Routing() and private handle function in this classes.
Here exemple :
WebServer.h
#ifndef DEF_WEBSERVER
#define DEF_WEBSERVER
#include <Arduino.h>
#include <ESP8266WebServer.h>
class WebServer {
public:
WebServer(void);
void setup();
void loop();
private:
ESP8266WebServer server;
void ServerRouting();
void RootRoute();
void handleNotFound();
};
#endif
WebServer.cpp
#include <Arduino.h>
#include <ESP8266WebServer.h>
#include "WebServer.h"
#define WEBPORT 80
WebServer::WebServer() : server(WEBPORT) {}
void WebServer::setup() {
WebServer::ServerRouting();
WebServer::server.onNotFound(std::bind(&WebServer::handleNotFound, this));
WebServer::server.begin();
Serial.println("HTTP server started");
}
void WebServer::loop(){
WebServer::server.handleClient();
}
void WebServer::ServerRouting() {
WebServer::server.on("/", HTTP_GET, std::bind(&WebServer::RootRoute, this));
// Sub classes
// MyClass.ServerRouting();
}
void WebServer::RootRoute() {
WebServer::server.send(200, F("text/html"),F("Your are not allow to be here, get out now !"));
}
// Manage not found URL
void WebServer::handleNotFound() {
String message = "File Not Found\n\n";
message += "URI: ";
message += server.uri();
message += "\nMethod: ";
message += (server.method() == HTTP_GET) ? "GET" : "POST";
message += "\nArguments: ";
message += server.args();
message += "\n";
for (uint8_t i = 0; i < server.args(); i++) {
message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
}
server.send(404, "text/plain", message);
}
This code works perfectly.
I want to create MyClass :
MyClass.h
#ifndef DEF_MYCLASS
#define DEF_MYCLASS
#include <Arduino.h>
#include "WebServer.h"
#include <ESP8266WebServer.h>
class MyClass {
public:
MyClass(ESP8266WebServer& server) {srv = &server; }
void Routing();
private:
ESP8266WebServer* srv;
void getData();
void setData();
};
#endif
MyClass.cpp
#include <Arduino.h>
#include <ESP8266WebServer.h>
#include <ArduinoJson.h>
#include "MyClass.h"
bool isOn = false;
void MyClass::Routing(){
this->srv.on(F("/mylight"), HTTP_GET, std::bind(&MyClass::getData, this));
}
void MyClass::getData(){
// Function to send JSON
}
void MyClass::setData(){
// Function to set light state
}
But I can't pass ESP8266WebServer server object to MyClass.
I got this kind of messages :
src\MyClass.cpp: In member function 'void MyClass::Routing()':
src\MyClass.cpp:9:15: error: request for member 'on' in '((MyClass*)this)->MyClass::srv', which is of pointer type 'ESP8266WebServer* {aka esp8266webserver::ESP8266WebServerTemplate<WiFiServer>*}' (maybe you meant to use '->' ?)
this->srv.on(F("/mylight"), HTTP_GET, std::bind(&MyClass::getData, this));
^
*** [.pio\build\esp12e\src\MyClass.cpp.o] Error 1
Can you help me please ?