Status handler

This handler implements a simple REST API, returning a JSON structure containing the current club status. This can be used by an external application to show real-time information on the system, which is useful for a dashboard or website.

Due to its simplicity, this class is also fully implemented in its header:

#include <Poco/Net/HTTPRequestHandler.h>
#include <Poco/Net/HTTPServerResponse.h>
#include <Poco/Net/HTTPServerRequest.h>
#include <Poco/URI.h>

using namespace Poco;
using namespace Poco::Net;

#include "club.h"


class StatusHandler: public HTTPRequestHandler {
public:
void handleRequest(HTTPServerRequest& request, HTTPServerResponse& response) {
Club::log(LOG_INFO, "StatusHandler: Request from " + request.clientAddress().toString());

URI uri(request.getURI());
vector<string> parts;
uri.getPathSegments(parts);

response.setContentType("application/json");
response.setChunkedTransferEncoding(true);

if (parts.size() == 1) {
ostream& ostr = response.send();
ostr << "{ "clubstatus": " << !Club::clubOff << ",";
ostr << ""lock": " << Club::clubLocked << ",";
ostr << ""power": " << Club::powerOn << "";
ostr << "}";
}
else {
response.setStatus(HTTPResponse::HTTP_BAD_REQUEST);
ostream& ostr = response.send();
ostr << "{ "error": "Invalid request." }";
}
}
};

We use the central logger function from the Club class here to register details on incoming requests. Here, we just log the IP address of the client, but one could use the POCO HTTPServerRequest class's API to request even more detailed information.

Next, the URI is obtained from the request and we split the path section of the URL into a vector instance. After setting the content type and a transfer encoding setting on the response object, we check that we did indeed get the expected REST API call, at which point we compose the JSON string, obtain the club room status information from the Club class, and return this.

In the JSON object, we include information about the club room's status in general, inverting its Boolean variable, as well as the status of the lock and the power status, with a 1, indicating that the lock is closed or the power is on, respectively.

If the URL path had further segments, it would be an unrecognized API call, which would lead us to return an HTTP 400 (Bad Request) error instead.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.111.183