88 lines
2.0 KiB
C++
88 lines
2.0 KiB
C++
#include "Bridge.h"
|
|
#include <Logging.h>
|
|
#include <functional>
|
|
#include <sstream>
|
|
|
|
|
|
namespace ToonBridge {
|
|
namespace Toon {
|
|
|
|
Bridge::Bridge(int port, const ToonSettings& toonSettings, const MQTTSettings& mqttSettings) :
|
|
m_mqttClient(mqttSettings.hostname, mqttSettings.port),
|
|
m_messageHandler(m_mqttClient, mqttSettings.topic),
|
|
m_port(port),
|
|
m_toonSettings(toonSettings),
|
|
m_mqttSettings(mqttSettings)
|
|
{
|
|
Start();
|
|
}
|
|
|
|
Bridge::~Bridge()
|
|
{
|
|
std::stringstream ss;
|
|
ss << m_mqttSettings.topic << "/BridgeState";
|
|
|
|
MQTT::MQTTMessage message;
|
|
message.topic = ss.str();
|
|
message.payload = "Stop";
|
|
m_mqttClient.Send(message);
|
|
}
|
|
|
|
void Bridge::Wait()
|
|
{
|
|
m_pHttpServer->Wait();
|
|
}
|
|
|
|
void Bridge::Start()
|
|
{
|
|
Http::HttpServer::CallbackMethod httpCallback = std::bind(&Bridge::HttpCallback, this, std::placeholders::_1, std::placeholders::_2);
|
|
|
|
m_pHttpServer.reset(new Http::HttpServer(m_port, httpCallback));
|
|
|
|
m_pWebSocketSubscription.reset(new WebSocketSubscription(m_toonSettings));
|
|
m_messageHandler.Connect(std::bind(&Bridge::TimeToLiveCallback, this, m_pWebSocketSubscription.get(), std::placeholders::_1));
|
|
|
|
std::stringstream ss;
|
|
ss << m_mqttSettings.topic << "/BridgeState";
|
|
|
|
MQTT::MQTTMessage message;
|
|
message.topic = ss.str();
|
|
message.payload = ss.str();
|
|
m_mqttClient.Send(message);
|
|
}
|
|
|
|
Http::HttpServer::HttpReply Bridge::HttpCallback(const std::string& uri, const std::vector<Http::HttpPostData>& postData)
|
|
{
|
|
Http::HttpServer::HttpReply reply;
|
|
reply.status = Http::HttpServer::HttpReply::Status::Ok;
|
|
|
|
try
|
|
{
|
|
if (postData.size() > 0)
|
|
{
|
|
for (auto& data : postData)
|
|
{
|
|
if (data.name == "data")
|
|
m_messageHandler.HandleMessage(data.value);
|
|
}
|
|
}
|
|
}
|
|
catch (const std::exception& e)
|
|
{
|
|
std::stringstream ss;
|
|
ss << "Bridge::HttpCallback() - Error: " << e.what() << std::endl;
|
|
Logging::Log(Logging::Severity::Error, ss.str());
|
|
}
|
|
|
|
return reply;
|
|
}
|
|
|
|
void Bridge::TimeToLiveCallback(ToonBridge::Toon::WebSocketSubscription* pSubscription, int timeToLive)
|
|
{
|
|
if (timeToLive < 20)
|
|
pSubscription->Reconnect();
|
|
}
|
|
|
|
} // namespace Toon
|
|
} // namespace ToonBridge
|