Files
webcamservice/Servicer.cpp
2024-12-15 16:18:16 +08:00

84 lines
1.8 KiB
C++

#include "Servicer.h"
#include "hv/EventLoop.h"
#include "hv/htime.h"
#include "hv/hssl.h"
#include "hv/HttpService.h"
#include "hv/WebSocketServer.h"
using namespace hv;
#define VER "1.0.0"
#define WS_PORT 9080
class WsContext {
public:
WsContext() {
}
~WsContext() {
}
int handleMessage(const std::string& msg) {
std::cout << msg << std::endl;
return msg.size();
}
hv::TimerID timerID;
};
Servicer::Servicer()
{
HttpService http;
http.GET("/webcam", [](const HttpContextPtr& ctx) {
return ctx->send(VER);
});
hv::WebSocketService ws;
ws.onopen = [](const WebSocketChannelPtr& channel, const std::string& url) {
printf("onopen: GET %s\n", url.c_str());
WsContext* ctx = channel->newContext<WsContext>();
// send(time) every 1s
ctx->timerID = hv::setInterval(1000, [channel](hv::TimerID id) {
char str[DATETIME_FMT_BUFLEN] = { 0 };
datetime_t dt = datetime_now();
datetime_fmt(&dt, str);
channel->send(str);
});
};
ws.onmessage = [](const WebSocketChannelPtr& channel, const std::string& msg) {
WsContext* ctx = channel->getContext<WsContext>();
ctx->handleMessage(msg);
};
ws.onclose = [](const WebSocketChannelPtr& channel) {
printf("onclose\n");
WsContext* ctx = channel->getContext<WsContext>();
if (ctx->timerID != INVALID_TIMER_ID) {
hv::killTimer(ctx->timerID);
}
channel->deleteContext<WsContext>();
};
websocket_server_t server;
server.port = WS_PORT;
server.service = &http;
server.ws = &ws;
websocket_server_run(&server, 0);
}
Servicer::~Servicer()
{
}
Servicer* Servicer::getInstance()
{
static Servicer _instance;
return &_instance;
}