remove protobuf (part 2)

This commit is contained in:
Paulchen-Panther 2018-12-30 22:07:53 +01:00
parent 559311e18c
commit 38950edf35
54 changed files with 1441 additions and 377 deletions

View File

@ -56,7 +56,7 @@ public:
/// ///
/// @param message the incoming message as string /// @param message the incoming message as string
/// ///
void handleMessage(const QString & message, const QString& httpAuthHeader = ""); void handleMessage(const QString & message);
public slots: public slots:
/// _timer_ledcolors requests ledcolor updates (if enabled) /// _timer_ledcolors requests ledcolor updates (if enabled)

View File

@ -28,23 +28,29 @@ class FlatBufferConnection : public QObject
public: public:
/// ///
/// Constructor /// @brief Constructor
///
/// @param address The address of the Hyperion server (for example "192.168.0.32:19444) /// @param address The address of the Hyperion server (for example "192.168.0.32:19444)
/// @param skipReply If true skip reply
/// ///
FlatBufferConnection(const QString & address); FlatBufferConnection(const QString& origin, const QString & address, const int& priority, const bool& skipReply);
/// ///
/// Destructor /// @brief Destructor
/// ///
~FlatBufferConnection(); ~FlatBufferConnection();
/// Do not read reply messages from Hyperion if set to true /// @brief Do not read reply messages from Hyperion if set to true
void setSkipReply(const bool& skip); void setSkipReply(const bool& skip);
/// ///
/// Set all leds to the specified color /// @brief Register a new priority with given origin
/// @param origin The user friendly origin string
/// @param priority The priority to register
/// ///
void setRegister(const QString& origin, int priority);
///
/// @brief Set all leds to the specified color
/// @param color The color /// @param color The color
/// @param priority The priority /// @param priority The priority
/// @param duration The duration in milliseconds /// @param duration The duration in milliseconds
@ -52,64 +58,63 @@ public:
void setColor(const ColorRgb & color, int priority, int duration = 1); void setColor(const ColorRgb & color, int priority, int duration = 1);
/// ///
/// Set the leds according to the given image (assume the image is stretched to the display size) /// @brief Clear the given priority channel
///
/// @param image The image
/// @param priority The priority
/// @param duration The duration in milliseconds
///
void setImage(const Image<ColorRgb> & image, int priority, int duration = -1);
///
/// Clear the given priority channel
///
/// @param priority The priority /// @param priority The priority
/// ///
void clear(int priority); void clear(int priority);
/// ///
/// Clear all priority channels /// @brief Clear all priority channels
/// ///
void clearAll(); void clearAll();
/// ///
/// Send a command message and receive its reply /// @brief Send a command message and receive its reply
///
/// @param message The message to send /// @param message The message to send
/// ///
void sendMessage(const uint8_t* buffer, uint32_t size); void sendMessage(const uint8_t* buffer, uint32_t size);
public slots:
///
/// @brief Set the leds according to the given image
/// @param image The image
///
void setImage(const Image<ColorRgb> &image);
private slots: private slots:
/// Try to connect to the Hyperion host ///
/// @brief Try to connect to the Hyperion host
///
void connectToHost(); void connectToHost();
/// ///
/// Slot called when new data has arrived /// @brief Slot called when new data has arrived
/// ///
void readData(); void readData();
signals: signals:
/// ///
/// emits when a new videoMode was requested from flatbuf client /// @brief emits when a new videoMode was requested from flatbuf client
/// ///
void setVideoMode(const VideoMode videoMode); void setVideoMode(const VideoMode videoMode);
private: private:
/// ///
/// Parse a reply message /// @brief Parse a reply message
///
/// @param reply The received reply /// @param reply The received reply
///
/// @return true if the reply indicates success /// @return true if the reply indicates success
/// ///
bool parseReply(const flatbuf::HyperionReply * reply); bool parseReply(const hyperionnet::Reply *reply);
private: private:
/// The TCP-Socket with the connection to the server /// The TCP-Socket with the connection to the server
QTcpSocket _socket; QTcpSocket _socket;
QString _origin;
int _priority;
/// Host address /// Host address
QString _host; QString _host;
@ -124,4 +129,6 @@ private:
Logger * _log; Logger * _log;
flatbuffers::FlatBufferBuilder _builder; flatbuffers::FlatBufferBuilder _builder;
bool _registered;
}; };

View File

@ -24,8 +24,8 @@ public:
public slots: public slots:
/// ///
/// @brief Handle settings update /// @brief Handle settings update
/// @param type The type from enum /// @param type The type from enum
/// @param config The configuration /// @param config The configuration
/// ///
void handleSettingsUpdate(const settings::type& type, const QJsonDocument& config); void handleSettingsUpdate(const settings::type& type, const QJsonDocument& config);

View File

@ -0,0 +1,56 @@
#pragma once
#include <utils/Logger.h>
#include <QHostAddress>
class QUdpSocket;
enum searchType{
STY_WEBSERVER,
STY_FLATBUFSERVER
};
///
/// @brief Search for SSDP sessions, used by standalone capture binaries
///
class SSDPDiscover : public QObject
{
Q_OBJECT
public:
SSDPDiscover(QObject* parent = nullptr);
///
/// @brief Search for specified service, results will be returned by signal newService(). Calling this method again will reset all found usns and search again
/// @param st The service to search for
///
void searchForService(const QString& st = "urn:hyperion-project.org:device:basic:1");
///
/// @brief Search for specified searchTarget, the method will block until a server has been found or a timeout happend
/// @param type The address type one of struct searchType
/// @param st The service to search for
/// @param timeout_ms The timeout in ms
/// @return The address+port of webserver or empty if timed out
///
const QString getFirstService(const searchType& type = STY_WEBSERVER,const QString& st = "urn:hyperion-project.org:device:basic:1", const int& timeout_ms = 3000);
signals:
///
/// @brief Emits whenever a new service has ben found, search started with searchForService()
/// @param webServer The address+port of webserver "192.168.0.10:8090"
///
void newService(const QString webServer);
private slots:
void readPendingDatagrams();
private:
void sendSearch(const QString& st);
private:
Logger* _log;
QUdpSocket* _udpSocket;
QString _searchTarget;
QStringList _usnList;
};

View File

@ -0,0 +1,81 @@
#pragma once
#include <ssdp/SSDPServer.h>
#include <QNetworkConfiguration>
// utils
#include <utils/settings.h>
class WebServer;
class QNetworkConfigurationManager;
///
/// Manage SSDP discovery. SimpleServiceDisoveryProtocol is the discovery subset of UPnP. Implemented is spec V1.0.
/// As SSDP requires a webserver, this class depends on it
/// UPnP 1.0: spec: http://upnp.org/specs/arch/UPnP-arch-DeviceArchitecture-v1.0.pdf
///
class SSDPHandler : public SSDPServer{
Q_OBJECT
public:
SSDPHandler(WebServer* webserver, const quint16& flatBufPort, QObject * parent = nullptr);
public slots:
///
/// @brief Init SSDP after thread start
///
void initServer();
///
/// @brief get state changes from webserver
///
void handleWebServerStateChange(const bool newState);
///
/// @brief Handle settings update from Hyperion Settingsmanager emit
/// @param type settingyType from enum
/// @param config configuration object
///
void handleSettingsUpdate(const settings::type& type, const QJsonDocument& config);
private:
///
/// @brief Build http url for current ip:port/desc.xml
///
const QString getDescAddress();
///
/// @brief Get the base address
///
const QString getBaseAddress();
///
/// @brief Build the ssdp description (description.xml)
///
const QString buildDesc();
///
/// @brief Get the local address of interface
/// @return the address, might be empty
///
const QString getLocalAddress();
private slots:
///
/// @brief Handle the mSeach request from SSDPServer
/// @param target The ST service type
/// @param mx Answer with delay in s
/// @param address The ip of the caller
/// @param port The port of the caller
///
void handleMSearchRequest(const QString& target, const QString& mx, const QString address, const quint16 & port);
void handleNetworkConfigurationChanged(const QNetworkConfiguration &config);
private:
WebServer* _webserver;
QString _localAddress;
QNetworkConfigurationManager* _NCA;
quint16 _flatbufPort;
};

98
include/ssdp/SSDPServer.h Normal file
View File

@ -0,0 +1,98 @@
#pragma once
#include <utils/Logger.h>
class QUdpSocket;
///
/// @brief The SSDP Server sends and receives (parses) SSDP requests
///
class SSDPServer : public QObject {
Q_OBJECT
public:
friend class SSDPHandler;
///
/// @brief Construct the server, listen on default ssdp address/port with multicast
/// @param parent The parent object
///
SSDPServer(QObject* parent = nullptr);
virtual ~SSDPServer();
///
/// @brief Prepare server after thread start
///
void initServer();
///
/// @brief Start SSDP
/// @return false if already running or bind failure
///
const bool start();
///
/// @brief Stop SSDP
///
void stop();
///
/// @brief Send an answer to mSearch requester
/// @param st the searchTarget
/// @param senderIp Ip address of the sender
/// @param senderPort The port of the sender
///
void sendMSearchResponse(const QString& st, const QString& senderIp, const quint16& senderPort);
///
/// @brief Send ByeBye notification (on SSDP stop) (repeated 3 times)
/// @param st Search target
///
void sendByeBye(const QString& st);
///
/// @brief Send a NOTIFY msg on SSDP startup to notify our presence (repeated 3 times)
/// @param st The search target
///
void sendAlive(const QString& st);
///
/// @brief Send a NOTIFY msg as ssdp:update to notify about changes
/// @param st The search target
///
void sendUpdate(const QString& st);
///
/// @brief Overwrite description address
/// @param addr new address
///
void setDescriptionAddress(const QString& addr) { _descAddress = addr; };
///
/// @brief set new flatbuffer server port
///
void setFlatBufPort(const quint16& port) { _fbsPort = QString::number(port); };
signals:
///
/// @brief Emits whenever a new SSDP search "man : ssdp:discover" is received along with the service type
/// @param target The ST service type
/// @param mx Answer with delay in s
/// @param address The ip of the caller
/// @param port The port of the caller
///
void msearchRequestReceived(const QString& target, const QString& mx, const QString address, const quint16 & port);
private:
Logger* _log;
QUdpSocket* _udpSocket;
QString _serverHeader;
QString _uuid;
QString _fbsPort;
QString _descAddress;
bool _running;
private slots:
void readPendingDatagrams();
};

View File

@ -21,7 +21,6 @@ enum Components
COMP_COLOR, COMP_COLOR,
COMP_IMAGE, COMP_IMAGE,
COMP_EFFECT, COMP_EFFECT,
COMP_PROTOSERVER,
COMP_LEDDEVICE, COMP_LEDDEVICE,
COMP_FLATBUFSERVER COMP_FLATBUFSERVER
}; };
@ -41,7 +40,6 @@ inline const char* componentToString(Components c)
case COMP_COLOR: return "Solid color"; case COMP_COLOR: return "Solid color";
case COMP_EFFECT: return "Effect"; case COMP_EFFECT: return "Effect";
case COMP_IMAGE: return "Image"; case COMP_IMAGE: return "Image";
case COMP_PROTOSERVER: return "Proto Server";
case COMP_LEDDEVICE: return "LED device"; case COMP_LEDDEVICE: return "LED device";
case COMP_FLATBUFSERVER: return "Image Receiver"; case COMP_FLATBUFSERVER: return "Image Receiver";
default: return ""; default: return "";
@ -63,7 +61,6 @@ inline const char* componentToIdString(Components c)
case COMP_COLOR: return "COLOR"; case COMP_COLOR: return "COLOR";
case COMP_EFFECT: return "EFFECT"; case COMP_EFFECT: return "EFFECT";
case COMP_IMAGE: return "IMAGE"; case COMP_IMAGE: return "IMAGE";
case COMP_PROTOSERVER: return "PROTOSERVER";
case COMP_LEDDEVICE: return "LEDDEVICE"; case COMP_LEDDEVICE: return "LEDDEVICE";
case COMP_FLATBUFSERVER: return "FLATBUFSERVER"; case COMP_FLATBUFSERVER: return "FLATBUFSERVER";
default: return ""; default: return "";
@ -84,7 +81,6 @@ inline Components stringToComponent(QString component)
if (component == "COLOR") return COMP_COLOR; if (component == "COLOR") return COMP_COLOR;
if (component == "EFFECT") return COMP_EFFECT; if (component == "EFFECT") return COMP_EFFECT;
if (component == "IMAGE") return COMP_IMAGE; if (component == "IMAGE") return COMP_IMAGE;
if (component == "PROTOSERVER") return COMP_PROTOSERVER;
if (component == "LEDDEVICE") return COMP_LEDDEVICE; if (component == "LEDDEVICE") return COMP_LEDDEVICE;
if (component == "FLATBUFSERVER") return COMP_FLATBUFSERVER; if (component == "FLATBUFSERVER") return COMP_FLATBUFSERVER;
return COMP_INVALID; return COMP_INVALID;

View File

@ -240,7 +240,7 @@ public:
/// ///
/// get size of buffer /// get size of buffer
// //
ssize_t size() ssize_t size() const
{ {
return _width * _height * sizeof(Pixel_T); return _width * _height * sizeof(Pixel_T);
} }

View File

@ -23,7 +23,6 @@ enum type {
LEDCONFIG, LEDCONFIG,
LEDS, LEDS,
LOGGER, LOGGER,
PROTOSERVER,
SMOOTHING, SMOOTHING,
UDPLISTENER, UDPLISTENER,
WEBSERVER, WEBSERVER,
@ -57,7 +56,6 @@ inline QString typeToString(const type& type)
case LEDCONFIG: return "ledConfig"; case LEDCONFIG: return "ledConfig";
case LEDS: return "leds"; case LEDS: return "leds";
case LOGGER: return "logger"; case LOGGER: return "logger";
case PROTOSERVER: return "protoServer";
case SMOOTHING: return "smoothing"; case SMOOTHING: return "smoothing";
case UDPLISTENER: return "udpListener"; case UDPLISTENER: return "udpListener";
case WEBSERVER: return "webConfig"; case WEBSERVER: return "webConfig";
@ -90,7 +88,6 @@ inline type stringToType(const QString& type)
else if (type == "ledConfig") return LEDCONFIG; else if (type == "ledConfig") return LEDCONFIG;
else if (type == "leds") return LEDS; else if (type == "leds") return LEDS;
else if (type == "logger") return LOGGER; else if (type == "logger") return LOGGER;
else if (type == "protoServer") return PROTOSERVER;
else if (type == "smoothing") return SMOOTHING; else if (type == "smoothing") return SMOOTHING;
else if (type == "udpListener") return UDPLISTENER; else if (type == "udpListener") return UDPLISTENER;
else if (type == "webConfig") return WEBSERVER; else if (type == "webConfig") return WEBSERVER;

View File

@ -5,7 +5,7 @@
#include <QString> #include <QString>
#include <QJsonDocument> #include <QJsonDocument>
// utils include // hyperion / utils
#include <utils/Logger.h> #include <utils/Logger.h>
// settings // settings
@ -28,7 +28,32 @@ public:
quint16 getPort() { return _port; }; quint16 getPort() { return _port; };
/// check if server has been inited
const bool isInited() { return _inited; };
///
/// @brief Set a new description, if empty the description is NotFound for clients
///
void setSSDPDescription(const QString & desc);
signals:
///
/// @emits whenever server is started or stopped (to sync with SSDPHandler)
/// @param newState True when started, false when stopped
///
void stateChange(const bool newState);
///
/// @brief Emits whenever the port changes (doesn't compare prev <> now)
///
void portChanged(const quint16& port);
public slots: public slots:
///
/// @brief Init server after thread start
///
void initServer();
void onServerStopped (void); void onServerStopped (void);
void onServerStarted (quint16 port); void onServerStarted (quint16 port);
void onServerError (QString msg); void onServerError (QString msg);
@ -41,11 +66,13 @@ public slots:
void handleSettingsUpdate(const settings::type& type, const QJsonDocument& config); void handleSettingsUpdate(const settings::type& type, const QJsonDocument& config);
private: private:
QJsonDocument _config;
Logger* _log; Logger* _log;
QString _baseUrl; QString _baseUrl;
quint16 _port; quint16 _port;
StaticFileServing* _staticFileServing; StaticFileServing* _staticFileServing;
QtHttpServer* _server; QtHttpServer* _server;
bool _inited = false;
const QString WEBSERVER_DEFAULT_PATH = ":/webconfig"; const QString WEBSERVER_DEFAULT_PATH = ":/webconfig";
const quint16 WEBSERVER_DEFAULT_PORT = 8090; const quint16 WEBSERVER_DEFAULT_PORT = 8090;

View File

@ -7,9 +7,9 @@ add_subdirectory(hyperion)
add_subdirectory(commandline) add_subdirectory(commandline)
add_subdirectory(blackborder) add_subdirectory(blackborder)
add_subdirectory(jsonserver) add_subdirectory(jsonserver)
add_subdirectory(protoserver)
add_subdirectory(flatbufserver) add_subdirectory(flatbufserver)
add_subdirectory(bonjour) add_subdirectory(bonjour)
add_subdirectory(ssdp)
add_subdirectory(boblightserver) add_subdirectory(boblightserver)
add_subdirectory(udplistener) add_subdirectory(udplistener)
add_subdirectory(leddevice) add_subdirectory(leddevice)

View File

@ -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 // 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); connect(_jsonCB, &JsonCB::newCallback, this, &JsonAPI::callbackMessage);
// notify hyperion about a jsonMessageForward // notify hyperion about a jsonMessageForward
connect(this, &JsonAPI::forwardJsonMessage, _hyperion, &Hyperion::forwardJsonMessage); 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(); _image_stream_mutex.unlock();
} }
void JsonAPI::handleMessage(const QString& messageString, const QString& httpAuthHeader) void JsonAPI::handleMessage(const QString& messageString)
{ {
const QString ident = "JsonRpc@"+_peerAddress; const QString ident = "JsonRpc@"+_peerAddress;
Q_INIT_RESOURCE(JSONRPC_schemas); 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["success"] = true;
_streaming_leds_reply["command"] = command+"-ledstream-update"; _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); _timer_ledcolors.start(125);
} }
else if (subcommand == "ledstream-stop") 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["success"] = true;
_streaming_image_reply["command"] = command+"-imagestream-update"; _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); connect(_hyperion, &Hyperion::currentImage, this, &JsonAPI::setImage, Qt::UniqueConnection);
} }
else if (subcommand == "imagestream-stop") else if (subcommand == "imagestream-stop")

View File

@ -14,6 +14,9 @@ BonjourBrowserWrapper::BonjourBrowserWrapper(QObject * parent)
, _bonjourResolver(new BonjourServiceResolver(this)) , _bonjourResolver(new BonjourServiceResolver(this))
, _timerBonjourResolver( new QTimer(this)) , _timerBonjourResolver( new QTimer(this))
{ {
// register meta
qRegisterMetaType<QMap<QString,BonjourRecord>>("QMap<QString,BonjourRecord>");
BonjourBrowserWrapper::instance = this; BonjourBrowserWrapper::instance = this;
connect(_bonjourResolver, &BonjourServiceResolver::bonjourRecordResolved, this, &BonjourBrowserWrapper::bonjourRecordResolved); connect(_bonjourResolver, &BonjourServiceResolver::bonjourRecordResolved, this, &BonjourBrowserWrapper::bonjourRecordResolved);

View File

@ -58,6 +58,9 @@ Effect::~Effect()
void Effect::run() void Effect::run()
{ {
// we probably need to wait until mainThreadState is available
while(mainThreadState == nullptr){};
// get global lock // get global lock
PyEval_RestoreThread(mainThreadState); PyEval_RestoreThread(mainThreadState);

View File

@ -4,6 +4,7 @@
#include <QTcpSocket> #include <QTcpSocket>
#include <QHostAddress> #include <QHostAddress>
#include <QTimer> #include <QTimer>
#include <QRgb>
#include <hyperion/Hyperion.h> #include <hyperion/Hyperion.h>
#include <QDebug> #include <QDebug>
@ -11,7 +12,7 @@ FlatBufferClient::FlatBufferClient(QTcpSocket* socket, const int &timeout, QObje
: QObject(parent) : QObject(parent)
, _log(Logger::getInstance("FLATBUFSERVER")) , _log(Logger::getInstance("FLATBUFSERVER"))
, _socket(socket) , _socket(socket)
, _clientAddress(socket->peerAddress().toString()) , _clientAddress("@"+socket->peerAddress().toString())
, _timeoutTimer(new QTimer(this)) , _timeoutTimer(new QTimer(this))
, _timeout(timeout * 1000) , _timeout(timeout * 1000)
, _priority() , _priority()
@ -49,12 +50,12 @@ void FlatBufferClient::readyRead()
const QByteArray msg = _receiveBuffer.right(messageSize); const QByteArray msg = _receiveBuffer.right(messageSize);
_receiveBuffer.remove(0, messageSize + 4); _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); 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); handleMessage(message);
continue; continue;
} }
@ -83,79 +84,92 @@ void FlatBufferClient::disconnected()
emit clientDisconnected(); emit clientDisconnected();
} }
void FlatBufferClient::handleMessage(const flatbuf::HyperionRequest * message) void FlatBufferClient::handleMessage(const hyperionnet::Request * req)
{ {
switch (message->command()) const void* reqPtr;
{ if ((reqPtr = req->command_as_Color()) != nullptr) {
case flatbuf::Command_COLOR: handleColorCommand(static_cast<const hyperionnet::Color*>(reqPtr));
qDebug()<<"handle colorReuest"; } else if ((reqPtr = req->command_as_Image()) != nullptr) {
if (!flatbuffers::IsFieldPresent(message, flatbuf::HyperionRequest::VT_COLORREQUEST)) handleImageCommand(static_cast<const hyperionnet::Image*>(reqPtr));
{ } else if ((reqPtr = req->command_as_Clear()) != nullptr) {
sendErrorReply("Received COLOR command without ColorRequest"); handleClearCommand(static_cast<const hyperionnet::Clear*>(reqPtr));
break; } else if ((reqPtr = req->command_as_Register()) != nullptr) {
} handleRegisterCommand(static_cast<const hyperionnet::Register*>(reqPtr));
//handleColorCommand(message->colorRequest()); } else {
break; sendErrorReply("Received invalid packet.");
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();
} }
} }
void FlatBufferClient::handleImageCommand(const flatbuf::ImageRequest *message) void FlatBufferClient::handleColorCommand(const hyperionnet::Color *colorReq)
{ {
// extract parameters // extract parameters
int priority = message->priority(); const int32_t rgbData = colorReq->data();
int duration = message->duration(); ColorRgb color;
int width = message->imagewidth(); color.red = qRed(rgbData);
int height = message->imageheight(); color.green = qGreen(rgbData);
const auto & imageData = message->imagedata(); color.blue = qBlue(rgbData);
// make sure the prio is registered before setInput() // set output
if(priority != _priority) _hyperion->setColor(_priority, color, colorReq->duration());
{
_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);
// send reply // send reply
sendSuccessReply(); 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() void FlatBufferClient::handleNotImplemented()
{ {
@ -175,7 +189,7 @@ void FlatBufferClient::sendMessage()
void FlatBufferClient::sendSuccessReply() void FlatBufferClient::sendSuccessReply()
{ {
auto reply = flatbuf::CreateHyperionReplyDirect(_builder, flatbuf::Type_REPLY, true); auto reply = hyperionnet::CreateReplyDirect(_builder);
_builder.Finish(reply); _builder.Finish(reply);
// send reply // send reply
@ -185,7 +199,7 @@ void FlatBufferClient::sendSuccessReply()
void FlatBufferClient::sendErrorReply(const std::string &error) void FlatBufferClient::sendErrorReply(const std::string &error)
{ {
// create reply // 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); _builder.Finish(reply);
// send reply // send reply

View File

@ -75,14 +75,31 @@ private:
/// ///
/// @brief Handle the received message /// @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 /// 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 /// Send handle not implemented
@ -108,12 +125,12 @@ private:
private: private:
Logger *_log; Logger *_log;
QTcpSocket *_socket; QTcpSocket *_socket;
const QString _clientAddress; const QString _clientAddress;
QTimer *_timeoutTimer; QTimer *_timeoutTimer;
int _timeout; int _timeout;
int _priority; int _priority;
Hyperion* _hyperion; Hyperion* _hyperion;
QByteArray _receiveBuffer; QByteArray _receiveBuffer;

View File

@ -7,10 +7,13 @@
// protoserver includes // protoserver includes
#include <flatbufserver/FlatBufferConnection.h> #include <flatbufserver/FlatBufferConnection.h>
FlatBufferConnection::FlatBufferConnection(const QString & address) FlatBufferConnection::FlatBufferConnection(const QString& origin, const QString & address, const int& priority, const bool& skipReply)
: _socket() : _socket()
, _origin(origin)
, _priority(priority)
, _prevSocketState(QAbstractSocket::UnconnectedState) , _prevSocketState(QAbstractSocket::UnconnectedState)
, _log(Logger::getInstance("FLATBUFCONNECTION")) , _log(Logger::getInstance("FLATBUFCONNECTION"))
, _registered(false)
{ {
QStringList parts = address.split(":"); QStringList parts = address.split(":");
if (parts.size() != 2) 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()); 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 // init connect
Info(_log, "Connecting to Hyperion: %s:%d", _host.toStdString().c_str(), _port); Info(_log, "Connecting to Hyperion: %s:%d", _host.toStdString().c_str(), _port);
connectToHost(); connectToHost();
@ -66,10 +72,9 @@ void FlatBufferConnection::readData()
const uint8_t* msgData = reinterpret_cast<const uint8_t*>(msg.constData()); const uint8_t* msgData = reinterpret_cast<const uint8_t*>(msg.constData());
flatbuffers::Verifier verifier(msgData, messageSize); flatbuffers::Verifier verifier(msgData, messageSize);
if (flatbuf::VerifyHyperionReplyBuffer(verifier)) if (hyperionnet::VerifyReplyBuffer(verifier))
{ {
auto message = flatbuf::GetHyperionReply(msgData); parseReply(hyperionnet::GetReply(msgData));
parseReply(message);
continue; continue;
} }
Error(_log, "Unable to parse reply"); 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); 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 registerReq = hyperionnet::CreateRegister(_builder, _builder.CreateString(QSTRING_CSTR(origin)), priority);
auto req = flatbuf::CreateHyperionRequest(_builder,flatbuf::Command_COLOR, colorReq); auto req = hyperionnet::CreateRequest(_builder, hyperionnet::Command_Register, registerReq.Union());
_builder.Finish(req); _builder.Finish(req);
sendMessage(_builder.GetBufferPointer(), _builder.GetSize()); 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 colorReq = hyperionnet::CreateColor(_builder, (color.red << 16) | (color.green << 8) | color.blue, duration);
auto imgReq = flatbuf::CreateImageRequest(_builder, priority, image.width(), image.height(), imgData, duration); auto req = hyperionnet::CreateRequest(_builder, hyperionnet::Command_Color, colorReq.Union());
auto req = flatbuf::CreateHyperionRequest(_builder,flatbuf::Command_IMAGE,0,imgReq);
_builder.Finish(req); _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) void FlatBufferConnection::clear(int priority)
{ {
auto clearReq = flatbuf::CreateClearRequest(_builder, priority); auto clearReq = hyperionnet::CreateClear(_builder, priority);
auto req = flatbuf::CreateHyperionRequest(_builder,flatbuf::Command_CLEAR,0,0,clearReq); auto req = hyperionnet::CreateRequest(_builder,hyperionnet::Command_Clear, clearReq.Union());
_builder.Finish(req); _builder.Finish(req);
sendMessage(_builder.GetBufferPointer(), _builder.GetSize()); sendMessage(_builder.GetBufferPointer(), _builder.GetSize());
@ -113,11 +129,7 @@ void FlatBufferConnection::clear(int priority)
void FlatBufferConnection::clearAll() void FlatBufferConnection::clearAll()
{ {
auto req = flatbuf::CreateHyperionRequest(_builder,flatbuf::Command_CLEARALL); clear(-1);
// send command message
_builder.Finish(req);
sendMessage(_builder.GetBufferPointer(), _builder.GetSize());
} }
void FlatBufferConnection::connectToHost() 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 // print out connection message only when state is changed
if (_socket.state() != _prevSocketState ) if (_socket.state() != _prevSocketState )
{ {
switch (_socket.state() ) switch (_socket.state() )
{ {
case QAbstractSocket::UnconnectedState: case QAbstractSocket::UnconnectedState:
Info(_log, "No connection to Hyperion: %s:%d", _host.toStdString().c_str(), _port); Info(_log, "No connection to Hyperion: %s:%d", _host.toStdString().c_str(), _port);
break; break;
case QAbstractSocket::ConnectedState:
case QAbstractSocket::ConnectedState: Info(_log, "Connected to Hyperion: %s:%d", _host.toStdString().c_str(), _port);
Info(_log, "Connected to Hyperion: %s:%d", _host.toStdString().c_str(), _port); _registered = false;
break; break;
default:
default: Debug(_log, "Connecting to Hyperion: %s:%d", _host.toStdString().c_str(), _port);
Debug(_log, "Connecting to Hyperion: %s:%d", _host.toStdString().c_str(), _port); break;
break;
} }
_prevSocketState = _socket.state(); _prevSocketState = _socket.state();
} }
if (_socket.state() != QAbstractSocket::ConnectedState) if (_socket.state() != QAbstractSocket::ConnectedState)
return;
if(!_registered)
{ {
_registered = true;
setRegister(_origin, _priority);
return; return;
} }
@ -168,46 +184,22 @@ void FlatBufferConnection::sendMessage(const uint8_t* buffer, uint32_t size)
int count = 0; int count = 0;
count += _socket.write(reinterpret_cast<const char *>(header), 4); count += _socket.write(reinterpret_cast<const char *>(header), 4);
count += _socket.write(reinterpret_cast<const char *>(buffer), size); count += _socket.write(reinterpret_cast<const char *>(buffer), size);
if (!_socket.waitForBytesWritten()) _socket.flush();
{ _builder.Clear();
Error(_log, "Error while writing data to host");
return;
}
} }
bool FlatBufferConnection::parseReply(const flatbuf::HyperionReply *reply) bool FlatBufferConnection::parseReply(const hyperionnet::Reply *reply)
{ {
bool success = false; if (!reply->error())
switch (reply->type())
{ {
case flatbuf::Type_REPLY: // no error set must be a success or video
{ const auto videoMode = reply->video();
if (!reply->success()) if (videoMode != -1) {
{ // We got a video reply.
if (flatbuffers::IsFieldPresent(reply, flatbuf::HyperionReply::VT_ERROR)) emit setVideoMode(static_cast<VideoMode>(videoMode));
{
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;
} }
return true;
} }
return success; return false;
} }

View File

@ -58,6 +58,7 @@ void FlatBufferServer::newConnection()
{ {
if(QTcpSocket* socket = _server->nextPendingConnection()) if(QTcpSocket* socket = _server->nextPendingConnection())
{ {
Debug(_log, "New connection from %s", QSTRING_CSTR(socket->peerAddress().toString())); Debug(_log, "New connection from %s", QSTRING_CSTR(socket->peerAddress().toString()));
FlatBufferClient *client = new FlatBufferClient(socket, _timeout, this); FlatBufferClient *client = new FlatBufferClient(socket, _timeout, this);
// internal // internal

View File

@ -1,15 +1,8 @@
namespace flatbuf; namespace hyperionnet;
enum Type : int { table Reply {
REPLY = 0,
VIDEO = 1,
}
table HyperionReply {
type:Type;
success:bool;
error:string; error:string;
video:int; video:int = -1;
} }
root_type HyperionReply; root_type Reply;

View File

@ -1,35 +1,37 @@
namespace flatbuf; namespace hyperionnet;
enum Command : int { // A priority value of -1 clears all priorities
COLOR = 0, table Register {
IMAGE = 1, origin:string (required);
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 {
priority:int; 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;

View File

@ -23,8 +23,6 @@ LinearColorSmoothing::LinearColorSmoothing( LedDevice * ledDevice, const QJsonDo
, _pause(false) , _pause(false)
, _currentConfigId(0) , _currentConfigId(0)
{ {
Debug(_log, "Instance created");
// set initial state to true, as LedDevice::enabled() is true by default // set initial state to true, as LedDevice::enabled() is true by default
_hyperion->getComponentRegister().componentStateChanged(hyperion::COMP_SMOOTHING, true); _hyperion->getComponentRegister().componentStateChanged(hyperion::COMP_SMOOTHING, true);

View File

@ -98,7 +98,7 @@ void MessageForwarder::addProtoSlave(QString slave)
} }
// verify loop with protoserver // 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()) if(QHostAddress(parts[0]) == QHostAddress::LocalHost && parts[1].toInt() == obj["port"].toInt())
{ {
Error(_log, "Loop between ProtoServer and Forwarder! (%s)",QSTRING_CSTR(slave)); Error(_log, "Loop between ProtoServer and Forwarder! (%s)",QSTRING_CSTR(slave));

View File

@ -20,11 +20,11 @@ SettingsManager::SettingsManager(Hyperion* hyperion, const quint8& instance, con
: _hyperion(hyperion) : _hyperion(hyperion)
, _log(Logger::getInstance("SettingsManager")) , _log(Logger::getInstance("SettingsManager"))
{ {
Q_INIT_RESOURCE(resource);
connect(this, &SettingsManager::settingsChanged, _hyperion, &Hyperion::settingsChanged); connect(this, &SettingsManager::settingsChanged, _hyperion, &Hyperion::settingsChanged);
// get schema // get schema
if(schemaJson.isEmpty()) if(schemaJson.isEmpty())
{ {
Q_INIT_RESOURCE(resource);
try try
{ {
schemaJson = QJsonFactory::readSchema(":/hyperion-schema"); schemaJson = QJsonFactory::readSchema(":/hyperion-schema");

View File

@ -51,10 +51,6 @@
{ {
"$ref": "schema-jsonServer.json" "$ref": "schema-jsonServer.json"
}, },
"protoServer" :
{
"$ref": "schema-protoServer.json"
},
"flatbufServer": "flatbufServer":
{ {
"$ref": "schema-flatbufServer.json" "$ref": "schema-flatbufServer.json"

View File

@ -15,7 +15,6 @@
<file alias="schema-backgroundEffect.json">schema/schema-backgroundEffect.json</file> <file alias="schema-backgroundEffect.json">schema/schema-backgroundEffect.json</file>
<file alias="schema-forwarder.json">schema/schema-forwarder.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-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-flatbufServer.json">schema/schema-flatbufServer.json</file>
<file alias="schema-boblightServer.json">schema/schema-boblightServer.json</file> <file alias="schema-boblightServer.json">schema/schema-boblightServer.json</file>
<file alias="schema-udpListener.json">schema/schema-udpListener.json</file> <file alias="schema-udpListener.json">schema/schema-udpListener.json</file>

View File

@ -77,6 +77,7 @@ ENDFOREACH()
add_library(leddevice ${CMAKE_BINARY_DIR}/LedDevice_headers.h ${Leddevice_SOURCES} ) add_library(leddevice ${CMAKE_BINARY_DIR}/LedDevice_headers.h ${Leddevice_SOURCES} )
target_link_libraries(leddevice target_link_libraries(leddevice
hyperion
hyperion-utils hyperion-utils
${CMAKE_THREAD_LIBS_INIT} ${CMAKE_THREAD_LIBS_INIT}
Qt5::Network Qt5::Network

View 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
)

View 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>";

View 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
View 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
View 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);
}

View File

@ -22,8 +22,6 @@ UDPListener::UDPListener(const QJsonDocument& config) :
_isActive(false), _isActive(false),
_listenPort(0) _listenPort(0)
{ {
Debug(_log, "Instance created");
// init // init
handleSettingsUpdate(settings::UDPLISTENER, config); handleSettingsUpdate(settings::UDPLISTENER, config);
} }

View File

@ -49,7 +49,7 @@ public:
quint16 getServerPort (void) const; quint16 getServerPort (void) const;
QString getErrorString (void) const; QString getErrorString (void) const;
// const bool isListening(void) { return m_sockServer->isListening(); }; const bool isListening(void) { return m_sockServer->isListening(); };
public slots: public slots:
void start (quint16 port = 0); void start (quint16 port = 0);

View File

@ -32,6 +32,14 @@ void StaticFileServing::setBaseUrl(const QString& url)
_cgi.setBaseUrl(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) void StaticFileServing::printErrorToReply (QtHttpReply * reply, QtHttpReply::StatusCode code, QString errorMessage)
{ {
reply->setStatusCode(code); reply->setStatusCode(code);
@ -76,24 +84,33 @@ void StaticFileServing::onRequestNeedsReply (QtHttpRequest * request, QtHttpRepl
QStringList uri_parts = path.split('/', QString::SkipEmptyParts); QStringList uri_parts = path.split('/', QString::SkipEmptyParts);
// special uri handling for server commands // special uri handling for server commands
if ( ! uri_parts.empty() && uri_parts.at(0) == "cgi" ) if ( ! uri_parts.empty() )
{ {
uri_parts.removeAt(0); if(uri_parts.at(0) == "cgi")
try
{ {
_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); reply->addHeader ("Content-Type", "text/xml");
printErrorToReply (reply, QtHttpReply::InternalError, "script failed (" % path % ")"); 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); QFileInfo info(_baseUrl % "/" % path);

View File

@ -1,16 +1,14 @@
#ifndef STATICFILESERVING_H #ifndef STATICFILESERVING_H
#define STATICFILESERVING_H #define STATICFILESERVING_H
// locales includes
#include "CgiHandler.h"
// qt includes
#include <QMimeDatabase> #include <QMimeDatabase>
//#include "QtHttpServer.h"
#include "QtHttpRequest.h" #include "QtHttpRequest.h"
#include "QtHttpReply.h" #include "QtHttpReply.h"
#include "QtHttpHeader.h" #include "QtHttpHeader.h"
#include "CgiHandler.h"
//utils includes
#include <utils/Logger.h> #include <utils/Logger.h>
class StaticFileServing : public QObject { class StaticFileServing : public QObject {
@ -20,7 +18,15 @@ public:
explicit StaticFileServing (QObject * parent = nullptr); explicit StaticFileServing (QObject * parent = nullptr);
virtual ~StaticFileServing (void); virtual ~StaticFileServing (void);
///
/// @brief Overwrite current base url
///
void setBaseUrl(const QString& 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: public slots:
void onRequestNeedsReply (QtHttpRequest * request, QtHttpReply * reply); void onRequestNeedsReply (QtHttpRequest * request, QtHttpReply * reply);
@ -30,6 +36,7 @@ private:
QMimeDatabase * _mimeDb; QMimeDatabase * _mimeDb;
CgiHandler _cgi; CgiHandler _cgi;
Logger * _log; Logger * _log;
QByteArray _ssdpDescription;
void printErrorToReply (QtHttpReply * reply, QtHttpReply::StatusCode code, QString errorMessage); void printErrorToReply (QtHttpReply * reply, QtHttpReply::StatusCode code, QString errorMessage);

View File

@ -1,23 +1,34 @@
#include "webserver/WebServer.h" #include "webserver/WebServer.h"
#include "StaticFileServing.h" #include "StaticFileServing.h"
// qt includes
#include "QtHttpServer.h" #include "QtHttpServer.h"
#include <QFileInfo> #include <QFileInfo>
#include <QJsonObject> #include <QJsonObject>
// bonjour includes // bonjour
#include <bonjour/bonjourserviceregister.h> #include <bonjour/bonjourserviceregister.h>
#include <bonjour/bonjourrecord.h>
// utils includes // netUtil
#include <utils/NetUtils.h> #include <utils/NetUtils.h>
WebServer::WebServer(const QJsonDocument& config, QObject * parent) WebServer::WebServer(const QJsonDocument& config, QObject * parent)
: QObject(parent) : QObject(parent)
, _config(config)
, _log(Logger::getInstance("WEBSERVER")) , _log(Logger::getInstance("WEBSERVER"))
, _server(new QtHttpServer (this)) , _server()
{ {
}
WebServer::~WebServer()
{
stop();
}
void WebServer::initServer()
{
_server = new QtHttpServer (this);
_server->setServerName (QStringLiteral ("Hyperion Webserver")); _server->setServerName (QStringLiteral ("Hyperion Webserver"));
connect (_server, &QtHttpServer::started, this, &WebServer::onServerStarted); connect (_server, &QtHttpServer::started, this, &WebServer::onServerStarted);
@ -28,18 +39,14 @@ WebServer::WebServer(const QJsonDocument& config, QObject * parent)
_staticFileServing = new StaticFileServing (this); _staticFileServing = new StaticFileServing (this);
connect(_server, &QtHttpServer::requestNeedsReply, _staticFileServing, &StaticFileServing::onRequestNeedsReply); connect(_server, &QtHttpServer::requestNeedsReply, _staticFileServing, &StaticFileServing::onRequestNeedsReply);
Debug(_log, "Instance created");
// init // init
handleSettingsUpdate(settings::WEBSERVER, config); handleSettingsUpdate(settings::WEBSERVER, _config);
}
WebServer::~WebServer()
{
stop();
} }
void WebServer::onServerStarted (quint16 port) void WebServer::onServerStarted (quint16 port)
{ {
_inited= true;
Info(_log, "Started on port %d name '%s'", port ,_server->getServerName().toStdString().c_str()); Info(_log, "Started on port %d name '%s'", port ,_server->getServerName().toStdString().c_str());
if(_serviceRegister == nullptr) if(_serviceRegister == nullptr)
@ -53,10 +60,12 @@ void WebServer::onServerStarted (quint16 port)
_serviceRegister = new BonjourServiceRegister(this); _serviceRegister = new BonjourServiceRegister(this);
_serviceRegister->registerService("_hyperiond-http._tcp", port); _serviceRegister->registerService("_hyperiond-http._tcp", port);
} }
emit stateChange(true);
} }
void WebServer::onServerStopped () { void WebServer::onServerStopped () {
Info(_log, "Stopped %s", _server->getServerName().toStdString().c_str()); Info(_log, "Stopped %s", _server->getServerName().toStdString().c_str());
emit stateChange(false);
} }
void WebServer::onServerError (QString msg) 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); _baseUrl = obj["document_root"].toString(WEBSERVER_DEFAULT_PATH);
if ( (_baseUrl != ":/webconfig") && !_baseUrl.trimmed().isEmpty()) if ( (_baseUrl != ":/webconfig") && !_baseUrl.trimmed().isEmpty())
{ {
QFileInfo info(_baseUrl); 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 // eval if the port is available, will be incremented if not
NetUtils::portAvailable(_port, _log); if(!_server->isListening())
NetUtils::portAvailable(_port, _log);
start(); start();
emit portChanged(_port);
} }
} }
@ -108,3 +121,8 @@ void WebServer::stop()
{ {
_server->stop(); _server->stop();
} }
void WebServer::setSSDPDescription(const QString & desc)
{
_staticFileServing->setSSDPDescription(desc);
}

View File

@ -4,8 +4,8 @@ project(hyperion-aml)
find_package(Qt5Widgets REQUIRED) find_package(Qt5Widgets REQUIRED)
include_directories( include_directories(
${CMAKE_CURRENT_BINARY_DIR}/../../libsrc/protoserver ${CMAKE_CURRENT_BINARY_DIR}/../../libsrc/flatbufserver
${PROTOBUF_INCLUDE_DIRS} ${FLATBUFFERS_INCLUDE_DIRS}
) )
set(Hyperion_AML_HEADERS set(Hyperion_AML_HEADERS
@ -27,9 +27,11 @@ target_link_libraries(${PROJECT_NAME}
commandline commandline
blackborder blackborder
hyperion-utils hyperion-utils
protoclient flatbufserver
flatbuffers
amlogic-grabber amlogic-grabber
framebuffer-grabber framebuffer-grabber
ssdp
Qt5::Core Qt5::Core
Qt5::Gui Qt5::Gui
Qt5::Network Qt5::Network

View File

@ -4,12 +4,15 @@
#include <QCoreApplication> #include <QCoreApplication>
#include <QImage> #include <QImage>
#include <protoserver/ProtoConnectionWrapper.h> #include <flatbufserver/FlatBufferConnection.h>
#include "AmlogicWrapper.h" #include "AmlogicWrapper.h"
#include "HyperionConfig.h" #include "HyperionConfig.h"
#include <commandline/Parser.h> #include <commandline/Parser.h>
// ssdp discover
#include <ssdp/SSDPDiscover.h>
using namespace commandline; using namespace commandline;
// save the image as screenshot // save the image as screenshot
@ -32,7 +35,7 @@ int main(int argc, char ** argv)
try try
{ {
// create the option parser and initialize all parser // create the option parser and initialize all parser
Parser parser("AmLogic capture application for Hyperion"); Parser parser("AmLogic capture application for Hyperion. Will automatically search a Hyperion server if -a option isn't used. Please note that if you have more than one server running it's more or less random which one will be used.");
IntOption & argFps = parser.add<IntOption> ('f', "framerate", "Capture frame rate [default: %1]", "10"); IntOption & argFps = parser.add<IntOption> ('f', "framerate", "Capture frame rate [default: %1]", "10");
IntOption & argWidth = parser.add<IntOption> (0x0, "width", "Width of the captured image [default: %1]", "160", 160, 4096); IntOption & argWidth = parser.add<IntOption> (0x0, "width", "Width of the captured image [default: %1]", "160", 160, 4096);
@ -62,11 +65,26 @@ int main(int argc, char ** argv)
} }
else else
{ {
// Create the Proto-connection with hyperiond // server searching by ssdp
ProtoConnectionWrapper protoWrapper(argAddress.value(parser), argPriority.getInt(parser), 1000, parser.isSet(argSkipReply)); QString address;
if(parser.isSet(argAddress))
{
address = argAddress.value(parser);
}
else
{
SSDPDiscover discover;
address = discover.getFirstService(STY_FLATBUFSERVER);
if(address.isEmpty())
{
address = argAddress.value(parser);
}
}
// Create the Flabuf-connection
FlatBufferConnection flatbuf("AML Standalone", address, argPriority.getInt(parser), parser.isSet(argSkipReply));
// Connect the screen capturing to the proto processing // Connect the screen capturing to flatbuf connection processing
QObject::connect(&amlWrapper, SIGNAL(sig_screenshot(const Image<ColorRgb> &)), &protoWrapper, SLOT(receiveImage(Image<ColorRgb>))); QObject::connect(&amlWrapper, SIGNAL(sig_screenshot(const Image<ColorRgb> &)), &flatbuf, SLOT(setImage(Image<ColorRgb>)));
// Start the capturing // Start the capturing
amlWrapper.start(); amlWrapper.start();

View File

@ -10,9 +10,9 @@ ELSE()
ENDIF() ENDIF()
include_directories( include_directories(
${CMAKE_CURRENT_BINARY_DIR}/../../libsrc/protoserver ${CMAKE_CURRENT_BINARY_DIR}/../../libsrc/flatbufserver
${BCM_INCLUDE_DIRS} ${BCM_INCLUDE_DIRS}
${PROTOBUF_INCLUDE_DIRS} ${FLATBUFFERS_INCLUDE_DIRS}
) )
set(Hyperion_Dispmanx_HEADERS set(Hyperion_Dispmanx_HEADERS
@ -34,9 +34,11 @@ target_link_libraries( ${PROJECT_NAME}
commandline commandline
blackborder blackborder
hyperion-utils hyperion-utils
protoclient flatbufserver
flatbuffers
dispmanx-grabber dispmanx-grabber
${Dispmanx_LIBRARIES} ${Dispmanx_LIBRARIES}
ssdp
Qt5::Core Qt5::Core
Qt5::Gui Qt5::Gui
Qt5::Network Qt5::Network

View File

@ -3,12 +3,15 @@
#include <QCoreApplication> #include <QCoreApplication>
#include <QImage> #include <QImage>
#include <protoserver/ProtoConnectionWrapper.h> #include <flatbufserver/FlatBufferConnection.h>
#include "DispmanxWrapper.h" #include "DispmanxWrapper.h"
#include "HyperionConfig.h" #include "HyperionConfig.h"
#include <commandline/Parser.h> #include <commandline/Parser.h>
// ssdp discover
#include <ssdp/SSDPDiscover.h>
using namespace commandline; using namespace commandline;
// save the image as screenshot // save the image as screenshot
@ -31,7 +34,7 @@ int main(int argc, char ** argv)
try try
{ {
// create the option parser and initialize all parameters // create the option parser and initialize all parameters
Parser parser("Dispmanx capture application for Hyperion"); Parser parser("Dispmanx capture application for Hyperion. Will automatically search a Hyperion server if -a option isn't used. Please note that if you have more than one server running it's more or less random which one will be used.");
IntOption & argFps = parser.add<IntOption> ('f', "framerate", "Capture frame rate [default: %1]", "10"); IntOption & argFps = parser.add<IntOption> ('f', "framerate", "Capture frame rate [default: %1]", "10");
IntOption & argWidth = parser.add<IntOption> (0x0, "width", "Width of the captured image [default: %1]", "64", 32, 4096); IntOption & argWidth = parser.add<IntOption> (0x0, "width", "Width of the captured image [default: %1]", "64", 32, 4096);
@ -90,11 +93,26 @@ int main(int argc, char ** argv)
} }
else else
{ {
// Create the Proto-connection with hyperiond // server searching by ssdp
ProtoConnectionWrapper protoWrapper(argAddress.value(parser), argPriority.getInt(parser), 1000, parser.isSet(argSkipReply)); QString address;
if(parser.isSet(argAddress))
{
address = argAddress.value(parser);
}
else
{
SSDPDiscover discover;
address = discover.getFirstService(STY_FLATBUFSERVER);
if(address.isEmpty())
{
address = argAddress.value(parser);
}
}
// Create the Flabuf-connection
FlatBufferConnection flatbuf("Dispmanx Standalone", address, argPriority.getInt(parser), parser.isSet(argSkipReply));
// Connect the screen capturing to the proto processing // Connect the screen capturing to flatbuf connection processing
QObject::connect(&dispmanxWrapper, SIGNAL(sig_screenshot(const Image<ColorRgb> &)), &protoWrapper, SLOT(receiveImage(Image<ColorRgb>))); QObject::connect(&dispmanxWrapper, SIGNAL(sig_screenshot(const Image<ColorRgb> &)), &flatbuf, SLOT(setImage(Image<ColorRgb>)));
// Start the capturing // Start the capturing
dispmanxWrapper.start(); dispmanxWrapper.start();

View File

@ -4,8 +4,8 @@ project(hyperion-framebuffer)
find_package(Qt5Widgets REQUIRED) find_package(Qt5Widgets REQUIRED)
include_directories( include_directories(
${CMAKE_CURRENT_BINARY_DIR}/../../libsrc/protoserver ${CMAKE_CURRENT_BINARY_DIR}/../../libsrc/flatbufserver
${PROTOBUF_INCLUDE_DIRS} ${FLATBUFFERS_INCLUDE_DIRS}
) )
set(Hyperion_FB_HEADERS set(Hyperion_FB_HEADERS
@ -27,8 +27,10 @@ target_link_libraries( ${PROJECT_NAME}
commandline commandline
blackborder blackborder
hyperion-utils hyperion-utils
protoclient flatbufserver
flatbuffers
framebuffer-grabber framebuffer-grabber
ssdp
Qt5::Core Qt5::Core
Qt5::Gui Qt5::Gui
Qt5::Network Qt5::Network

View File

@ -4,10 +4,13 @@
#include <QCoreApplication> #include <QCoreApplication>
#include <QImage> #include <QImage>
#include <protoserver/ProtoConnectionWrapper.h> #include <flatbufserver/FlatBufferConnection.h>
#include "FramebufferWrapper.h" #include "FramebufferWrapper.h"
#include <commandline/Parser.h> #include <commandline/Parser.h>
// ssdp discover
#include <ssdp/SSDPDiscover.h>
using namespace commandline; using namespace commandline;
// save the image as screenshot // save the image as screenshot
@ -25,7 +28,7 @@ int main(int argc, char ** argv)
try try
{ {
// create the option parser and initialize all parameters // create the option parser and initialize all parameters
Parser parser("FrameBuffer capture application for Hyperion"); Parser parser("FrameBuffer capture application for Hyperion. Will automatically search a Hyperion server if -a option isn't used. Please note that if you have more than one server running it's more or less random which one will be used.");
Option & argDevice = parser.add<Option> ('d', "device", "Set the video device [default: %1]", "/dev/video0"); Option & argDevice = parser.add<Option> ('d', "device", "Set the video device [default: %1]", "/dev/video0");
IntOption & argFps = parser.add<IntOption> ('f', "framerate", "Capture frame rate [default: %1]", "10"); IntOption & argFps = parser.add<IntOption> ('f', "framerate", "Capture frame rate [default: %1]", "10");
@ -56,11 +59,26 @@ int main(int argc, char ** argv)
} }
else else
{ {
// Create the Proto-connection with hyperiond // server searching by ssdp
ProtoConnectionWrapper protoWrapper(argAddress.value(parser), argPriority.getInt(parser), 1000, parser.isSet(argSkipReply)); QString address;
if(parser.isSet(argAddress))
{
address = argAddress.value(parser);
}
else
{
SSDPDiscover discover;
address = discover.getFirstService(STY_FLATBUFSERVER);
if(address.isEmpty())
{
address = argAddress.value(parser);
}
}
// Create the Flabuf-connection
FlatBufferConnection flatbuf("Framebuffer Standalone", address, argPriority.getInt(parser), parser.isSet(argSkipReply));
// Connect the screen capturing to the proto processing // Connect the screen capturing to flatbuf connection processing
QObject::connect(&fbWrapper, SIGNAL(sig_screenshot(const Image<ColorRgb> &)), &protoWrapper, SLOT(receiveImage(Image<ColorRgb>))); QObject::connect(&fbWrapper, SIGNAL(sig_screenshot(const Image<ColorRgb> &)), &flatbuf, SLOT(setImage(Image<ColorRgb>)));
// Start the capturing // Start the capturing
fbWrapper.start(); fbWrapper.start();

View File

@ -4,8 +4,8 @@ project(hyperion-osx)
find_package(Qt5Widgets REQUIRED) find_package(Qt5Widgets REQUIRED)
include_directories( include_directories(
${CMAKE_CURRENT_BINARY_DIR}/../../libsrc/protoserver ${CMAKE_CURRENT_BINARY_DIR}/../../libsrc/flatbufserver
${PROTOBUF_INCLUDE_DIRS} ${FLATBUFFERS_INCLUDE_DIRS}
) )
set(Hyperion_OSX_HEADERS set(Hyperion_OSX_HEADERS
@ -27,8 +27,10 @@ target_link_libraries( ${PROJECT_NAME}
commandline commandline
blackborder blackborder
hyperion-utils hyperion-utils
protoclient flatbufserver
flatbuffers
osx-grabber osx-grabber
ssdp
Qt5::Core Qt5::Core
Qt5::Gui Qt5::Gui
Qt5::Network Qt5::Network

View File

@ -4,10 +4,13 @@
#include <QCoreApplication> #include <QCoreApplication>
#include <QImage> #include <QImage>
#include <protoserver/ProtoConnectionWrapper.h> #include <flatbufserver/FlatBufferConnection.h>
#include "OsxWrapper.h" #include "OsxWrapper.h"
#include <commandline/Parser.h> #include <commandline/Parser.h>
// ssdp discover
#include <ssdp/SSDPDiscover.h>
using namespace commandline; using namespace commandline;
// save the image as screenshot // save the image as screenshot
@ -25,7 +28,7 @@ int main(int argc, char ** argv)
try try
{ {
// create the option parser and initialize all parameters // create the option parser and initialize all parameters
Parser parser("OSX capture application for Hyperion"); Parser parser("OSX capture application for Hyperion. Will automatically search a Hyperion server if -a option isn't used. Please note that if you have more than one server running it's more or less random which one will be used.");
Option & argDisplay = parser.add<Option> ('d', "display", "Set the display to capture [default: %1]"); Option & argDisplay = parser.add<Option> ('d', "display", "Set the display to capture [default: %1]");
IntOption & argFps = parser.add<IntOption> ('f', "framerate", "Capture frame rate [default: %1]", "10", 1, 600); IntOption & argFps = parser.add<IntOption> ('f', "framerate", "Capture frame rate [default: %1]", "10", 1, 600);
@ -46,37 +49,50 @@ int main(int argc, char ** argv)
parser.showHelp(0); parser.showHelp(0);
} }
OsxWrapper osxWrapper OsxWrapper osxWrapper
(parser.isSet(argDisplay), argWidth.getInt(parser), argHeight.getInt(parser), 1000 / argFps.getInt(parser)); (parser.isSet(argDisplay), argWidth.getInt(parser), argHeight.getInt(parser), 1000 / argFps.getInt(parser));
if (parser.isSet(argScreenshot)) { if (parser.isSet(argScreenshot))
// Capture a single screenshot and finish {
const Image<ColorRgb> &screenshot = osxWrapper.getScreenshot(); // Capture a single screenshot and finish
saveScreenshot("screenshot.png", screenshot); const Image<ColorRgb> &screenshot = osxWrapper.getScreenshot();
} saveScreenshot("screenshot.png", screenshot);
else { }
// Create the Proto-connection with hyperiond else
ProtoConnectionWrapper protoWrapper {
(argAddress.value(parser), argPriority.getInt(parser), 1000, parser.isSet(argSkipReply)); // server searching by ssdp
QString address;
if(parser.isSet(argAddress))
{
address = argAddress.value(parser);
}
else
{
SSDPDiscover discover;
address = discover.getFirstService(STY_FLATBUFSERVER);
if(address.isEmpty())
{
address = argAddress.value(parser);
}
}
// Connect the screen capturing to the proto processing // Create the Flabuf-connection
QObject::connect(&osxWrapper, FlatBufferConnection flatbuf("OSX Standalone", address, argPriority.getInt(parser), parser.isSet(argSkipReply));
SIGNAL(sig_screenshot(
const Image<ColorRgb> &)),
&protoWrapper,
SLOT(receiveImage(Image<ColorRgb>)));
// Start the capturing // Connect the screen capturing to flatbuf connection processing
osxWrapper.start(); QObject::connect(&osxWrapper, SIGNAL(sig_screenshot(const Image<ColorRgb> &)), &flatbuf, SLOT(setImage(Image<ColorRgb>)));
// Start the application // Start the capturing
app.exec(); osxWrapper.start();
// Start the application
app.exec();
} }
} }
catch (const std::runtime_error & e) catch (const std::runtime_error & e)
{ {
// An error occured. Display error and quit // An error occured. Display error and quit
Error(Logger::getInstance("OSXGRABBER"), "%s", e.what()); Error(Logger::getInstance("OSXGRABBER"), "%s", e.what());
return -1; return -1;
} }
return 0; return 0;

View File

@ -4,8 +4,8 @@ project(hyperion-v4l2)
find_package(Qt5Widgets REQUIRED) find_package(Qt5Widgets REQUIRED)
include_directories( include_directories(
${CMAKE_CURRENT_BINARY_DIR}/../../libsrc/protoserver ${CMAKE_CURRENT_BINARY_DIR}/../../libsrc/flatbufserver
${PROTOBUF_INCLUDE_DIRS} ${FLATBUFFERS_INCLUDE_DIRS}
) )
set(Hyperion_V4L2_HEADERS set(Hyperion_V4L2_HEADERS
@ -28,7 +28,9 @@ target_link_libraries(${PROJECT_NAME}
commandline commandline
blackborder blackborder
hyperion-utils hyperion-utils
protoclient flatbufserver
flatbuffers
ssdp
Qt5::Core Qt5::Core
Qt5::Gui Qt5::Gui
Qt5::Network Qt5::Network

View File

@ -12,9 +12,8 @@
// grabber includes // grabber includes
#include "grabber/V4L2Grabber.h" #include "grabber/V4L2Grabber.h"
// proto includes // flatbuf includes
#include "protoserver/ProtoConnection.h" #include <flatbufserver/FlatBufferConnection.h>
#include "protoserver/ProtoConnectionWrapper.h"
// hyperion-v4l2 includes // hyperion-v4l2 includes
#include "ScreenshotHandler.h" #include "ScreenshotHandler.h"
@ -22,6 +21,9 @@
#include "HyperionConfig.h" #include "HyperionConfig.h"
#include <commandline/Parser.h> #include <commandline/Parser.h>
// ssdp discover
#include <ssdp/SSDPDiscover.h>
using namespace commandline; using namespace commandline;
// save the image as screenshot // save the image as screenshot
@ -54,7 +56,7 @@ int main(int argc, char** argv)
try try
{ {
// create the option parser and initialize all parameters // create the option parser and initialize all parameters
Parser parser("V4L capture application for Hyperion"); Parser parser("V4L capture application for Hyperion. Will automatically search a Hyperion server if -a option isn't used. Please note that if you have more than one server running it's more or less random which one will be used.");
Option & argDevice = parser.add<Option> ('d', "device", "The device to use, can be /dev/video0 [default: %1 (auto detected)]", "auto"); Option & argDevice = parser.add<Option> ('d', "device", "The device to use, can be /dev/video0 [default: %1 (auto detected)]", "auto");
SwitchOption<VideoStandard> & argVideoStandard= parser.add<SwitchOption<VideoStandard>>('v', "video-standard", "The used video standard. Valid values are PAL, NTSC, SECAM or no-change. [default: %1]", "no-change"); SwitchOption<VideoStandard> & argVideoStandard= parser.add<SwitchOption<VideoStandard>>('v', "video-standard", "The used video standard. Valid values are PAL, NTSC, SECAM or no-change. [default: %1]", "no-change");
@ -188,8 +190,28 @@ int main(int argc, char** argv)
} }
else else
{ {
ProtoConnectionWrapper protoWrapper(argAddress.value(parser), argPriority.getInt(parser), 1000, parser.isSet(argSkipReply)); // server searching by ssdp
QObject::connect(&grabber, SIGNAL(newFrame(Image<ColorRgb>)), &protoWrapper, SLOT(receiveImage(Image<ColorRgb>))); QString address;
if(parser.isSet(argAddress))
{
address = argAddress.value(parser);
}
else
{
SSDPDiscover discover;
address = discover.getFirstService(STY_FLATBUFSERVER);
if(address.isEmpty())
{
address = argAddress.value(parser);
}
}
// Create the Flatbuf-connection
FlatBufferConnection flatbuf("V4L2 Standalone", address, argPriority.getInt(parser), parser.isSet(argSkipReply));
// Connect the screen capturing to flatbuf connection processing
QObject::connect(&grabber, SIGNAL(newFrame(const Image<ColorRgb> &)), &flatbuf, SLOT(setImage(Image<ColorRgb>)));
if (grabber.start()) if (grabber.start())
QCoreApplication::exec(); QCoreApplication::exec();
grabber.stop(); grabber.stop();

View File

@ -5,9 +5,9 @@ find_package(Qt5Widgets REQUIRED)
find_package(X11 REQUIRED) find_package(X11 REQUIRED)
include_directories( include_directories(
${CMAKE_CURRENT_BINARY_DIR}/../../libsrc/protoserver ${CMAKE_CURRENT_BINARY_DIR}/../../libsrc/flatbufserver
${X11_INCLUDES} ${X11_INCLUDES}
${PROTOBUF_INCLUDE_DIRS} ${FLATBUFFERS_INCLUDE_DIRS}
) )
set(Hyperion_X11_HEADERS set(Hyperion_X11_HEADERS
@ -29,8 +29,10 @@ target_link_libraries(${PROJECT_NAME}
blackborder blackborder
commandline commandline
hyperion-utils hyperion-utils
protoclient flatbufserver
flatbuffers
x11-grabber x11-grabber
ssdp
${X11_LIBRARIES} ${X11_LIBRARIES}
${X11_Xrender_LIB} ${X11_Xrender_LIB}
Qt5::Core Qt5::Core

View File

@ -4,10 +4,13 @@
#include <QImage> #include <QImage>
#include <commandline/Parser.h> #include <commandline/Parser.h>
#include "protoserver/ProtoConnectionWrapper.h" #include <flatbufserver/FlatBufferConnection.h>
#include "X11Wrapper.h" #include "X11Wrapper.h"
#include "HyperionConfig.h" #include "HyperionConfig.h"
// ssdp discover
#include <ssdp/SSDPDiscover.h>
using namespace commandline; using namespace commandline;
// save the image as screenshot // save the image as screenshot
@ -30,7 +33,7 @@ int main(int argc, char ** argv)
try try
{ {
// create the option parser and initialize all parameters // create the option parser and initialize all parameters
Parser parser("X11 capture application for Hyperion"); Parser parser("X11 capture application for Hyperion. Will automatically search a Hyperion server if -a option isn't used. Please note that if you have more than one server running it's more or less random which one will be used.");
IntOption & argFps = parser.add<IntOption> ('f', "framerate", "Capture frame rate [default: %1]", "10"); IntOption & argFps = parser.add<IntOption> ('f', "framerate", "Capture frame rate [default: %1]", "10");
IntOption & argCropWidth = parser.add<IntOption> (0x0, "crop-width", "Number of pixels to crop from the left and right sides of the picture before decimation [default: %1]", "0"); IntOption & argCropWidth = parser.add<IntOption> (0x0, "crop-width", "Number of pixels to crop from the left and right sides of the picture before decimation [default: %1]", "0");
@ -62,7 +65,7 @@ int main(int argc, char ** argv)
parser.isSet(argCropRight) ? argCropRight.getInt(parser) : argCropWidth.getInt(parser), parser.isSet(argCropRight) ? argCropRight.getInt(parser) : argCropWidth.getInt(parser),
parser.isSet(argCropTop) ? argCropTop.getInt(parser) : argCropHeight.getInt(parser), parser.isSet(argCropTop) ? argCropTop.getInt(parser) : argCropHeight.getInt(parser),
parser.isSet(argCropBottom) ? argCropBottom.getInt(parser) : argCropHeight.getInt(parser), parser.isSet(argCropBottom) ? argCropBottom.getInt(parser) : argCropHeight.getInt(parser),
argSizeDecimation.getInt(parser)); // pixel decimation argSizeDecimation.getInt(parser)); // decimation
if (!x11Wrapper.displayInit()) if (!x11Wrapper.displayInit())
return -1; return -1;
@ -75,14 +78,26 @@ int main(int argc, char ** argv)
} }
else else
{ {
// Create the Proto-connection with hyperiond // server searching by ssdp
ProtoConnectionWrapper protoWrapper(argAddress.value(parser), argPriority.getInt(parser), 1000, parser.isSet(argSkipReply)); QString address;
if(parser.isSet(argAddress))
{
address = argAddress.value(parser);
}
else
{
SSDPDiscover discover;
address = discover.getFirstService(STY_FLATBUFSERVER);
if(address.isEmpty())
{
address = argAddress.value(parser);
}
}
// Create the Flatbuf-connection
FlatBufferConnection flatbuf("X11 Standalone", address, argPriority.getInt(parser), parser.isSet(argSkipReply));
// Connect the screen capturing to the proto processing // Connect the screen capturing to flatbuf connection processing
QObject::connect(&x11Wrapper, SIGNAL(sig_screenshot(const Image<ColorRgb> &)), &protoWrapper, SLOT(receiveImage(Image<ColorRgb>))); QObject::connect(&x11Wrapper, SIGNAL(sig_screenshot(const Image<ColorRgb> &)), &flatbuf, SLOT(setImage(Image<ColorRgb>)));
// Connect the vodeMode to the proto processing
QObject::connect(&protoWrapper, SIGNAL(setVideoMode(VideoMode)), &x11Wrapper, SLOT(setVideoMode(VideoMode)));
// Start the capturing // Start the capturing
x11Wrapper.start(); x11Wrapper.start();

View File

@ -16,10 +16,10 @@ target_link_libraries(hyperiond
effectengine effectengine
jsonserver jsonserver
udplistener udplistener
protoserver
flatbufserver flatbufserver
webserver webserver
bonjour bonjour
ssdp
python python
${PYTHON_LIBRARIES} ${PYTHON_LIBRARIES}
) )

View File

@ -21,7 +21,6 @@
#include <hyperion/Hyperion.h> #include <hyperion/Hyperion.h>
#include <jsonserver/JsonServer.h> #include <jsonserver/JsonServer.h>
#include <protoserver/ProtoServer.h>
#include <udplistener/UDPListener.h> #include <udplistener/UDPListener.h>
#include <webserver/WebServer.h> #include <webserver/WebServer.h>
#include <utils/Stats.h> #include <utils/Stats.h>
@ -34,6 +33,9 @@
// bonjour browser // bonjour browser
#include <bonjour/bonjourbrowserwrapper.h> #include <bonjour/bonjourbrowserwrapper.h>
// ssdp
#include <ssdp/SSDPHandler.h>
// settings // settings
#include <hyperion/SettingsManager.h> #include <hyperion/SettingsManager.h>
@ -49,7 +51,6 @@ HyperionDaemon::HyperionDaemon(QString configFile, const QString rootPath, QObje
, _pyInit(new PythonInit()) , _pyInit(new PythonInit())
, _webserver(nullptr) , _webserver(nullptr)
, _jsonServer(nullptr) , _jsonServer(nullptr)
, _protoServer(nullptr)
, _udpListener(nullptr) , _udpListener(nullptr)
, _v4l2Grabbers() , _v4l2Grabbers()
, _dispmanx(nullptr) , _dispmanx(nullptr)
@ -59,6 +60,7 @@ HyperionDaemon::HyperionDaemon(QString configFile, const QString rootPath, QObje
, _osxGrabber(nullptr) , _osxGrabber(nullptr)
, _hyperion(nullptr) , _hyperion(nullptr)
, _stats(nullptr) , _stats(nullptr)
, _ssdp(nullptr)
, _currVideoMode(VIDEO_2D) , _currVideoMode(VIDEO_2D)
{ {
HyperionDaemon::daemon = this; HyperionDaemon::daemon = this;
@ -67,6 +69,8 @@ HyperionDaemon::HyperionDaemon(QString configFile, const QString rootPath, QObje
qRegisterMetaType<Image<ColorRgb>>("Image<ColorRgb>"); qRegisterMetaType<Image<ColorRgb>>("Image<ColorRgb>");
qRegisterMetaType<hyperion::Components>("hyperion::Components"); qRegisterMetaType<hyperion::Components>("hyperion::Components");
qRegisterMetaType<settings::type>("settings::type"); qRegisterMetaType<settings::type>("settings::type");
qRegisterMetaType<VideoMode>("VideoMode");
qRegisterMetaType<QMap<quint8,QJsonObject>>("QMap<quint8,QJsonObject>");
// init settings // init settings
_settingsManager = new SettingsManager(0,configFile); _settingsManager = new SettingsManager(0,configFile);
@ -113,11 +117,6 @@ HyperionDaemon::~HyperionDaemon()
delete _pyInit; delete _pyInit;
} }
quint16 HyperionDaemon::getWebServerPort()
{
return _webserver->getPort();
}
void HyperionDaemon::setVideoMode(const VideoMode& mode) void HyperionDaemon::setVideoMode(const VideoMode& mode)
{ {
if(_currVideoMode != mode) if(_currVideoMode != mode)
@ -135,19 +134,22 @@ const QJsonDocument HyperionDaemon::getSetting(const settings::type &type)
void HyperionDaemon::freeObjects() void HyperionDaemon::freeObjects()
{ {
_hyperion->clearall(true); _hyperion->clearall(true);
// destroy network first as a client might want to access pointers // destroy network first as a client might want to access hyperion
delete _webserver;
delete _jsonServer; delete _jsonServer;
delete _protoServer;
_flatBufferServer->thread()->quit(); _flatBufferServer->thread()->quit();
_flatBufferServer->thread()->wait(1000); _flatBufferServer->thread()->wait(1000);
//ssdp before webserver
_ssdp->thread()->quit();
_ssdp->thread()->wait(1000);
_webserver->thread()->quit();
_webserver->thread()->wait(1000);
delete _udpListener; delete _udpListener;
delete _bonjourBrowserWrapper; delete _bonjourBrowserWrapper;
delete _amlGrabber; delete _amlGrabber;
delete _dispmanx; delete _dispmanx;
delete _fbGrabber; delete _fbGrabber;
delete _osxGrabber; delete _osxGrabber;
for(V4L2Wrapper* grabber : _v4l2Grabbers) for(V4L2Wrapper* grabber : _v4l2Grabbers)
{ {
delete grabber; delete grabber;
@ -162,7 +164,6 @@ void HyperionDaemon::freeObjects()
_osxGrabber = nullptr; _osxGrabber = nullptr;
_webserver = nullptr; _webserver = nullptr;
_jsonServer = nullptr; _jsonServer = nullptr;
_protoServer = nullptr;
_udpListener = nullptr; _udpListener = nullptr;
_stats = nullptr; _stats = nullptr;
} }
@ -176,28 +177,40 @@ void HyperionDaemon::startNetworkServices()
_jsonServer = new JsonServer(getSetting(settings::JSONSERVER)); _jsonServer = new JsonServer(getSetting(settings::JSONSERVER));
connect(this, &HyperionDaemon::settingsChanged, _jsonServer, &JsonServer::handleSettingsUpdate); connect(this, &HyperionDaemon::settingsChanged, _jsonServer, &JsonServer::handleSettingsUpdate);
// Create Proto server // Create FlatBuffer server in thread
_protoServer = new ProtoServer(getSetting(settings::PROTOSERVER));
connect(this, &HyperionDaemon::settingsChanged, _protoServer, &ProtoServer::handleSettingsUpdate);
// Create FlatBuffer server & move to Thread
_flatBufferServer = new FlatBufferServer(getSetting(settings::FLATBUFSERVER)); _flatBufferServer = new FlatBufferServer(getSetting(settings::FLATBUFSERVER));
connect(this, &HyperionDaemon::settingsChanged, _flatBufferServer, &FlatBufferServer::handleSettingsUpdate);
QThread* fbThread = new QThread(this); QThread* fbThread = new QThread(this);
_flatBufferServer->moveToThread(fbThread); _flatBufferServer->moveToThread(fbThread);
connect( fbThread, &QThread::started, _flatBufferServer, &FlatBufferServer::initServer ); connect( fbThread, &QThread::started, _flatBufferServer, &FlatBufferServer::initServer );
connect( fbThread, &QThread::finished, _flatBufferServer, &QObject::deleteLater ); connect( fbThread, &QThread::finished, _flatBufferServer, &QObject::deleteLater );
connect( fbThread, &QThread::finished, fbThread, &QObject::deleteLater ); connect( fbThread, &QThread::finished, fbThread, &QObject::deleteLater );
connect(this, &HyperionDaemon::settingsChanged, _flatBufferServer, &FlatBufferServer::handleSettingsUpdate);
fbThread->start(); fbThread->start();
// Create UDP listener // Create UDP listener
_udpListener = new UDPListener(getSetting(settings::UDPLISTENER)); _udpListener = new UDPListener(getSetting(settings::UDPLISTENER));
connect(this, &HyperionDaemon::settingsChanged, _udpListener, &UDPListener::handleSettingsUpdate); connect(this, &HyperionDaemon::settingsChanged, _udpListener, &UDPListener::handleSettingsUpdate);
// Create Webserver // Create Webserver in thread
_webserver = new WebServer(getSetting(settings::WEBSERVER)); _webserver = new WebServer(getSetting(settings::WEBSERVER));
QThread* wsThread = new QThread(this);
_webserver->moveToThread(wsThread);
connect( wsThread, &QThread::started, _webserver, &WebServer::initServer );
connect( wsThread, &QThread::finished, _webserver, &QObject::deleteLater );
connect( wsThread, &QThread::finished, wsThread, &QObject::deleteLater );
connect(this, &HyperionDaemon::settingsChanged, _webserver, &WebServer::handleSettingsUpdate); connect(this, &HyperionDaemon::settingsChanged, _webserver, &WebServer::handleSettingsUpdate);
wsThread->start();
// create SSDPHandler in thread
_ssdp = new SSDPHandler(_webserver, getSetting(settings::FLATBUFSERVER).object()["port"].toInt());
QThread* ssdpThread = new QThread(this);
_ssdp->moveToThread(ssdpThread);
connect( ssdpThread, &QThread::started, _ssdp, &SSDPHandler::initServer );
connect( ssdpThread, &QThread::finished, _ssdp, &QObject::deleteLater );
connect( ssdpThread, &QThread::finished, ssdpThread, &QObject::deleteLater );
connect( _webserver, &WebServer::stateChange, _ssdp, &SSDPHandler::handleWebServerStateChange);
connect(this, &HyperionDaemon::settingsChanged, _ssdp, &SSDPHandler::handleSettingsUpdate);
ssdpThread->start();
} }
void HyperionDaemon::handleSettingsUpdate(const settings::type& type, const QJsonDocument& config) void HyperionDaemon::handleSettingsUpdate(const settings::type& type, const QJsonDocument& config)

View File

@ -49,13 +49,13 @@
class Hyperion; class Hyperion;
class SysTray; class SysTray;
class JsonServer; class JsonServer;
class ProtoServer;
class UDPListener; class UDPListener;
class Stats; class Stats;
class BonjourBrowserWrapper; class BonjourBrowserWrapper;
class WebServer; class WebServer;
class SettingsManager; class SettingsManager;
class PythonInit; class PythonInit;
class SSDPHandler;
class FlatBufferServer; class FlatBufferServer;
class HyperionDaemon : public QObject class HyperionDaemon : public QObject
@ -68,7 +68,11 @@ public:
HyperionDaemon(QString configFile, QString rootPath, QObject *parent, const bool& logLvlOverwrite ); HyperionDaemon(QString configFile, QString rootPath, QObject *parent, const bool& logLvlOverwrite );
~HyperionDaemon(); ~HyperionDaemon();
quint16 getWebServerPort(); ///
/// @brief Get webserver pointer (systray)
///
WebServer* getWebServerInstance() { return _webserver; };
/// ///
/// @brief Get the current videoMode /// @brief Get the current videoMode
/// ///
@ -134,7 +138,6 @@ private:
PythonInit* _pyInit; PythonInit* _pyInit;
WebServer* _webserver; WebServer* _webserver;
JsonServer* _jsonServer; JsonServer* _jsonServer;
ProtoServer* _protoServer;
UDPListener* _udpListener; UDPListener* _udpListener;
std::vector<V4L2Wrapper*> _v4l2Grabbers; std::vector<V4L2Wrapper*> _v4l2Grabbers;
DispmanxWrapper* _dispmanx; DispmanxWrapper* _dispmanx;
@ -144,6 +147,7 @@ private:
OsxWrapper* _osxGrabber; OsxWrapper* _osxGrabber;
Hyperion* _hyperion; Hyperion* _hyperion;
Stats* _stats; Stats* _stats;
SSDPHandler* _ssdp;
FlatBufferServer* _flatBufferServer; FlatBufferServer* _flatBufferServer;
unsigned _grabber_width; unsigned _grabber_width;

View File

@ -332,7 +332,7 @@ int main(int argc, char** argv)
{ {
Info(log, "start systray"); Info(log, "start systray");
QApplication::setQuitOnLastWindowClosed(false); QApplication::setQuitOnLastWindowClosed(false);
SysTray tray(hyperiond, hyperiond->getWebServerPort()); SysTray tray(hyperiond);
tray.hide(); tray.hide();
rc = (qobject_cast<QApplication *>(app.data()))->exec(); rc = (qobject_cast<QApplication *>(app.data()))->exec();
} }

View File

@ -10,23 +10,28 @@
#include <utils/ColorRgb.h> #include <utils/ColorRgb.h>
#include <effectengine/EffectDefinition.h> #include <effectengine/EffectDefinition.h>
#include <webserver/WebServer.h>
#include "hyperiond.h" #include "hyperiond.h"
#include "systray.h" #include "systray.h"
SysTray::SysTray(HyperionDaemon *hyperiond, quint16 webPort) SysTray::SysTray(HyperionDaemon *hyperiond)
: QWidget() : QWidget()
, _colorDlg(this) , _colorDlg(this)
, _hyperiond(hyperiond) , _hyperiond(hyperiond)
, _webPort(webPort) , _hyperion(nullptr)
, _webPort(8090)
{ {
Q_INIT_RESOURCE(resource); Q_INIT_RESOURCE(resource);
// webserver port
WebServer* webserver = _hyperiond->getWebServerInstance();
connect(webserver, &WebServer::portChanged, this, &SysTray::webserverPortChanged);
_hyperion = Hyperion::getInstance(); _hyperion = Hyperion::getInstance();
createTrayIcon(); createTrayIcon();
connect(_trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), connect(_trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(iconActivated(QSystemTrayIcon::ActivationReason)));
this, SLOT(iconActivated(QSystemTrayIcon::ActivationReason)));
connect(&_colorDlg, SIGNAL(currentColorChanged(const QColor&)), this, SLOT(setColor(const QColor &))); connect(&_colorDlg, SIGNAL(currentColorChanged(const QColor&)), this, SLOT(setColor(const QColor &)));
QIcon icon(":/hyperion-icon.png"); QIcon icon(":/hyperion-icon.png");
_trayIcon->setIcon(icon); _trayIcon->setIcon(icon);

View File

@ -15,7 +15,7 @@ class SysTray : public QWidget
Q_OBJECT Q_OBJECT
public: public:
SysTray(HyperionDaemon *hyperiond, quint16 webPort); SysTray(HyperionDaemon *hyperiond);
~SysTray(); ~SysTray();
@ -30,6 +30,11 @@ public slots:
private slots: private slots:
void iconActivated(QSystemTrayIcon::ActivationReason reason); void iconActivated(QSystemTrayIcon::ActivationReason reason);
///
/// @brief is called whenever the webserver changes the port
///
void webserverPortChanged(const quint16& port) { _webPort = port; };
private: private:
void createTrayIcon(); void createTrayIcon();
@ -44,7 +49,7 @@ private:
QMenu *_trayIconMenu; QMenu *_trayIconMenu;
QMenu *_trayIconEfxMenu; QMenu *_trayIconEfxMenu;
QColorDialog _colorDlg; QColorDialog _colorDlg;
HyperionDaemon *_hyperiond; HyperionDaemon *_hyperiond;
quint16 _webPort;
Hyperion *_hyperion; Hyperion *_hyperion;
quint16 _webPort;
}; };