mirror of
https://github.com/hyperion-project/hyperion.ng.git
synced 2025-03-01 10:33:28 +00:00
remove protobuf (part 2)
This commit is contained in:
@@ -7,9 +7,9 @@ add_subdirectory(hyperion)
|
||||
add_subdirectory(commandline)
|
||||
add_subdirectory(blackborder)
|
||||
add_subdirectory(jsonserver)
|
||||
add_subdirectory(protoserver)
|
||||
add_subdirectory(flatbufserver)
|
||||
add_subdirectory(bonjour)
|
||||
add_subdirectory(ssdp)
|
||||
add_subdirectory(boblightserver)
|
||||
add_subdirectory(udplistener)
|
||||
add_subdirectory(leddevice)
|
||||
|
@@ -51,6 +51,7 @@ JsonAPI::JsonAPI(QString peerAddress, Logger* log, QObject* parent, bool noListe
|
||||
{
|
||||
// the JsonCB creates json messages you can subscribe to e.g. data change events; forward them to the parent client
|
||||
connect(_jsonCB, &JsonCB::newCallback, this, &JsonAPI::callbackMessage);
|
||||
|
||||
// notify hyperion about a jsonMessageForward
|
||||
connect(this, &JsonAPI::forwardJsonMessage, _hyperion, &Hyperion::forwardJsonMessage);
|
||||
|
||||
@@ -59,7 +60,7 @@ JsonAPI::JsonAPI(QString peerAddress, Logger* log, QObject* parent, bool noListe
|
||||
_image_stream_mutex.unlock();
|
||||
}
|
||||
|
||||
void JsonAPI::handleMessage(const QString& messageString, const QString& httpAuthHeader)
|
||||
void JsonAPI::handleMessage(const QString& messageString)
|
||||
{
|
||||
const QString ident = "JsonRpc@"+_peerAddress;
|
||||
Q_INIT_RESOURCE(JSONRPC_schemas);
|
||||
@@ -859,7 +860,8 @@ void JsonAPI::handleLedColorsCommand(const QJsonObject& message, const QString &
|
||||
{
|
||||
_streaming_leds_reply["success"] = true;
|
||||
_streaming_leds_reply["command"] = command+"-ledstream-update";
|
||||
_streaming_leds_reply["tan"] = tan;
|
||||
_streaming_leds_reply["tan"] = tan;
|
||||
_timer_ledcolors.setInterval(125);
|
||||
_timer_ledcolors.start(125);
|
||||
}
|
||||
else if (subcommand == "ledstream-stop")
|
||||
@@ -870,7 +872,7 @@ void JsonAPI::handleLedColorsCommand(const QJsonObject& message, const QString &
|
||||
{
|
||||
_streaming_image_reply["success"] = true;
|
||||
_streaming_image_reply["command"] = command+"-imagestream-update";
|
||||
_streaming_image_reply["tan"] = tan;
|
||||
_streaming_image_reply["tan"] = tan;
|
||||
connect(_hyperion, &Hyperion::currentImage, this, &JsonAPI::setImage, Qt::UniqueConnection);
|
||||
}
|
||||
else if (subcommand == "imagestream-stop")
|
||||
|
@@ -14,6 +14,9 @@ BonjourBrowserWrapper::BonjourBrowserWrapper(QObject * parent)
|
||||
, _bonjourResolver(new BonjourServiceResolver(this))
|
||||
, _timerBonjourResolver( new QTimer(this))
|
||||
{
|
||||
// register meta
|
||||
qRegisterMetaType<QMap<QString,BonjourRecord>>("QMap<QString,BonjourRecord>");
|
||||
|
||||
BonjourBrowserWrapper::instance = this;
|
||||
connect(_bonjourResolver, &BonjourServiceResolver::bonjourRecordResolved, this, &BonjourBrowserWrapper::bonjourRecordResolved);
|
||||
|
||||
|
@@ -58,6 +58,9 @@ Effect::~Effect()
|
||||
|
||||
void Effect::run()
|
||||
{
|
||||
// we probably need to wait until mainThreadState is available
|
||||
while(mainThreadState == nullptr){};
|
||||
|
||||
// get global lock
|
||||
PyEval_RestoreThread(mainThreadState);
|
||||
|
||||
|
@@ -4,6 +4,7 @@
|
||||
#include <QTcpSocket>
|
||||
#include <QHostAddress>
|
||||
#include <QTimer>
|
||||
#include <QRgb>
|
||||
|
||||
#include <hyperion/Hyperion.h>
|
||||
#include <QDebug>
|
||||
@@ -11,7 +12,7 @@ FlatBufferClient::FlatBufferClient(QTcpSocket* socket, const int &timeout, QObje
|
||||
: QObject(parent)
|
||||
, _log(Logger::getInstance("FLATBUFSERVER"))
|
||||
, _socket(socket)
|
||||
, _clientAddress(socket->peerAddress().toString())
|
||||
, _clientAddress("@"+socket->peerAddress().toString())
|
||||
, _timeoutTimer(new QTimer(this))
|
||||
, _timeout(timeout * 1000)
|
||||
, _priority()
|
||||
@@ -49,12 +50,12 @@ void FlatBufferClient::readyRead()
|
||||
const QByteArray msg = _receiveBuffer.right(messageSize);
|
||||
_receiveBuffer.remove(0, messageSize + 4);
|
||||
|
||||
const uint8_t* msgData = reinterpret_cast<const uint8_t*>(msg.constData());
|
||||
const auto* msgData = reinterpret_cast<const uint8_t*>(msg.constData());
|
||||
flatbuffers::Verifier verifier(msgData, messageSize);
|
||||
|
||||
if (flatbuf::VerifyHyperionRequestBuffer(verifier))
|
||||
if (hyperionnet::VerifyRequestBuffer(verifier))
|
||||
{
|
||||
auto message = flatbuf::GetHyperionRequest(msgData);
|
||||
auto message = hyperionnet::GetRequest(msgData);
|
||||
handleMessage(message);
|
||||
continue;
|
||||
}
|
||||
@@ -83,79 +84,92 @@ void FlatBufferClient::disconnected()
|
||||
emit clientDisconnected();
|
||||
}
|
||||
|
||||
void FlatBufferClient::handleMessage(const flatbuf::HyperionRequest * message)
|
||||
void FlatBufferClient::handleMessage(const hyperionnet::Request * req)
|
||||
{
|
||||
switch (message->command())
|
||||
{
|
||||
case flatbuf::Command_COLOR:
|
||||
qDebug()<<"handle colorReuest";
|
||||
if (!flatbuffers::IsFieldPresent(message, flatbuf::HyperionRequest::VT_COLORREQUEST))
|
||||
{
|
||||
sendErrorReply("Received COLOR command without ColorRequest");
|
||||
break;
|
||||
}
|
||||
//handleColorCommand(message->colorRequest());
|
||||
break;
|
||||
case flatbuf::Command_IMAGE:
|
||||
qDebug()<<"handle imageReuest";
|
||||
if (!flatbuffers::IsFieldPresent(message, flatbuf::HyperionRequest::VT_IMAGEREQUEST))
|
||||
{
|
||||
sendErrorReply("Received IMAGE command without ImageRequest");
|
||||
break;
|
||||
}
|
||||
handleImageCommand(message->imageRequest());
|
||||
break;
|
||||
case flatbuf::Command_CLEAR:
|
||||
if (!flatbuffers::IsFieldPresent(message, flatbuf::HyperionRequest::VT_CLEARREQUEST))
|
||||
{
|
||||
sendErrorReply("Received CLEAR command without ClearRequest");
|
||||
break;
|
||||
}
|
||||
//handleClearCommand(message->clearRequest());
|
||||
break;
|
||||
case flatbuf::Command_CLEARALL:
|
||||
//handleClearallCommand();
|
||||
break;
|
||||
default:
|
||||
qDebug()<<"handleNotImplemented";
|
||||
handleNotImplemented();
|
||||
const void* reqPtr;
|
||||
if ((reqPtr = req->command_as_Color()) != nullptr) {
|
||||
handleColorCommand(static_cast<const hyperionnet::Color*>(reqPtr));
|
||||
} else if ((reqPtr = req->command_as_Image()) != nullptr) {
|
||||
handleImageCommand(static_cast<const hyperionnet::Image*>(reqPtr));
|
||||
} else if ((reqPtr = req->command_as_Clear()) != nullptr) {
|
||||
handleClearCommand(static_cast<const hyperionnet::Clear*>(reqPtr));
|
||||
} else if ((reqPtr = req->command_as_Register()) != nullptr) {
|
||||
handleRegisterCommand(static_cast<const hyperionnet::Register*>(reqPtr));
|
||||
} else {
|
||||
sendErrorReply("Received invalid packet.");
|
||||
}
|
||||
}
|
||||
|
||||
void FlatBufferClient::handleImageCommand(const flatbuf::ImageRequest *message)
|
||||
void FlatBufferClient::handleColorCommand(const hyperionnet::Color *colorReq)
|
||||
{
|
||||
// extract parameters
|
||||
int priority = message->priority();
|
||||
int duration = message->duration();
|
||||
int width = message->imagewidth();
|
||||
int height = message->imageheight();
|
||||
const auto & imageData = message->imagedata();
|
||||
const int32_t rgbData = colorReq->data();
|
||||
ColorRgb color;
|
||||
color.red = qRed(rgbData);
|
||||
color.green = qGreen(rgbData);
|
||||
color.blue = qBlue(rgbData);
|
||||
|
||||
// make sure the prio is registered before setInput()
|
||||
if(priority != _priority)
|
||||
{
|
||||
_hyperion->clear(_priority);
|
||||
_hyperion->registerInput(priority, hyperion::COMP_FLATBUFSERVER, "proto@"+_clientAddress);
|
||||
_priority = priority;
|
||||
}
|
||||
|
||||
// check consistency of the size of the received data
|
||||
if ((int) imageData->size() != width*height*3)
|
||||
{
|
||||
sendErrorReply("Size of image data does not match with the width and height");
|
||||
return;
|
||||
}
|
||||
|
||||
// create ImageRgb
|
||||
Image<ColorRgb> image(width, height);
|
||||
memcpy(image.memptr(), imageData->data(), imageData->size());
|
||||
|
||||
_hyperion->setInputImage(_priority, image, duration);
|
||||
// set output
|
||||
_hyperion->setColor(_priority, color, colorReq->duration());
|
||||
|
||||
// send reply
|
||||
sendSuccessReply();
|
||||
}
|
||||
|
||||
void FlatBufferClient::handleRegisterCommand(const hyperionnet::Register *regReq)
|
||||
{
|
||||
_priority = regReq->priority();
|
||||
_hyperion->registerInput(_priority, hyperion::COMP_FLATBUFSERVER, regReq->origin()->c_str()+_clientAddress);
|
||||
}
|
||||
|
||||
void FlatBufferClient::handleImageCommand(const hyperionnet::Image *image)
|
||||
{
|
||||
// extract parameters
|
||||
int duration = image->duration();
|
||||
|
||||
const void* reqPtr;
|
||||
if ((reqPtr = image->data_as_RawImage()) != nullptr)
|
||||
{
|
||||
const auto *img = static_cast<const hyperionnet::RawImage*>(reqPtr);
|
||||
const auto & imageData = img->data();
|
||||
const int width = img->width();
|
||||
const int height = img->height();
|
||||
|
||||
if ((int) imageData->size() != width*height*3)
|
||||
{
|
||||
sendErrorReply("Size of image data does not match with the width and height");
|
||||
return;
|
||||
}
|
||||
|
||||
Image<ColorRgb> image(width, height);
|
||||
memmove(image.memptr(), imageData->data(), imageData->size());
|
||||
_hyperion->setInputImage(_priority, image, duration);
|
||||
}
|
||||
|
||||
// send reply
|
||||
sendSuccessReply();
|
||||
}
|
||||
|
||||
|
||||
void FlatBufferClient::handleClearCommand(const hyperionnet::Clear *clear)
|
||||
{
|
||||
// extract parameters
|
||||
const int priority = clear->priority();
|
||||
|
||||
if (priority == -1) {
|
||||
_hyperion->clearall();
|
||||
}
|
||||
else {
|
||||
// Check if we are clearing ourselves.
|
||||
if (priority == _priority) {
|
||||
_priority = -1;
|
||||
}
|
||||
|
||||
_hyperion->clear(priority);
|
||||
}
|
||||
|
||||
sendSuccessReply();
|
||||
}
|
||||
|
||||
void FlatBufferClient::handleNotImplemented()
|
||||
{
|
||||
@@ -175,7 +189,7 @@ void FlatBufferClient::sendMessage()
|
||||
|
||||
void FlatBufferClient::sendSuccessReply()
|
||||
{
|
||||
auto reply = flatbuf::CreateHyperionReplyDirect(_builder, flatbuf::Type_REPLY, true);
|
||||
auto reply = hyperionnet::CreateReplyDirect(_builder);
|
||||
_builder.Finish(reply);
|
||||
|
||||
// send reply
|
||||
@@ -185,7 +199,7 @@ void FlatBufferClient::sendSuccessReply()
|
||||
void FlatBufferClient::sendErrorReply(const std::string &error)
|
||||
{
|
||||
// create reply
|
||||
auto reply = flatbuf::CreateHyperionReplyDirect(_builder, flatbuf::Type_REPLY, false, error.c_str());
|
||||
auto reply = hyperionnet::CreateReplyDirect(_builder, error.c_str());
|
||||
_builder.Finish(reply);
|
||||
|
||||
// send reply
|
||||
|
@@ -75,14 +75,31 @@ private:
|
||||
///
|
||||
/// @brief Handle the received message
|
||||
///
|
||||
void handleMessage(const flatbuf::HyperionRequest *message);
|
||||
void handleMessage(const hyperionnet::Request * req);
|
||||
|
||||
///
|
||||
/// Register new priority
|
||||
///
|
||||
void handleRegisterCommand(const hyperionnet::Register *regReq);
|
||||
|
||||
///
|
||||
/// @brief Hande Color message
|
||||
///
|
||||
void handleColorCommand(const hyperionnet::Color *colorReq);
|
||||
|
||||
///
|
||||
/// Handle an incoming Image message
|
||||
///
|
||||
/// @param message the incoming message
|
||||
/// @param image the incoming image
|
||||
///
|
||||
void handleImageCommand(const flatbuf::ImageRequest * message);
|
||||
void handleImageCommand(const hyperionnet::Image *image);
|
||||
|
||||
///
|
||||
/// @brief Handle clear command
|
||||
///
|
||||
/// @param clear the incoming clear request
|
||||
///
|
||||
void handleClearCommand(const hyperionnet::Clear *clear);
|
||||
|
||||
///
|
||||
/// Send handle not implemented
|
||||
@@ -108,12 +125,12 @@ private:
|
||||
|
||||
private:
|
||||
Logger *_log;
|
||||
QTcpSocket *_socket;
|
||||
QTcpSocket *_socket;
|
||||
const QString _clientAddress;
|
||||
QTimer *_timeoutTimer;
|
||||
int _timeout;
|
||||
int _priority;
|
||||
Hyperion* _hyperion;
|
||||
Hyperion* _hyperion;
|
||||
|
||||
QByteArray _receiveBuffer;
|
||||
|
||||
|
@@ -7,10 +7,13 @@
|
||||
// protoserver includes
|
||||
#include <flatbufserver/FlatBufferConnection.h>
|
||||
|
||||
FlatBufferConnection::FlatBufferConnection(const QString & address)
|
||||
FlatBufferConnection::FlatBufferConnection(const QString& origin, const QString & address, const int& priority, const bool& skipReply)
|
||||
: _socket()
|
||||
, _origin(origin)
|
||||
, _priority(priority)
|
||||
, _prevSocketState(QAbstractSocket::UnconnectedState)
|
||||
, _log(Logger::getInstance("FLATBUFCONNECTION"))
|
||||
, _registered(false)
|
||||
{
|
||||
QStringList parts = address.split(":");
|
||||
if (parts.size() != 2)
|
||||
@@ -26,6 +29,9 @@ FlatBufferConnection::FlatBufferConnection(const QString & address)
|
||||
throw std::runtime_error(QString("FLATBUFCONNECTION ERROR: Unable to parse the port (%1)").arg(parts[1]).toStdString());
|
||||
}
|
||||
|
||||
if(!skipReply)
|
||||
connect(&_socket, &QTcpSocket::readyRead, this, &FlatBufferConnection::readData, Qt::UniqueConnection);
|
||||
|
||||
// init connect
|
||||
Info(_log, "Connecting to Hyperion: %s:%d", _host.toStdString().c_str(), _port);
|
||||
connectToHost();
|
||||
@@ -66,10 +72,9 @@ void FlatBufferConnection::readData()
|
||||
const uint8_t* msgData = reinterpret_cast<const uint8_t*>(msg.constData());
|
||||
flatbuffers::Verifier verifier(msgData, messageSize);
|
||||
|
||||
if (flatbuf::VerifyHyperionReplyBuffer(verifier))
|
||||
if (hyperionnet::VerifyReplyBuffer(verifier))
|
||||
{
|
||||
auto message = flatbuf::GetHyperionReply(msgData);
|
||||
parseReply(message);
|
||||
parseReply(hyperionnet::GetReply(msgData));
|
||||
continue;
|
||||
}
|
||||
Error(_log, "Unable to parse reply");
|
||||
@@ -84,28 +89,39 @@ void FlatBufferConnection::setSkipReply(const bool& skip)
|
||||
connect(&_socket, &QTcpSocket::readyRead, this, &FlatBufferConnection::readData, Qt::UniqueConnection);
|
||||
}
|
||||
|
||||
void FlatBufferConnection::setColor(const ColorRgb & color, int priority, int duration)
|
||||
void FlatBufferConnection::setRegister(const QString& origin, int priority)
|
||||
{
|
||||
auto colorReq = flatbuf::CreateColorRequest(_builder, priority, (color.red << 16) | (color.green << 8) | color.blue, duration);
|
||||
auto req = flatbuf::CreateHyperionRequest(_builder,flatbuf::Command_COLOR, colorReq);
|
||||
auto registerReq = hyperionnet::CreateRegister(_builder, _builder.CreateString(QSTRING_CSTR(origin)), priority);
|
||||
auto req = hyperionnet::CreateRequest(_builder, hyperionnet::Command_Register, registerReq.Union());
|
||||
|
||||
_builder.Finish(req);
|
||||
sendMessage(_builder.GetBufferPointer(), _builder.GetSize());
|
||||
}
|
||||
|
||||
void FlatBufferConnection::setImage(const Image<ColorRgb> &image, int priority, int duration)
|
||||
void FlatBufferConnection::setColor(const ColorRgb & color, int priority, int duration)
|
||||
{
|
||||
/* #TODO #BROKEN auto imgData = _builder.CreateVector<flatbuffers::Offset<uint8_t>>(image.memptr(), image.width() * image.height() * 3);
|
||||
auto imgReq = flatbuf::CreateImageRequest(_builder, priority, image.width(), image.height(), imgData, duration);
|
||||
auto req = flatbuf::CreateHyperionRequest(_builder,flatbuf::Command_IMAGE,0,imgReq);
|
||||
auto colorReq = hyperionnet::CreateColor(_builder, (color.red << 16) | (color.green << 8) | color.blue, duration);
|
||||
auto req = hyperionnet::CreateRequest(_builder, hyperionnet::Command_Color, colorReq.Union());
|
||||
|
||||
_builder.Finish(req);
|
||||
sendMessage(_builder.GetBufferPointer(), _builder.GetSize());*/
|
||||
sendMessage(_builder.GetBufferPointer(), _builder.GetSize());
|
||||
}
|
||||
|
||||
void FlatBufferConnection::setImage(const Image<ColorRgb> &image)
|
||||
{
|
||||
auto imgData = _builder.CreateVector(reinterpret_cast<const uint8_t*>(image.memptr()), image.size());
|
||||
auto rawImg = hyperionnet::CreateRawImage(_builder, imgData, image.width(), image.height());
|
||||
auto imageReq = hyperionnet::CreateImage(_builder, hyperionnet::ImageType_RawImage, rawImg.Union(), -1);
|
||||
auto req = hyperionnet::CreateRequest(_builder,hyperionnet::Command_Image,imageReq.Union());
|
||||
|
||||
_builder.Finish(req);
|
||||
sendMessage(_builder.GetBufferPointer(), _builder.GetSize());
|
||||
}
|
||||
|
||||
void FlatBufferConnection::clear(int priority)
|
||||
{
|
||||
auto clearReq = flatbuf::CreateClearRequest(_builder, priority);
|
||||
auto req = flatbuf::CreateHyperionRequest(_builder,flatbuf::Command_CLEAR,0,0,clearReq);
|
||||
auto clearReq = hyperionnet::CreateClear(_builder, priority);
|
||||
auto req = hyperionnet::CreateRequest(_builder,hyperionnet::Command_Clear, clearReq.Union());
|
||||
|
||||
_builder.Finish(req);
|
||||
sendMessage(_builder.GetBufferPointer(), _builder.GetSize());
|
||||
@@ -113,11 +129,7 @@ void FlatBufferConnection::clear(int priority)
|
||||
|
||||
void FlatBufferConnection::clearAll()
|
||||
{
|
||||
auto req = flatbuf::CreateHyperionRequest(_builder,flatbuf::Command_CLEARALL);
|
||||
|
||||
// send command message
|
||||
_builder.Finish(req);
|
||||
sendMessage(_builder.GetBufferPointer(), _builder.GetSize());
|
||||
clear(-1);
|
||||
}
|
||||
|
||||
void FlatBufferConnection::connectToHost()
|
||||
@@ -135,26 +147,30 @@ void FlatBufferConnection::sendMessage(const uint8_t* buffer, uint32_t size)
|
||||
// print out connection message only when state is changed
|
||||
if (_socket.state() != _prevSocketState )
|
||||
{
|
||||
switch (_socket.state() )
|
||||
{
|
||||
case QAbstractSocket::UnconnectedState:
|
||||
Info(_log, "No connection to Hyperion: %s:%d", _host.toStdString().c_str(), _port);
|
||||
break;
|
||||
|
||||
case QAbstractSocket::ConnectedState:
|
||||
Info(_log, "Connected to Hyperion: %s:%d", _host.toStdString().c_str(), _port);
|
||||
break;
|
||||
|
||||
default:
|
||||
Debug(_log, "Connecting to Hyperion: %s:%d", _host.toStdString().c_str(), _port);
|
||||
break;
|
||||
switch (_socket.state() )
|
||||
{
|
||||
case QAbstractSocket::UnconnectedState:
|
||||
Info(_log, "No connection to Hyperion: %s:%d", _host.toStdString().c_str(), _port);
|
||||
break;
|
||||
case QAbstractSocket::ConnectedState:
|
||||
Info(_log, "Connected to Hyperion: %s:%d", _host.toStdString().c_str(), _port);
|
||||
_registered = false;
|
||||
break;
|
||||
default:
|
||||
Debug(_log, "Connecting to Hyperion: %s:%d", _host.toStdString().c_str(), _port);
|
||||
break;
|
||||
}
|
||||
_prevSocketState = _socket.state();
|
||||
}
|
||||
|
||||
|
||||
if (_socket.state() != QAbstractSocket::ConnectedState)
|
||||
return;
|
||||
|
||||
if(!_registered)
|
||||
{
|
||||
_registered = true;
|
||||
setRegister(_origin, _priority);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -168,46 +184,22 @@ void FlatBufferConnection::sendMessage(const uint8_t* buffer, uint32_t size)
|
||||
int count = 0;
|
||||
count += _socket.write(reinterpret_cast<const char *>(header), 4);
|
||||
count += _socket.write(reinterpret_cast<const char *>(buffer), size);
|
||||
if (!_socket.waitForBytesWritten())
|
||||
{
|
||||
Error(_log, "Error while writing data to host");
|
||||
return;
|
||||
}
|
||||
_socket.flush();
|
||||
_builder.Clear();
|
||||
}
|
||||
|
||||
bool FlatBufferConnection::parseReply(const flatbuf::HyperionReply *reply)
|
||||
bool FlatBufferConnection::parseReply(const hyperionnet::Reply *reply)
|
||||
{
|
||||
bool success = false;
|
||||
|
||||
switch (reply->type())
|
||||
if (!reply->error())
|
||||
{
|
||||
case flatbuf::Type_REPLY:
|
||||
{
|
||||
if (!reply->success())
|
||||
{
|
||||
if (flatbuffers::IsFieldPresent(reply, flatbuf::HyperionReply::VT_ERROR))
|
||||
{
|
||||
throw std::runtime_error("PROTOCONNECTION ERROR: " + reply->error()->str());
|
||||
}
|
||||
else
|
||||
{
|
||||
throw std::runtime_error("PROTOCONNECTION ERROR: No error info");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
success = true;
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
case flatbuf::Type_VIDEO:
|
||||
{
|
||||
VideoMode vMode = (VideoMode)reply->video();
|
||||
emit setVideoMode(vMode);
|
||||
break;
|
||||
// no error set must be a success or video
|
||||
const auto videoMode = reply->video();
|
||||
if (videoMode != -1) {
|
||||
// We got a video reply.
|
||||
emit setVideoMode(static_cast<VideoMode>(videoMode));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
return success;
|
||||
return false;
|
||||
}
|
||||
|
@@ -58,6 +58,7 @@ void FlatBufferServer::newConnection()
|
||||
{
|
||||
if(QTcpSocket* socket = _server->nextPendingConnection())
|
||||
{
|
||||
|
||||
Debug(_log, "New connection from %s", QSTRING_CSTR(socket->peerAddress().toString()));
|
||||
FlatBufferClient *client = new FlatBufferClient(socket, _timeout, this);
|
||||
// internal
|
||||
|
@@ -1,15 +1,8 @@
|
||||
namespace flatbuf;
|
||||
namespace hyperionnet;
|
||||
|
||||
enum Type : int {
|
||||
REPLY = 0,
|
||||
VIDEO = 1,
|
||||
}
|
||||
|
||||
table HyperionReply {
|
||||
type:Type;
|
||||
success:bool;
|
||||
table Reply {
|
||||
error:string;
|
||||
video:int;
|
||||
video:int = -1;
|
||||
}
|
||||
|
||||
root_type HyperionReply;
|
||||
root_type Reply;
|
||||
|
@@ -1,35 +1,37 @@
|
||||
namespace flatbuf;
|
||||
namespace hyperionnet;
|
||||
|
||||
enum Command : int {
|
||||
COLOR = 0,
|
||||
IMAGE = 1,
|
||||
CLEAR = 2,
|
||||
CLEARALL = 3,
|
||||
}
|
||||
|
||||
table HyperionRequest {
|
||||
command:Command;
|
||||
colorRequest:flatbuf.ColorRequest;
|
||||
imageRequest:flatbuf.ImageRequest;
|
||||
clearRequest:flatbuf.ClearRequest;
|
||||
}
|
||||
|
||||
table ColorRequest {
|
||||
priority:int;
|
||||
RgbColor:int;
|
||||
duration:int;
|
||||
}
|
||||
|
||||
table ImageRequest {
|
||||
priority:int;
|
||||
imagewidth:int;
|
||||
imageheight:int;
|
||||
imagedata:[ubyte];
|
||||
duration:int;
|
||||
}
|
||||
|
||||
table ClearRequest {
|
||||
// A priority value of -1 clears all priorities
|
||||
table Register {
|
||||
origin:string (required);
|
||||
priority:int;
|
||||
}
|
||||
|
||||
root_type HyperionRequest;
|
||||
table RawImage {
|
||||
data:[ubyte];
|
||||
width:int = -1;
|
||||
height:int = -1;
|
||||
}
|
||||
|
||||
union ImageType {RawImage}
|
||||
|
||||
table Image {
|
||||
data:ImageType (required);
|
||||
duration:int = -1;
|
||||
}
|
||||
|
||||
table Clear {
|
||||
priority:int;
|
||||
}
|
||||
|
||||
table Color {
|
||||
data:int = -1;
|
||||
duration:int = -1;
|
||||
}
|
||||
|
||||
union Command {Color, Image, Clear, Register}
|
||||
|
||||
table Request {
|
||||
command:Command (required);
|
||||
}
|
||||
|
||||
root_type Request;
|
||||
|
@@ -23,8 +23,6 @@ LinearColorSmoothing::LinearColorSmoothing( LedDevice * ledDevice, const QJsonDo
|
||||
, _pause(false)
|
||||
, _currentConfigId(0)
|
||||
{
|
||||
Debug(_log, "Instance created");
|
||||
|
||||
// set initial state to true, as LedDevice::enabled() is true by default
|
||||
_hyperion->getComponentRegister().componentStateChanged(hyperion::COMP_SMOOTHING, true);
|
||||
|
||||
|
@@ -98,7 +98,7 @@ void MessageForwarder::addProtoSlave(QString slave)
|
||||
}
|
||||
|
||||
// verify loop with protoserver
|
||||
const QJsonObject& obj = _hyperion->getSetting(settings::PROTOSERVER).object();
|
||||
const QJsonObject& obj = _hyperion->getSetting(settings::FLATBUFSERVER).object();
|
||||
if(QHostAddress(parts[0]) == QHostAddress::LocalHost && parts[1].toInt() == obj["port"].toInt())
|
||||
{
|
||||
Error(_log, "Loop between ProtoServer and Forwarder! (%s)",QSTRING_CSTR(slave));
|
||||
|
@@ -20,11 +20,11 @@ SettingsManager::SettingsManager(Hyperion* hyperion, const quint8& instance, con
|
||||
: _hyperion(hyperion)
|
||||
, _log(Logger::getInstance("SettingsManager"))
|
||||
{
|
||||
Q_INIT_RESOURCE(resource);
|
||||
connect(this, &SettingsManager::settingsChanged, _hyperion, &Hyperion::settingsChanged);
|
||||
// get schema
|
||||
if(schemaJson.isEmpty())
|
||||
{
|
||||
Q_INIT_RESOURCE(resource);
|
||||
try
|
||||
{
|
||||
schemaJson = QJsonFactory::readSchema(":/hyperion-schema");
|
||||
|
@@ -51,10 +51,6 @@
|
||||
{
|
||||
"$ref": "schema-jsonServer.json"
|
||||
},
|
||||
"protoServer" :
|
||||
{
|
||||
"$ref": "schema-protoServer.json"
|
||||
},
|
||||
"flatbufServer":
|
||||
{
|
||||
"$ref": "schema-flatbufServer.json"
|
||||
|
@@ -15,7 +15,6 @@
|
||||
<file alias="schema-backgroundEffect.json">schema/schema-backgroundEffect.json</file>
|
||||
<file alias="schema-forwarder.json">schema/schema-forwarder.json</file>
|
||||
<file alias="schema-jsonServer.json">schema/schema-jsonServer.json</file>
|
||||
<file alias="schema-protoServer.json">schema/schema-protoServer.json</file>
|
||||
<file alias="schema-flatbufServer.json">schema/schema-flatbufServer.json</file>
|
||||
<file alias="schema-boblightServer.json">schema/schema-boblightServer.json</file>
|
||||
<file alias="schema-udpListener.json">schema/schema-udpListener.json</file>
|
||||
|
@@ -77,6 +77,7 @@ ENDFOREACH()
|
||||
add_library(leddevice ${CMAKE_BINARY_DIR}/LedDevice_headers.h ${Leddevice_SOURCES} )
|
||||
|
||||
target_link_libraries(leddevice
|
||||
hyperion
|
||||
hyperion-utils
|
||||
${CMAKE_THREAD_LIBS_INIT}
|
||||
Qt5::Network
|
||||
|
14
libsrc/ssdp/CMakeLists.txt
Normal file
14
libsrc/ssdp/CMakeLists.txt
Normal file
@@ -0,0 +1,14 @@
|
||||
# Define the current source locations
|
||||
SET(CURRENT_HEADER_DIR ${CMAKE_SOURCE_DIR}/include/ssdp)
|
||||
SET(CURRENT_SOURCE_DIR ${CMAKE_SOURCE_DIR}/libsrc/ssdp)
|
||||
|
||||
FILE ( GLOB SSDP_SOURCES "${CURRENT_HEADER_DIR}/*.h" "${CURRENT_SOURCE_DIR}/*.h" "${CURRENT_SOURCE_DIR}/*.cpp" )
|
||||
|
||||
add_library(ssdp
|
||||
${SSDP_SOURCES}
|
||||
)
|
||||
|
||||
target_link_libraries(ssdp
|
||||
Qt5::Network
|
||||
webserver
|
||||
)
|
41
libsrc/ssdp/SSDPDescription.h
Normal file
41
libsrc/ssdp/SSDPDescription.h
Normal file
@@ -0,0 +1,41 @@
|
||||
#pragma once
|
||||
|
||||
///
|
||||
/// The xml to fill with data
|
||||
/// %1 base url http://192.168.0.177:80/
|
||||
/// %2 friendly name Hyperion 2.0.0 (192.168.0.177)
|
||||
/// %3 modelNumber 2.0.0
|
||||
/// %4 serialNumber / UDN (H ID) Fjsa723dD0....
|
||||
///
|
||||
/// def URN urn:schemas-upnp-org:device:Basic:1
|
||||
|
||||
static const QString SSDP_DESCRIPTION = "<?xml version=\"1.0\"?>"
|
||||
"<root xmlns=\"urn:schemas-upnp-org:device-1-0\">"
|
||||
"<specVersion>"
|
||||
"<major>1</major>"
|
||||
"<minor>0</minor>"
|
||||
"</specVersion>"
|
||||
"<URLBase>%1</URLBase>"
|
||||
"<device>"
|
||||
"<deviceType>urn:schemas-upnp-org:device:Basic:1</deviceType>"
|
||||
"<friendlyName>%2</friendlyName>"
|
||||
"<manufacturer>Hyperion Open Source Ambient Lighting</manufacturer>"
|
||||
"<manufacturerURL>https://www.hyperion-project.org</manufacturerURL>"
|
||||
"<modelDescription>Hyperion Open Source Ambient Light</modelDescription>"
|
||||
"<modelName>Hyperion</modelName>"
|
||||
"<modelNumber>%3</modelNumber>"
|
||||
"<modelURL>https://www.hyperion-project.org</modelURL>"
|
||||
"<serialNumber>%4</serialNumber>"
|
||||
"<UDN>uuid:%4</UDN>"
|
||||
"<presentationURL>index.html</presentationURL>"
|
||||
"<iconList>"
|
||||
"<icon>"
|
||||
"<mimetype>image/png</mimetype>"
|
||||
"<height>100</height>"
|
||||
"<width>100</width>"
|
||||
"<depth>32</depth>"
|
||||
"<url>img/hyperion/ssdp_icon.png</url>"
|
||||
"</icon>"
|
||||
"</iconList>"
|
||||
"</device>"
|
||||
"</root>";
|
169
libsrc/ssdp/SSDPDiscover.cpp
Normal file
169
libsrc/ssdp/SSDPDiscover.cpp
Normal file
@@ -0,0 +1,169 @@
|
||||
#include <ssdp/SSDPDiscover.h>
|
||||
|
||||
// qt inc
|
||||
#include <QUdpSocket>
|
||||
#include <QUrl>
|
||||
|
||||
static const QHostAddress SSDP_ADDR("239.255.255.250");
|
||||
static const quint16 SSDP_PORT(1900);
|
||||
|
||||
// as per upnp spec 1.1, section 1.2.2.
|
||||
// TODO: Make IP and port below another #define and replace message below
|
||||
static const QString UPNP_DISCOVER_MESSAGE = "M-SEARCH * HTTP/1.1\r\n"
|
||||
"HOST: 239.255.255.250:1900\r\n"
|
||||
"MAN: \"ssdp:discover\"\r\n"
|
||||
"MX: 1\r\n"
|
||||
"ST: %1\r\n"
|
||||
"\r\n";
|
||||
|
||||
SSDPDiscover::SSDPDiscover(QObject* parent)
|
||||
: QObject(parent)
|
||||
, _log(Logger::getInstance("SSDPDISCOVER"))
|
||||
, _udpSocket(new QUdpSocket(this))
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
void SSDPDiscover::searchForService(const QString& st)
|
||||
{
|
||||
_searchTarget = st;
|
||||
_usnList.clear();
|
||||
// setup socket
|
||||
connect(_udpSocket, &QUdpSocket::readyRead, this, &SSDPDiscover::readPendingDatagrams, Qt::UniqueConnection);
|
||||
|
||||
sendSearch(st);
|
||||
}
|
||||
|
||||
const QString SSDPDiscover::getFirstService(const searchType& type, const QString& st, const int& timeout_ms)
|
||||
{
|
||||
Info(_log, "Search for Hyperion server...");
|
||||
_searchTarget = st;
|
||||
|
||||
// search
|
||||
sendSearch(st);
|
||||
|
||||
_udpSocket->waitForReadyRead(timeout_ms);
|
||||
|
||||
while (_udpSocket->hasPendingDatagrams())
|
||||
{
|
||||
QByteArray datagram;
|
||||
datagram.resize(_udpSocket->pendingDatagramSize());
|
||||
QHostAddress sender;
|
||||
quint16 senderPort;
|
||||
|
||||
_udpSocket->readDatagram(datagram.data(), datagram.size(), &sender, &senderPort);
|
||||
|
||||
QString data(datagram);
|
||||
QMap<QString,QString> headers;
|
||||
QString address;
|
||||
// parse request
|
||||
QStringList entries = data.split("\n", QString::SkipEmptyParts);
|
||||
for(auto entry : entries)
|
||||
{
|
||||
// http header parse skip
|
||||
if(entry.contains("HTTP/1.1"))
|
||||
continue;
|
||||
|
||||
// split into key:vale, be aware that value field may contain also a ":"
|
||||
entry = entry.simplified();
|
||||
int pos = entry.indexOf(":");
|
||||
if(pos == -1)
|
||||
continue;
|
||||
|
||||
headers[entry.left(pos).trimmed().toLower()] = entry.mid(pos+1).trimmed();
|
||||
}
|
||||
|
||||
// verify ssdp spec
|
||||
if(!headers.contains("st"))
|
||||
continue;
|
||||
|
||||
// usn duplicates
|
||||
if (_usnList.contains(headers.value("usn")))
|
||||
continue;
|
||||
|
||||
if (headers.value("st") == _searchTarget)
|
||||
{
|
||||
_usnList << headers.value("usn");
|
||||
QUrl url(headers.value("location"));
|
||||
//Info(_log, "Received msearch response from '%s:%d'. Search target: %s",QSTRING_CSTR(sender.toString()), senderPort, QSTRING_CSTR(headers.value("st")));
|
||||
if(type == STY_WEBSERVER)
|
||||
{
|
||||
Info(_log, "Found Hyperion server at: %s:%d", QSTRING_CSTR(url.host()), url.port());
|
||||
|
||||
return url.host()+":"+QString::number(url.port());
|
||||
}
|
||||
else if(type == STY_FLATBUFSERVER)
|
||||
{
|
||||
const QString fbsport = headers.value("hyperion-fbs-port");
|
||||
if(fbsport.isEmpty())
|
||||
{
|
||||
continue;
|
||||
}
|
||||
else
|
||||
{
|
||||
Info(_log, "Found Hyperion server at: %s:%d", QSTRING_CSTR(url.host()), fbsport);
|
||||
return url.host()+":"+fbsport;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Info(_log,"Search timeout, no Hyperion server found");
|
||||
return QString();
|
||||
}
|
||||
|
||||
void SSDPDiscover::readPendingDatagrams()
|
||||
{
|
||||
while (_udpSocket->hasPendingDatagrams()) {
|
||||
|
||||
QByteArray datagram;
|
||||
datagram.resize(_udpSocket->pendingDatagramSize());
|
||||
QHostAddress sender;
|
||||
quint16 senderPort;
|
||||
|
||||
_udpSocket->readDatagram(datagram.data(), datagram.size(), &sender, &senderPort);
|
||||
|
||||
QString data(datagram);
|
||||
QMap<QString,QString> headers;
|
||||
// parse request
|
||||
QStringList entries = data.split("\n", QString::SkipEmptyParts);
|
||||
for(auto entry : entries)
|
||||
{
|
||||
// http header parse skip
|
||||
if(entry.contains("HTTP/1.1"))
|
||||
continue;
|
||||
|
||||
// split into key:vale, be aware that value field may contain also a ":"
|
||||
entry = entry.simplified();
|
||||
int pos = entry.indexOf(":");
|
||||
if(pos == -1)
|
||||
continue;
|
||||
|
||||
headers[entry.left(pos).trimmed().toLower()] = entry.mid(pos+1).trimmed();
|
||||
}
|
||||
|
||||
// verify ssdp spec
|
||||
if(!headers.contains("st"))
|
||||
continue;
|
||||
|
||||
// usn duplicates
|
||||
if (_usnList.contains(headers.value("usn")))
|
||||
continue;
|
||||
|
||||
if (headers.value("st") == _searchTarget)
|
||||
{
|
||||
_usnList << headers.value("usn");
|
||||
//Info(_log, "Received msearch response from '%s:%d'. Search target: %s",QSTRING_CSTR(sender.toString()), senderPort, QSTRING_CSTR(headers.value("st")));
|
||||
QUrl url(headers.value("location"));
|
||||
emit newService(url.host()+":"+QString::number(url.port()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void SSDPDiscover::sendSearch(const QString& st)
|
||||
{
|
||||
const QString msg = UPNP_DISCOVER_MESSAGE.arg(st);
|
||||
|
||||
_udpSocket->writeDatagram(msg.toUtf8(),
|
||||
QHostAddress(SSDP_ADDR),
|
||||
SSDP_PORT);
|
||||
}
|
144
libsrc/ssdp/SSDPHandler.cpp
Normal file
144
libsrc/ssdp/SSDPHandler.cpp
Normal file
@@ -0,0 +1,144 @@
|
||||
#include <ssdp/SSDPHandler.h>
|
||||
|
||||
#include <webserver/WebServer.h>
|
||||
#include "SSDPDescription.h"
|
||||
#include <hyperion/Hyperion.h>
|
||||
#include <HyperionConfig.h>
|
||||
|
||||
#include <QNetworkInterface>
|
||||
#include <QNetworkConfigurationManager>
|
||||
|
||||
SSDPHandler::SSDPHandler(WebServer* webserver, const quint16& flatBufPort, QObject * parent)
|
||||
: SSDPServer(parent)
|
||||
, _webserver(webserver)
|
||||
, _localAddress()
|
||||
, _NCA(nullptr)
|
||||
{
|
||||
_flatbufPort = flatBufPort;
|
||||
setFlatBufPort(_flatbufPort);
|
||||
}
|
||||
|
||||
void SSDPHandler::initServer()
|
||||
{
|
||||
// prep server
|
||||
SSDPServer::initServer();
|
||||
|
||||
_NCA = new QNetworkConfigurationManager(this);
|
||||
|
||||
// listen for mSearchRequestes
|
||||
connect(this, &SSDPServer::msearchRequestReceived, this, &SSDPHandler::handleMSearchRequest);
|
||||
|
||||
connect(_NCA, &QNetworkConfigurationManager::configurationChanged, this, &SSDPHandler::handleNetworkConfigurationChanged);
|
||||
|
||||
// get localAddress from interface
|
||||
if(!getLocalAddress().isEmpty())
|
||||
{
|
||||
_localAddress = getLocalAddress();
|
||||
}
|
||||
|
||||
// startup if localAddress is found
|
||||
if(!_localAddress.isEmpty() && _webserver->isInited())
|
||||
{
|
||||
handleWebServerStateChange(true);
|
||||
}
|
||||
}
|
||||
|
||||
void SSDPHandler::handleSettingsUpdate(const settings::type& type, const QJsonDocument& config)
|
||||
{
|
||||
if(type == settings::FLATBUFSERVER)
|
||||
{
|
||||
const QJsonObject& obj = config.object();
|
||||
if(obj["port"].toInt() != _flatbufPort)
|
||||
{
|
||||
_flatbufPort = obj["port"].toInt();
|
||||
setFlatBufPort(_flatbufPort);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void SSDPHandler::handleWebServerStateChange(const bool newState)
|
||||
{
|
||||
if(newState)
|
||||
{
|
||||
// refresh info
|
||||
_webserver->setSSDPDescription(buildDesc());
|
||||
setDescriptionAddress(getDescAddress());
|
||||
if(start())
|
||||
{
|
||||
sendAlive("upnp:rootdevice");
|
||||
sendAlive("urn:schemas-upnp-org:device:basic:1");
|
||||
sendAlive("urn:hyperion-project.org:device:basic:1");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
_webserver->setSSDPDescription("");
|
||||
stop();
|
||||
}
|
||||
}
|
||||
|
||||
void SSDPHandler::handleNetworkConfigurationChanged(const QNetworkConfiguration &config)
|
||||
{
|
||||
// get localAddress from interface
|
||||
if(!getLocalAddress().isEmpty())
|
||||
{
|
||||
QString localAddress = getLocalAddress();
|
||||
if(_localAddress != localAddress)
|
||||
{
|
||||
// revoke old ip
|
||||
sendByeBye("upnp:rootdevice");
|
||||
sendByeBye("urn:schemas-upnp-org:device:basic:1");
|
||||
sendByeBye("urn:hyperion-project.org:device:basic:1");
|
||||
|
||||
// update desc & notify new ip
|
||||
_localAddress = localAddress;
|
||||
_webserver->setSSDPDescription(buildDesc());
|
||||
setDescriptionAddress(getDescAddress());
|
||||
sendAlive("upnp:rootdevice");
|
||||
sendAlive("urn:schemas-upnp-org:device:basic:1");
|
||||
sendAlive("urn:hyperion-project.org:device:basic:1");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const QString SSDPHandler::getLocalAddress()
|
||||
{
|
||||
// get the first valid IPv4 address. This is probably not that one we actually want to announce
|
||||
for( const auto & address : QNetworkInterface::allAddresses())
|
||||
{
|
||||
// is valid when, no loopback, IPv4
|
||||
if (!address.isLoopback() && address.protocol() == QAbstractSocket::IPv4Protocol )
|
||||
{
|
||||
return address.toString();
|
||||
}
|
||||
}
|
||||
return QString();
|
||||
}
|
||||
|
||||
void SSDPHandler::handleMSearchRequest(const QString& target, const QString& mx, const QString address, const quint16 & port)
|
||||
{
|
||||
// TODO Response delay according to MX field (sec) random between 0 and MX
|
||||
|
||||
// when searched for all devices / root devices / basic device
|
||||
if(target == "ssdp:all" || target == "upnp:rootdevice" || target == "urn:schemas-upnp-org:device:basic:1" || target == "urn:hyperion-project.org:device:basic:1")
|
||||
sendMSearchResponse(target, address, port);
|
||||
}
|
||||
|
||||
const QString SSDPHandler::getDescAddress()
|
||||
{
|
||||
return getBaseAddress()+"description.xml";
|
||||
}
|
||||
|
||||
const QString SSDPHandler::getBaseAddress()
|
||||
{
|
||||
return "http://"+_localAddress+":"+QString::number(_webserver->getPort())+"/";
|
||||
}
|
||||
|
||||
const QString SSDPHandler::buildDesc()
|
||||
{
|
||||
/// %1 base url http://192.168.0.177:80/
|
||||
/// %2 friendly name Hyperion 2.0.0 (192.168.0.177)
|
||||
/// %3 modelNumber 2.0.0
|
||||
/// %4 serialNumber / UDN (H ID) Fjsa723dD0....
|
||||
return SSDP_DESCRIPTION.arg(getBaseAddress(), QString("Hyperion (%2)").arg(_localAddress), QString(HYPERION_VERSION), Hyperion::getInstance()->getId());
|
||||
}
|
227
libsrc/ssdp/SSDPServer.cpp
Normal file
227
libsrc/ssdp/SSDPServer.cpp
Normal file
@@ -0,0 +1,227 @@
|
||||
#include <ssdp/SSDPServer.h>
|
||||
|
||||
// util
|
||||
#include <utils/SysInfo.h>
|
||||
#include <hyperion/Hyperion.h>
|
||||
#include <HyperionConfig.h>
|
||||
|
||||
#include <QUdpSocket>
|
||||
#include <QDateTime>
|
||||
|
||||
static const QHostAddress SSDP_ADDR("239.255.255.250");
|
||||
static const quint16 SSDP_PORT(1900);
|
||||
static const QString SSDP_MAX_AGE("1800");
|
||||
|
||||
// as per upnp spec 1.1, section 1.2.2.
|
||||
// - BOOTID.UPNP.ORG
|
||||
// - CONFIGID.UPNP.ORG
|
||||
// - SEARCHPORT.UPNP.ORG (optional)
|
||||
// TODO: Make IP and port below another #define and replace message below
|
||||
static const QString UPNP_ALIVE_MESSAGE = "NOTIFY * HTTP/1.1\r\n"
|
||||
"HOST: 239.255.255.250:1900\r\n"
|
||||
"CACHE-CONTROL: max-age=%1\r\n"
|
||||
"LOCATION: %2\r\n"
|
||||
"NT: %3\r\n"
|
||||
"NTS: ssdp:alive\r\n"
|
||||
"SERVER: %4\r\n"
|
||||
"USN: uuid:%5\r\n"
|
||||
"HYPERION-FBS-PORT: %6\r\n"
|
||||
"\r\n";
|
||||
|
||||
// Implement ssdp:update as per spec 1.1, section 1.2.4
|
||||
// and use the below define to build the message, where
|
||||
// SEARCHPORT.UPNP.ORG are optional.
|
||||
// TODO: Make IP and port below another #define and replace message below
|
||||
static const QString UPNP_UPDATE_MESSAGE = "NOTIFY * HTTP/1.1\r\n"
|
||||
"HOST: 239.255.255.250:1900\r\n"
|
||||
"LOCATION: %1\r\n"
|
||||
"NT: %2\r\n"
|
||||
"NTS: ssdp:update\r\n"
|
||||
"USN: uuid:%3\r\n"
|
||||
/* "CONFIGID.UPNP.ORG: %4\r\n"
|
||||
UPNP spec = 1.1 "NEXTBOOTID.UPNP.ORG: %5\r\n"
|
||||
"SEARCHPORT.UPNP.ORG: %6\r\n"
|
||||
*/ "\r\n";
|
||||
|
||||
// TODO: Add this two fields commented below in the BYEBYE MESSAGE
|
||||
// as per upnp spec 1.1, section 1.2.2 and 1.2.3.
|
||||
// - BOOTID.UPNP.ORG
|
||||
// - CONFIGID.UPNP.ORG
|
||||
// TODO: Make IP and port below another #define and replace message below
|
||||
static const QString UPNP_BYEBYE_MESSAGE = "NOTIFY * HTTP/1.1\r\n"
|
||||
"HOST: 239.255.255.250:1900\r\n"
|
||||
"NT: %1\r\n"
|
||||
"NTS: ssdp:byebye\r\n"
|
||||
"USN: uuid:%2\r\n"
|
||||
"\r\n";
|
||||
|
||||
// TODO: Add this three fields commented below in the MSEARCH_RESPONSE
|
||||
// as per upnp spec 1.1, section 1.3.3.
|
||||
// - BOOTID.UPNP.ORG
|
||||
// - CONFIGID.UPNP.ORG
|
||||
// - SEARCHPORT.UPNP.ORG (optional)
|
||||
static const QString UPNP_MSEARCH_RESPONSE = "HTTP/1.1 200 OK\r\n"
|
||||
"CACHE-CONTROL: max-age = %1\r\n"
|
||||
"DATE: %2\r\n"
|
||||
"EXT: \r\n"
|
||||
"LOCATION: %3\r\n"
|
||||
"SERVER: %4\r\n"
|
||||
"ST: %5\r\n"
|
||||
"USN: uuid:%6\r\n"
|
||||
"HYPERION-FBS-PORT: %7\r\n"
|
||||
"\r\n";
|
||||
|
||||
SSDPServer::SSDPServer(QObject * parent)
|
||||
: QObject(parent)
|
||||
, _log(Logger::getInstance("SSDP"))
|
||||
, _udpSocket(nullptr)
|
||||
, _running(false)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
SSDPServer::~SSDPServer()
|
||||
{
|
||||
stop();
|
||||
}
|
||||
|
||||
void SSDPServer::initServer()
|
||||
{
|
||||
_udpSocket = new QUdpSocket(this);
|
||||
|
||||
// get system info
|
||||
SysInfo::HyperionSysInfo data = SysInfo::get();
|
||||
|
||||
// create SERVER String
|
||||
_serverHeader = data.prettyName+"/"+data.productVersion+" UPnP/1.0 Hyperion/"+QString(HYPERION_VERSION);
|
||||
|
||||
// usn uuid
|
||||
_uuid = Hyperion::getInstance()->getId();
|
||||
|
||||
connect(_udpSocket, &QUdpSocket::readyRead, this, &SSDPServer::readPendingDatagrams);
|
||||
}
|
||||
|
||||
const bool SSDPServer::start()
|
||||
{
|
||||
if(!_running && _udpSocket->bind(QHostAddress::AnyIPv4, SSDP_PORT, QAbstractSocket::ShareAddress))
|
||||
{
|
||||
_udpSocket->joinMulticastGroup(SSDP_ADDR);
|
||||
_running = true;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void SSDPServer::stop()
|
||||
{
|
||||
if(_running)
|
||||
{
|
||||
// send BYEBYE Msg
|
||||
sendByeBye("upnp:rootdevice");
|
||||
sendByeBye("urn:schemas-upnp-org:device:basic:1");
|
||||
sendByeBye("urn:hyperion-project.org:device:basic:1");
|
||||
_udpSocket->close();
|
||||
_running = false;
|
||||
}
|
||||
}
|
||||
|
||||
void SSDPServer::readPendingDatagrams()
|
||||
{
|
||||
while (_udpSocket->hasPendingDatagrams()) {
|
||||
|
||||
QByteArray datagram;
|
||||
datagram.resize(_udpSocket->pendingDatagramSize());
|
||||
QHostAddress sender;
|
||||
quint16 senderPort;
|
||||
|
||||
_udpSocket->readDatagram(datagram.data(), datagram.size(), &sender, &senderPort);
|
||||
|
||||
QString data(datagram);
|
||||
QMap<QString,QString> headers;
|
||||
// parse request
|
||||
QStringList entries = data.split("\n", QString::SkipEmptyParts);
|
||||
for(auto entry : entries)
|
||||
{
|
||||
// http header parse skip
|
||||
if(entry.contains("HTTP/1.1"))
|
||||
continue;
|
||||
|
||||
// split into key:vale, be aware that value field may contain also a ":"
|
||||
entry = entry.simplified();
|
||||
int pos = entry.indexOf(":");
|
||||
if(pos == -1)
|
||||
continue;
|
||||
|
||||
headers[entry.left(pos).trimmed().toLower()] = entry.mid(pos+1).trimmed();
|
||||
}
|
||||
|
||||
// verify ssdp spec
|
||||
if(!headers.contains("man"))
|
||||
continue;
|
||||
|
||||
if (headers.value("man") == "\"ssdp:discover\"")
|
||||
{
|
||||
//Debug(_log, "Received msearch from '%s:%d'. Search target: %s",QSTRING_CSTR(sender.toString()), senderPort, QSTRING_CSTR(headers.value("st")));
|
||||
emit msearchRequestReceived(headers.value("st"), headers.value("mx"), sender.toString(), senderPort);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void SSDPServer::sendMSearchResponse(const QString& st, const QString& senderIp, const quint16& senderPort)
|
||||
{
|
||||
QString message = UPNP_MSEARCH_RESPONSE.arg(SSDP_MAX_AGE
|
||||
, QDateTime::currentDateTimeUtc().toString("ddd, dd MMM yyyy HH:mm:ss GMT")
|
||||
, _descAddress
|
||||
, _serverHeader
|
||||
, st
|
||||
, _uuid
|
||||
, _fbsPort );
|
||||
|
||||
_udpSocket->writeDatagram(message.toUtf8(),
|
||||
QHostAddress(senderIp),
|
||||
senderPort);
|
||||
}
|
||||
|
||||
void SSDPServer::sendByeBye(const QString& st)
|
||||
{
|
||||
QString message = UPNP_BYEBYE_MESSAGE.arg(st, _uuid+"::"+st );
|
||||
|
||||
// we repeat 3 times
|
||||
quint8 rep = 0;
|
||||
while(rep < 3) {
|
||||
_udpSocket->writeDatagram(message.toUtf8(),
|
||||
QHostAddress(SSDP_ADDR),
|
||||
SSDP_PORT);
|
||||
rep++;
|
||||
}
|
||||
}
|
||||
|
||||
void SSDPServer::sendAlive(const QString& st)
|
||||
{
|
||||
QString message = UPNP_ALIVE_MESSAGE.arg(SSDP_MAX_AGE
|
||||
, _descAddress
|
||||
, st
|
||||
, _serverHeader
|
||||
, _uuid+"::"+st
|
||||
, _fbsPort);
|
||||
|
||||
// we repeat 3 times
|
||||
quint8 rep = 0;
|
||||
while(rep < 3) {
|
||||
_udpSocket->writeDatagram(message.toUtf8(),
|
||||
QHostAddress(SSDP_ADDR),
|
||||
SSDP_PORT);
|
||||
rep++;
|
||||
}
|
||||
}
|
||||
|
||||
void SSDPServer::sendUpdate(const QString& st)
|
||||
{
|
||||
QString message = UPNP_UPDATE_MESSAGE.arg(_descAddress
|
||||
, st
|
||||
, _uuid+"::"+st );
|
||||
|
||||
_udpSocket->writeDatagram(message.toUtf8(),
|
||||
QHostAddress(SSDP_ADDR),
|
||||
SSDP_PORT);
|
||||
}
|
@@ -22,8 +22,6 @@ UDPListener::UDPListener(const QJsonDocument& config) :
|
||||
_isActive(false),
|
||||
_listenPort(0)
|
||||
{
|
||||
Debug(_log, "Instance created");
|
||||
|
||||
// init
|
||||
handleSettingsUpdate(settings::UDPLISTENER, config);
|
||||
}
|
||||
|
@@ -49,7 +49,7 @@ public:
|
||||
quint16 getServerPort (void) const;
|
||||
QString getErrorString (void) const;
|
||||
|
||||
// const bool isListening(void) { return m_sockServer->isListening(); };
|
||||
const bool isListening(void) { return m_sockServer->isListening(); };
|
||||
|
||||
public slots:
|
||||
void start (quint16 port = 0);
|
||||
|
@@ -32,6 +32,14 @@ void StaticFileServing::setBaseUrl(const QString& url)
|
||||
_cgi.setBaseUrl(url);
|
||||
}
|
||||
|
||||
void StaticFileServing::setSSDPDescription(const QString& desc)
|
||||
{
|
||||
if(desc.isEmpty())
|
||||
_ssdpDescription.clear();
|
||||
else
|
||||
_ssdpDescription = desc.toLocal8Bit();
|
||||
}
|
||||
|
||||
void StaticFileServing::printErrorToReply (QtHttpReply * reply, QtHttpReply::StatusCode code, QString errorMessage)
|
||||
{
|
||||
reply->setStatusCode(code);
|
||||
@@ -76,24 +84,33 @@ void StaticFileServing::onRequestNeedsReply (QtHttpRequest * request, QtHttpRepl
|
||||
QStringList uri_parts = path.split('/', QString::SkipEmptyParts);
|
||||
|
||||
// special uri handling for server commands
|
||||
if ( ! uri_parts.empty() && uri_parts.at(0) == "cgi" )
|
||||
if ( ! uri_parts.empty() )
|
||||
{
|
||||
uri_parts.removeAt(0);
|
||||
try
|
||||
if(uri_parts.at(0) == "cgi")
|
||||
{
|
||||
_cgi.exec(uri_parts, request, reply);
|
||||
uri_parts.removeAt(0);
|
||||
try
|
||||
{
|
||||
_cgi.exec(uri_parts, request, reply);
|
||||
}
|
||||
catch(int err)
|
||||
{
|
||||
Error(_log,"Exception while executing cgi %s : %d", path.toStdString().c_str(), err);
|
||||
printErrorToReply (reply, QtHttpReply::InternalError, "script failed (" % path % ")");
|
||||
}
|
||||
catch(std::exception &e)
|
||||
{
|
||||
Error(_log,"Exception while executing cgi %s : %s", path.toStdString().c_str(), e.what());
|
||||
printErrorToReply (reply, QtHttpReply::InternalError, "script failed (" % path % ")");
|
||||
}
|
||||
return;
|
||||
}
|
||||
catch(int err)
|
||||
else if(uri_parts.at(0) == "description.xml" && !_ssdpDescription.isNull())
|
||||
{
|
||||
Error(_log,"Exception while executing cgi %s : %d", path.toStdString().c_str(), err);
|
||||
printErrorToReply (reply, QtHttpReply::InternalError, "script failed (" % path % ")");
|
||||
reply->addHeader ("Content-Type", "text/xml");
|
||||
reply->appendRawData (_ssdpDescription);
|
||||
return;
|
||||
}
|
||||
catch(std::exception &e)
|
||||
{
|
||||
Error(_log,"Exception while executing cgi %s : %s", path.toStdString().c_str(), e.what());
|
||||
printErrorToReply (reply, QtHttpReply::InternalError, "script failed (" % path % ")");
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
QFileInfo info(_baseUrl % "/" % path);
|
||||
|
@@ -1,16 +1,14 @@
|
||||
#ifndef STATICFILESERVING_H
|
||||
#define STATICFILESERVING_H
|
||||
|
||||
// locales includes
|
||||
#include "CgiHandler.h"
|
||||
|
||||
// qt includes
|
||||
#include <QMimeDatabase>
|
||||
|
||||
//#include "QtHttpServer.h"
|
||||
#include "QtHttpRequest.h"
|
||||
#include "QtHttpReply.h"
|
||||
#include "QtHttpHeader.h"
|
||||
#include "CgiHandler.h"
|
||||
|
||||
//utils includes
|
||||
#include <utils/Logger.h>
|
||||
|
||||
class StaticFileServing : public QObject {
|
||||
@@ -20,7 +18,15 @@ public:
|
||||
explicit StaticFileServing (QObject * parent = nullptr);
|
||||
virtual ~StaticFileServing (void);
|
||||
|
||||
///
|
||||
/// @brief Overwrite current base url
|
||||
///
|
||||
void setBaseUrl(const QString& url);
|
||||
///
|
||||
/// @brief Set a new SSDP description, if empty the description will be unset and clients will get a NotFound
|
||||
/// @param The description
|
||||
///
|
||||
void setSSDPDescription(const QString& desc);
|
||||
|
||||
public slots:
|
||||
void onRequestNeedsReply (QtHttpRequest * request, QtHttpReply * reply);
|
||||
@@ -30,6 +36,7 @@ private:
|
||||
QMimeDatabase * _mimeDb;
|
||||
CgiHandler _cgi;
|
||||
Logger * _log;
|
||||
QByteArray _ssdpDescription;
|
||||
|
||||
void printErrorToReply (QtHttpReply * reply, QtHttpReply::StatusCode code, QString errorMessage);
|
||||
|
||||
|
@@ -1,23 +1,34 @@
|
||||
#include "webserver/WebServer.h"
|
||||
#include "StaticFileServing.h"
|
||||
|
||||
// qt includes
|
||||
#include "QtHttpServer.h"
|
||||
|
||||
#include <QFileInfo>
|
||||
#include <QJsonObject>
|
||||
|
||||
// bonjour includes
|
||||
// bonjour
|
||||
#include <bonjour/bonjourserviceregister.h>
|
||||
#include <bonjour/bonjourrecord.h>
|
||||
|
||||
// utils includes
|
||||
// netUtil
|
||||
#include <utils/NetUtils.h>
|
||||
|
||||
|
||||
WebServer::WebServer(const QJsonDocument& config, QObject * parent)
|
||||
: QObject(parent)
|
||||
, _config(config)
|
||||
, _log(Logger::getInstance("WEBSERVER"))
|
||||
, _server(new QtHttpServer (this))
|
||||
, _server()
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
WebServer::~WebServer()
|
||||
{
|
||||
stop();
|
||||
}
|
||||
|
||||
void WebServer::initServer()
|
||||
{
|
||||
_server = new QtHttpServer (this);
|
||||
_server->setServerName (QStringLiteral ("Hyperion Webserver"));
|
||||
|
||||
connect (_server, &QtHttpServer::started, this, &WebServer::onServerStarted);
|
||||
@@ -28,18 +39,14 @@ WebServer::WebServer(const QJsonDocument& config, QObject * parent)
|
||||
_staticFileServing = new StaticFileServing (this);
|
||||
connect(_server, &QtHttpServer::requestNeedsReply, _staticFileServing, &StaticFileServing::onRequestNeedsReply);
|
||||
|
||||
Debug(_log, "Instance created");
|
||||
// init
|
||||
handleSettingsUpdate(settings::WEBSERVER, config);
|
||||
}
|
||||
|
||||
WebServer::~WebServer()
|
||||
{
|
||||
stop();
|
||||
handleSettingsUpdate(settings::WEBSERVER, _config);
|
||||
}
|
||||
|
||||
void WebServer::onServerStarted (quint16 port)
|
||||
{
|
||||
_inited= true;
|
||||
|
||||
Info(_log, "Started on port %d name '%s'", port ,_server->getServerName().toStdString().c_str());
|
||||
|
||||
if(_serviceRegister == nullptr)
|
||||
@@ -53,10 +60,12 @@ void WebServer::onServerStarted (quint16 port)
|
||||
_serviceRegister = new BonjourServiceRegister(this);
|
||||
_serviceRegister->registerService("_hyperiond-http._tcp", port);
|
||||
}
|
||||
emit stateChange(true);
|
||||
}
|
||||
|
||||
void WebServer::onServerStopped () {
|
||||
Info(_log, "Stopped %s", _server->getServerName().toStdString().c_str());
|
||||
emit stateChange(false);
|
||||
}
|
||||
|
||||
void WebServer::onServerError (QString msg)
|
||||
@@ -72,6 +81,7 @@ void WebServer::handleSettingsUpdate(const settings::type& type, const QJsonDocu
|
||||
|
||||
_baseUrl = obj["document_root"].toString(WEBSERVER_DEFAULT_PATH);
|
||||
|
||||
|
||||
if ( (_baseUrl != ":/webconfig") && !_baseUrl.trimmed().isEmpty())
|
||||
{
|
||||
QFileInfo info(_baseUrl);
|
||||
@@ -94,8 +104,11 @@ void WebServer::handleSettingsUpdate(const settings::type& type, const QJsonDocu
|
||||
}
|
||||
|
||||
// eval if the port is available, will be incremented if not
|
||||
NetUtils::portAvailable(_port, _log);
|
||||
if(!_server->isListening())
|
||||
NetUtils::portAvailable(_port, _log);
|
||||
|
||||
start();
|
||||
emit portChanged(_port);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -108,3 +121,8 @@ void WebServer::stop()
|
||||
{
|
||||
_server->stop();
|
||||
}
|
||||
|
||||
void WebServer::setSSDPDescription(const QString & desc)
|
||||
{
|
||||
_staticFileServing->setSSDPDescription(desc);
|
||||
}
|
||||
|
Reference in New Issue
Block a user