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

108 lines
5.1 KiB
C++
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include "VideoSocketService.h"
#include "GetCameraDeviceID.h"
#include "VideoProc.h"
#include "json.hpp"
VideoSocketService* VideoSocketService::getInstance()
{
static VideoSocketService _instance;
return &_instance;
}
VideoSocketService::VideoSocketService()
{
}
VideoSocketService::~VideoSocketService()
{
}
void VideoSocketService::Start(uint16_t port)
{
static auto fun = [this](uint16_t port) {
try {
m_web_server.set_access_channels(websocketpp::log::alevel::none);
m_web_server.clear_access_channels(websocketpp::log::alevel::none);
m_web_server.init_asio();
m_web_server.set_open_handler(bind(&VideoSocketService::OnWebSocketOpen, this, &m_web_server, ::_1));
m_web_server.set_close_handler(bind(&VideoSocketService::OnWebSocketClose, this, &m_web_server, _1));
m_web_server.set_message_handler(bind(&VideoSocketService::OnWebSocketMessage, this, &m_web_server, _1, _2));
m_web_server.listen(port);
m_web_server.start_accept();
m_web_server.run();
}
catch (websocketpp::exception const& e) {
std::cout << e.what() << std::endl;
}
catch (const std::exception & e) {
std::cout << e.what() << std::endl;
}
catch (...) {
std::cout << "未知异常" << std::endl;
}
};
std::thread(fun, port).detach();
std::thread(&VideoSocketService::PushImageThread, this).detach();
}
void VideoSocketService::Stop()
{
m_web_server.stop();
}
void VideoSocketService::OnWebSocketOpen(websocketsvr *server, websocketpp::connection_hdl hdl)
{
m_hdl = hdl;
std::cout << "New Connection" << std::endl;
}
void VideoSocketService::OnWebSocketClose(websocketsvr *server, websocketpp::connection_hdl hdl)
{
std::cout << "OnWebSocketClose" << std::endl;
// if (m_connection == hdl.lock().get())
// {
// m_connection = nullptr;
// }
//OnClose();
}
void VideoSocketService::OnWebSocketMessage(websocketsvr *server, websocketpp::connection_hdl hdl, message_ptr msg)
{
}
void VideoSocketService::PushImg(std::string img)
{
std::lock_guard<std::mutex> lock(m_mt);
if (m_img_list.size() > 30) {
m_img_list.pop();
}
m_img_list.push(img);
}
void VideoSocketService::PushImageThread()
{
while (true)
{
if (m_img_list.size() > 0)
{
std::string ret = std::string("data:image/bmp;base64,") + m_img_list.front();
m_web_server.send(m_hdl.lock(), ret, websocketpp::frame::opcode::TEXT);
{
std::lock_guard<std::mutex> lock(m_mt);
m_img_list.pop();
}
}
else
{
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
}
}