Move JsonProcessing from JsonClientConnection to own class (#444)

* update

* Tell me why...
This commit is contained in:
brindosch 2017-06-24 11:52:22 +02:00 committed by GitHub
parent dd5f840125
commit 5da871dc9f
10 changed files with 1709 additions and 1630 deletions

View File

@ -92,7 +92,7 @@ public:
/// @return The current priority
///
int getCurrentPriority() const;
///
/// Returns a list of active priorities
///
@ -117,15 +117,15 @@ public:
/// Get the list of available effects
/// @return The list of available effects
const std::list<EffectDefinition> &getEffects() const;
/// Get the list of active effects
/// @return The list of active effects
const std::list<ActiveEffectDefinition> &getActiveEffects();
/// Get the list of available effect schema files
/// @return The list of available effect schema files
const std::list<EffectSchema> &getEffectSchemas();
/// gets the current json config object
/// @return json config
const QJsonObject& getQJsonConfig() { return _qjsonConfig; };
@ -139,28 +139,28 @@ public:
/// @param origin External setter
/// @param priority priority channel
void registerPriority(const QString &name, const int priority);
/// unregister a input source to a priority channel
/// @param name uniq name of input source
void unRegisterPriority(const QString &name);
/// gets current priority register
/// @return the priority register
const PriorityRegister& getPriorityRegister() { return _priorityRegister; }
/// enable/disable automatic/priorized source selection
/// @param enabled the state
void setSourceAutoSelectEnabled(bool enabled);
/// set current input source to visible
/// @param priority the priority channel which should be vidible
/// @return true if success, false on error
bool setCurrentSourcePriority(int priority );
/// gets current state of automatic/priorized source selection
/// @return the state
bool sourceAutoSelectEnabled() { return _sourceAutoSelectEnabled; };
///
/// Enable/Disable components during runtime
///
@ -177,12 +177,10 @@ public:
/// gets the methode how image is maped to leds
int getLedMappingType() { return _ledMAppingType; };
int getConfigVersionId() { return _configVersionId; };
QJsonObject getConfig() { return _qjsonConfig; };
QString getConfigFile() { return _configFile; };
/// unique id per instance
QString id;
@ -273,6 +271,9 @@ public slots:
///
Hyperion::BonjourRegister getHyperionSessions();
/// Slot which is called, when state of hyperion has been changed
void hyperionStateChanged();
public:
static Hyperion *_hyperion;
@ -311,8 +312,11 @@ signals:
void emitImage(int priority, const Image<ColorRgb> & image, const int timeout_ms);
void closing();
/// Signal which is emitted, when state of config or bonjour or priorityMuxer changed
void hyperionStateChanged();
/// Signal which is emitted, when a new json message should be forwarded
void forwardJsonMessage(QJsonObject);
/// Signal which is emitted, after the hyperionStateChanged has been processed with a emit count blocker (250ms interval)
void sendServerInfo();
private slots:
///
@ -329,7 +333,7 @@ private slots:
void checkConfigState();
private:
///
/// Constructs the Hyperion instance based on the given Json configuration
///
@ -344,13 +348,13 @@ private:
LedString _ledStringClone;
std::vector<ColorOrder> _ledStringColorOrder;
/// The priority muxer
PriorityMuxer _muxer;
/// The adjustment from raw colors to led colors
MultiColorAdjustment * _raw2ledAdjustment;
/// The actual LedDevice
LedDevice * _device;
@ -359,7 +363,7 @@ private:
/// Effect engine
EffectEngine * _effectEngine;
// proto and json Message forwarder
MessageForwarder * _messageForwarder;
@ -383,24 +387,24 @@ private:
unsigned _hwLedCount;
ComponentRegister _componentRegister;
/// register of input sources and it's prio channel
PriorityRegister _priorityRegister;
/// flag indicates state for autoselection of input source
bool _sourceAutoSelectEnabled;
/// holds the current priority channel that is manualy selected
int _currentSourcePriority;
QByteArray _configHash;
QSize _ledGridSize;
int _ledMAppingType;
int _configVersionId;
hyperion::Components _prevCompId;
BonjourServiceBrowser _bonjourBrowser;
BonjourServiceResolver _bonjourResolver;
@ -417,4 +421,8 @@ private:
/// holds the current states of configWriteable and modified
bool _configMod = false;
bool _configWrite = true;
/// timers to handle severinfo blocking
QTimer _fsi_timer;
QTimer _fsi_blockTimer;
};

View File

@ -6,7 +6,6 @@
// Qt includes
#include <QTcpServer>
#include <QSet>
#include <QTimer>
// Hyperion includes
#include <hyperion/Hyperion.h>
@ -37,15 +36,12 @@ public:
///
uint16_t getPort() const;
private slots:
///
/// Slot which is called when a client tries to create a new connection
///
void newConnection();
///
/// Slot which is called when a new forced serverinfo should be pushed
///
void pushReq();
///
/// Slot which is called when a client closes a connection
@ -53,11 +49,25 @@ private slots:
///
void closedConnection(JsonClientConnection * connection);
/// forward message to all json slaves
void forwardJsonMessage(const QJsonObject &message);
public slots:
/// process current forwarder state
void componentStateChanged(const hyperion::Components component, bool enable);
///
/// forward message to a single json slaves
///
/// @param message The JSON message to send
///
void sendMessage(const QJsonObject & message, QTcpSocket * socket);
private:
/// The TCP server object
QTcpServer _server;
/// Link to Hyperion to get hyperion state emiter
/// Link to Hyperion to get config state emiter
Hyperion * _hyperion;
/// List with open connections
@ -66,6 +76,6 @@ private:
/// the logger instance
Logger * _log;
QTimer _timer;
QTimer _blockTimer;
/// Flag if forwarder is enabled
bool _forwarder_enabled = true;
};

View File

@ -0,0 +1,268 @@
#pragma once
// hyperion includes
#include <utils/Logger.h>
#include <utils/jsonschema/QJsonSchemaChecker.h>
#include <utils/Components.h>
#include <hyperion/Hyperion.h>
// qt includess
#include <QTimer>
#include <QJsonObject>
#include <QMutex>
#include <QString>
// createEffect helper
struct find_schema: std::unary_function<EffectSchema, bool>
{
QString pyFile;
find_schema(QString pyFile):pyFile(pyFile) { }
bool operator()(EffectSchema const& schema) const
{
return schema.pyFile == pyFile;
}
};
// deleteEffect helper
struct find_effect: std::unary_function<EffectDefinition, bool>
{
QString effectName;
find_effect(QString effectName) :effectName(effectName) { }
bool operator()(EffectDefinition const& effectDefinition) const
{
return effectDefinition.name == effectName;
}
};
class ImageProcessor;
class JsonProcessor : public QObject
{
Q_OBJECT
public:
JsonProcessor(QString peerAddress);
~JsonProcessor();
///
/// Handle an incoming JSON message
///
/// @param message the incoming message as string
///
void handleMessage(const QString & message);
///
/// send a forced serverinfo to a client
///
void forceServerInfo();
public slots:
/// _timer_ledcolors requests ledcolor updates (if enabled)
void streamLedcolorsUpdate();
/// push images whenever hyperion emits (if enabled)
void setImage(int priority, const Image<ColorRgb> & image, int duration_ms);
/// process and push new log messages from logger (if enabled)
void incommingLogMessage(Logger::T_LOG_MESSAGE);
signals:
///
/// Signal which is emitted when a sendSuccessReply() has been executed
///
void pushReq();
///
/// Signal emits with the reply message provided with handleMessage()
///
void callbackMessage(QJsonObject);
///
/// Signal emits whenever a jsonmessage should be forwarded
///
void forwardJsonMessage(QJsonObject);
private:
/// The peer address of the client
QString _peerAddress;
/// Log instance
Logger* _log;
/// Hyperion instance
Hyperion* _hyperion;
/// The processor for translating images to led-values
ImageProcessor * _imageProcessor;
/// holds the state before off state
static std::map<hyperion::Components, bool> _componentsPrevState;
/// returns if hyperion is on or off
inline bool hyperionIsActive() { return JsonProcessor::_componentsPrevState.empty(); };
/// timer for ledcolors streaming
QTimer _timer_ledcolors;
// streaming buffers
QJsonObject _streaming_leds_reply;
QJsonObject _streaming_image_reply;
QJsonObject _streaming_logging_reply;
/// flag to determine state of log streaming
bool _streaming_logging_activated;
/// mutex to determine state of image streaming
QMutex _image_stream_mutex;
/// timeout for live video refresh
volatile qint64 _image_stream_timeout;
///
/// Handle an incoming JSON Color message
///
/// @param message the incoming message
///
void handleColorCommand(const QJsonObject & message, const QString &command, const int tan);
///
/// Handle an incoming JSON Image message
///
/// @param message the incoming message
///
void handleImageCommand(const QJsonObject & message, const QString &command, const int tan);
///
/// Handle an incoming JSON Effect message
///
/// @param message the incoming message
///
void handleEffectCommand(const QJsonObject & message, const QString &command, const int tan);
///
/// Handle an incoming JSON Effect message (Write JSON Effect)
///
/// @param message the incoming message
///
void handleCreateEffectCommand(const QJsonObject & message, const QString &command, const int tan);
///
/// Handle an incoming JSON Effect message (Delete JSON Effect)
///
/// @param message the incoming message
///
void handleDeleteEffectCommand(const QJsonObject & message, const QString &command, const int tan);
///
/// Handle an incoming JSON System info message
///
/// @param message the incoming message
///
void handleSysInfoCommand(const QJsonObject & message, const QString &command, const int tan);
///
/// Handle an incoming JSON Server info message
///
/// @param message the incoming message
///
void handleServerInfoCommand(const QJsonObject & message, const QString &command, const int tan);
///
/// Handle an incoming JSON Clear message
///
/// @param message the incoming message
///
void handleClearCommand(const QJsonObject & message, const QString &command, const int tan);
///
/// Handle an incoming JSON Clearall message
///
/// @param message the incoming message
///
void handleClearallCommand(const QJsonObject & message, const QString &command, const int tan);
///
/// Handle an incoming JSON Adjustment message
///
/// @param message the incoming message
///
void handleAdjustmentCommand(const QJsonObject & message, const QString &command, const int tan);
///
/// Handle an incoming JSON SourceSelect message
///
/// @param message the incoming message
///
void handleSourceSelectCommand(const QJsonObject & message, const QString &command, const int tan);
/// Handle an incoming JSON GetConfig message and check subcommand
///
/// @param message the incoming message
///
void handleConfigCommand(const QJsonObject & message, const QString &command, const int tan);
/// Handle an incoming JSON GetConfig message from handleConfigCommand()
///
/// @param message the incoming message
///
void handleSchemaGetCommand(const QJsonObject & message, const QString &command, const int tan);
/// Handle an incoming JSON GetConfig message from handleConfigCommand()
///
/// @param message the incoming message
///
void handleConfigGetCommand(const QJsonObject & message, const QString &command, const int tan);
///
/// Handle an incoming JSON Component State message
///
/// @param message the incoming message
///
void handleComponentStateCommand(const QJsonObject & message, const QString &command, const int tan);
/// Handle an incoming JSON Led Colors message
///
/// @param message the incoming message
///
void handleLedColorsCommand(const QJsonObject & message, const QString &command, const int tan);
/// Handle an incoming JSON Logging message
///
/// @param message the incoming message
///
void handleLoggingCommand(const QJsonObject & message, const QString &command, const int tan);
/// Handle an incoming JSON Proccessing message
///
/// @param message the incoming message
///
void handleProcessingCommand(const QJsonObject & message, const QString &command, const int tan);
///
/// Handle an incoming JSON message of unknown type
///
void handleNotImplemented();
///
/// Send a standard reply indicating success
///
void sendSuccessReply(const QString &command="", const int tan=0);
///
/// Send an error message back to the client
///
/// @param error String describing the error
///
void sendErrorReply(const QString & error, const QString &command="", const int tan=0);
///
/// Check if a JSON messag is valid according to a given JSON schema
///
/// @param message JSON message which need to be checked
/// @param schemaResource Qt Resource identifier with the JSON schema
/// @param errors Output error message
/// @param ignoreRequired ignore the required value in JSON schema
///
/// @return true if message conforms the given JSON schema
///
bool checkJson(const QJsonObject & message, const QString &schemaResource, QString & errors, bool ignoreRequired = false);
};

View File

@ -50,7 +50,7 @@ Hyperion* Hyperion::getInstance()
{
if ( Hyperion::_hyperion == nullptr )
throw std::runtime_error("Hyperion::getInstance used without call of Hyperion::initInstance before");
return Hyperion::_hyperion;
}
@ -153,7 +153,7 @@ MultiColorAdjustment * Hyperion::createLedColorsAdjustment(const unsigned ledCnt
ss << index;
}
}
Info(CORE_LOGGER, "ColorAdjustment '%s' => [%s]", QSTRING_CSTR(colorAdjustment->_id), ss.str().c_str());
Info(CORE_LOGGER, "ColorAdjustment '%s' => [%s]", QSTRING_CSTR(colorAdjustment->_id), ss.str().c_str());
}
return adjustment;
@ -190,7 +190,7 @@ LedString Hyperion::createLedString(const QJsonValue& ledsConfig, const ColorOrd
const QString deviceOrderStr = colorOrderToString(deviceOrder);
const QJsonArray & ledConfigArray = ledsConfig.toArray();
int maxLedId = ledConfigArray.size();
for (signed i = 0; i < ledConfigArray.size(); ++i)
{
const QJsonObject& index = ledConfigArray[i].toObject();
@ -325,7 +325,7 @@ LinearColorSmoothing * Hyperion::createColorSmoothing(const QJsonObject & smooth
QString type = smoothingConfig["type"].toString("linear").toLower();
LinearColorSmoothing * device = nullptr;
type = "linear"; // TODO currently hardcoded type, delete it if we have more types
if (type == "linear")
{
Info( CORE_LOGGER, "Creating linear smoothing");
@ -341,7 +341,7 @@ LinearColorSmoothing * Hyperion::createColorSmoothing(const QJsonObject & smooth
{
Error(CORE_LOGGER, "Smoothing disabled, because of unknown type '%s'.", QSTRING_CSTR(type));
}
device->setEnable(smoothingConfig["enable"].toBool(true));
InfoIf(!device->enabled(), CORE_LOGGER,"Smoothing disabled");
@ -414,11 +414,11 @@ Hyperion::Hyperion(const QJsonObject &qjsonConfig, const QString configFile)
_bonjourBrowser.browseForServiceType(QLatin1String("_hyperiond-http._tcp"));
connect(&_bonjourBrowser, SIGNAL(currentBonjourRecordsChanged(const QList<BonjourRecord>&)),this, SLOT(currentBonjourRecordsChanged(const QList<BonjourRecord> &)));
connect(&_bonjourResolver, SIGNAL(bonjourRecordResolved(const QHostInfo &, int)), this, SLOT(bonjourRecordResolved(const QHostInfo &, int)));
// initialize the image processor factory
_ledMAppingType = ImageProcessor::mappingTypeToInt(color["imageToLedMappingType"].toString());
ImageProcessorFactory::getInstance().init(_ledString, qjsonConfig["blackborderdetector"].toObject(),_ledMAppingType );
getComponentRegister().componentStateChanged(hyperion::COMP_FORWARDER, _messageForwarder->forwardingEnabled());
// initialize leddevices
@ -438,7 +438,7 @@ Hyperion::Hyperion(const QJsonObject &qjsonConfig, const QString configFile)
// create the effect engine
_effectEngine = new EffectEngine(this,qjsonConfig["effects"].toObject() );
const QJsonObject& device = qjsonConfig["device"].toObject();
unsigned int hwLedCount = device["ledCount"].toInt(getLedCount());
_hwLedCount = std::max(hwLedCount, getLedCount());
@ -450,9 +450,14 @@ Hyperion::Hyperion(const QJsonObject &qjsonConfig, const QString configFile)
QObject::connect(&_cTimer, SIGNAL(timeout()), this, SLOT(checkConfigState()));
_cTimer.start(2000);
// pipe muxer signal for effect/color timerunner to hyperionStateChanged signal
// pipe muxer signal for effect/color timerunner to hyperionStateChanged slot
QObject::connect(&_muxer, &PriorityMuxer::timerunner, this, &Hyperion::hyperionStateChanged);
// prepare processing of hyperionStateChanged for forced serverinfo
connect(&_fsi_timer, SIGNAL(timeout()), this, SLOT(hyperionStateChanged()));
_fsi_timer.setSingleShot(true);
_fsi_blockTimer.setSingleShot(true);
const QJsonObject & generalConfig = qjsonConfig["general"].toObject();
_configVersionId = generalConfig["configVersion"].toInt(-1);
@ -542,7 +547,7 @@ Hyperion::BonjourRegister Hyperion::getHyperionSessions()
void Hyperion::checkConfigState()
{
// Check config modifications
// Check config modifications
QFile f(_configFile);
if (f.open(QFile::ReadOnly))
{
@ -568,9 +573,9 @@ void Hyperion::checkConfigState()
QFile file(_configFile);
QFileInfo fileInfo(file);
_configWrite = fileInfo.isWritable() && fileInfo.isReadable() ? true : false;
if(_prevConfigWrite != _configWrite)
{
{
emit hyperionStateChanged();
_prevConfigWrite = _configWrite;
}
@ -579,7 +584,7 @@ void Hyperion::checkConfigState()
void Hyperion::registerPriority(const QString &name, const int priority/*, const QString &origin*/)
{
Info(_log, "Register new input source named '%s' for priority channel '%d'", QSTRING_CSTR(name), priority );
for(auto key : _priorityRegister.keys())
{
WarningIf( ( key != name && _priorityRegister.value(key) == priority), _log,
@ -734,7 +739,7 @@ void Hyperion::clearall()
int Hyperion::getCurrentPriority() const
{
return _sourceAutoSelectEnabled || !_muxer.hasPriority(_currentSourcePriority) ? _muxer.getCurrentPriority() : _currentSourcePriority;
}
@ -784,6 +789,19 @@ void Hyperion::setLedMappingType(int mappingType)
emit imageToLedsMappingChanged(mappingType);
}
void Hyperion::hyperionStateChanged()
{
if(_fsi_blockTimer.isActive())
{
_fsi_timer.start(300);
}
else
{
emit sendServerInfo();
_fsi_blockTimer.start(250);
}
}
void Hyperion::update()
{
// Update the muxer, cleaning obsolete priorities
@ -817,13 +835,13 @@ void Hyperion::update()
_ledStringColorOrder.insert(_ledStringColorOrder.begin() + led.index, led.colorOrder);
}
}
// insert cloned leds into buffer
for (Led& led : _ledStringClone.leds())
{
_ledBuffer.insert(_ledBuffer.begin() + led.index, _ledBuffer.at(led.clone));
}
int i = 0;
for (ColorRgb& color : _ledBuffer)
{
@ -861,7 +879,7 @@ void Hyperion::update()
{
_ledBuffer.resize(_hwLedCount, ColorRgb::BLACK);
}
// Write the data to the device
if (_device->enabled())
{
@ -869,7 +887,7 @@ void Hyperion::update()
// feed smoothing in pause mode to maintain a smooth transistion back to smoth mode
if (_deviceSmooth->enabled() || _deviceSmooth->pause())
_deviceSmooth->setLedValues(_ledBuffer);
if (! _deviceSmooth->enabled())
_device->setLedValues(_ledBuffer);
}

File diff suppressed because it is too large Load Diff

View File

@ -5,7 +5,6 @@
// Qt includes
#include <QByteArray>
#include <QTcpSocket>
#include <QMutex>
#include <QHostAddress>
#include <QString>
@ -13,12 +12,8 @@
#include <hyperion/Hyperion.h>
// util includes
#include <utils/jsonschema/QJsonSchemaChecker.h>
#include <utils/Logger.h>
#include <utils/Components.h>
class ImageProcessor;
#include <utils/JsonProcessor.h>
/// Constants and utility functions related to WebSocket opcodes
/**
@ -74,26 +69,6 @@ namespace OPCODE {
}
}
struct find_schema: std::unary_function<EffectSchema, bool>
{
QString pyFile;
find_schema(QString pyFile):pyFile(pyFile) { }
bool operator()(EffectSchema const& schema) const
{
return schema.pyFile == pyFile;
}
};
struct find_effect: std::unary_function<EffectDefinition, bool>
{
QString effectName;
find_effect(QString effectName) :effectName(effectName) { }
bool operator()(EffectDefinition const& effectDefinition) const
{
return effectDefinition.name == effectName;
}
};
///
/// The Connection object created by \a JsonServer when a new connection is establshed
///
@ -105,7 +80,6 @@ public:
///
/// Constructor
/// @param socket The Socket object for this connection
/// @param hyperion The Hyperion server
///
JsonClientConnection(QTcpSocket * socket);
@ -114,16 +88,8 @@ public:
///
~JsonClientConnection();
///
/// send a forced serverinfo to a client
///
void forceServerInfo();
public slots:
void componentStateChanged(const hyperion::Components component, bool enable);
void streamLedcolorsUpdate();
void incommingLogMessage(Logger::T_LOG_MESSAGE);
void setImage(int priority, const Image<ColorRgb> & image, int duration_ms);
void sendMessage(QJsonObject);
signals:
///
@ -132,11 +98,6 @@ signals:
///
void connectionClosed(JsonClientConnection * connection);
///
/// Signal which is emitted when a sendSuccessReply() has been executed
///
void pushReq();
private slots:
///
/// Slot called when new data has arrived
@ -150,232 +111,37 @@ private slots:
private:
///
/// Handle an incoming JSON message
///
/// @param message the incoming message as string
///
void handleMessage(const QString & message);
/// new instance of JsonProcessor
JsonProcessor * _jsonProcessor;
///
/// Handle an incoming JSON Color message
///
/// @param message the incoming message
///
void handleColorCommand(const QJsonObject & message, const QString &command, const int tan);
///
/// Handle an incoming JSON Image message
///
/// @param message the incoming message
///
void handleImageCommand(const QJsonObject & message, const QString &command, const int tan);
///
/// Handle an incoming JSON Effect message
///
/// @param message the incoming message
///
void handleEffectCommand(const QJsonObject & message, const QString &command, const int tan);
///
/// Handle an incoming JSON Effect message (Write JSON Effect)
///
/// @param message the incoming message
///
void handleCreateEffectCommand(const QJsonObject & message, const QString &command, const int tan);
///
/// Handle an incoming JSON Effect message (Delete JSON Effect)
///
/// @param message the incoming message
///
void handleDeleteEffectCommand(const QJsonObject & message, const QString &command, const int tan);
///
/// Handle an incoming JSON Server info message
///
/// @param message the incoming message
///
void handleServerInfoCommand(const QJsonObject & message, const QString &command, const int tan);
///
/// Handle an incoming JSON System info message
///
/// @param message the incoming message
///
void handleSysInfoCommand(const QJsonObject & message, const QString &command, const int tan);
///
/// Handle an incoming JSON Clear message
///
/// @param message the incoming message
///
void handleClearCommand(const QJsonObject & message, const QString &command, const int tan);
///
/// Handle an incoming JSON Clearall message
///
/// @param message the incoming message
///
void handleClearallCommand(const QJsonObject & message, const QString &command, const int tan);
///
/// Handle an incoming JSON Adjustment message
///
/// @param message the incoming message
///
void handleAdjustmentCommand(const QJsonObject & message, const QString &command, const int tan);
///
/// Handle an incoming JSON SourceSelect message
///
/// @param message the incoming message
///
void handleSourceSelectCommand(const QJsonObject & message, const QString &command, const int tan);
/// Handle an incoming JSON GetConfig message
///
/// @param message the incoming message
///
void handleConfigCommand(const QJsonObject & message, const QString &command, const int tan);
/// Handle an incoming JSON GetConfig message
///
/// @param message the incoming message
///
void handleSchemaGetCommand(const QJsonObject & message, const QString &command, const int tan);
/// Handle an incoming JSON GetConfig message
///
/// @param message the incoming message
///
void handleConfigGetCommand(const QJsonObject & message, const QString &command, const int tan);
///
/// Handle an incoming JSON Component State message
///
/// @param message the incoming message
///
void handleComponentStateCommand(const QJsonObject & message, const QString &command, const int tan);
/// Handle an incoming JSON Led Colors message
///
/// @param message the incoming message
///
void handleLedColorsCommand(const QJsonObject & message, const QString &command, const int tan);
/// Handle an incoming JSON Logging message
///
/// @param message the incoming message
///
void handleLoggingCommand(const QJsonObject & message, const QString &command, const int tan);
/// Handle an incoming JSON Proccessing message
///
/// @param message the incoming message
///
void handleProcessingCommand(const QJsonObject & message, const QString &command, const int tan);
///
/// Handle an incoming JSON message of unknown type
///
void handleNotImplemented();
///
/// Send a message to the connected client
///
/// @param message The JSON message to send
///
void sendMessage(const QJsonObject & message);
void sendMessage(const QJsonObject & message, QTcpSocket * socket);
///
/// Send a standard reply indicating success
///
void sendSuccessReply(const QString &command="", const int tan=0);
///
/// Send an error message back to the client
///
/// @param error String describing the error
///
void sendErrorReply(const QString & error, const QString &command="", const int tan=0);
///
/// Do handshake for a websocket connection
///
void doWebSocketHandshake();
///
/// Handle incoming websocket data frame
///
void handleWebSocketFrame();
///
/// forward json message
///
void forwardJsonMessage(const QJsonObject & message);
///
/// Check if a JSON messag is valid according to a given JSON schema
///
/// @param message JSON message which need to be checked
/// @param schemaResource Qt Resource identifier with the JSON schema
/// @param errors Output error message
/// @param ignoreRequired ignore the required value in JSON schema
///
/// @return true if message conforms the given JSON schema
///
bool checkJson(const QJsonObject & message, const QString &schemaResource, QString & errors, bool ignoreRequired = false);
/// returns if hyperion is on or off
inline bool hyperionIsActive() { return JsonClientConnection::_componentsPrevState.empty(); };
/// The TCP-Socket that is connected tot the Json-client
QTcpSocket * _socket;
/// The processor for translating images to led-values
ImageProcessor * _imageProcessor;
/// Link to Hyperion for writing led-values to a priority channel
Hyperion * _hyperion;
/// The buffer used for reading data from the socket
QByteArray _receiveBuffer;
/// used for WebSocket detection and connection handling
bool _webSocketHandshakeDone;
/// The logger instance
Logger * _log;
/// Flag if forwarder is enabled
bool _forwarder_enabled;
/// timer for ledcolors streaming
QTimer _timer_ledcolors;
// streaming buffers
QJsonObject _streaming_leds_reply;
QJsonObject _streaming_image_reply;
QJsonObject _streaming_logging_reply;
/// flag to determine state of log streaming
bool _streaming_logging_activated;
/// mutex to determine state of image streaming
QMutex _image_stream_mutex;
/// timeout for live video refresh
volatile qint64 _image_stream_timeout;
/// address of client
QHostAddress _clientAddress;
/// holds the state before off state
static std::map<hyperion::Components, bool> _componentsPrevState;
// masks for fields in the basic header
static uint8_t const BHB0_OPCODE = 0x0F;
static uint8_t const BHB0_RSV3 = 0x10;

View File

@ -5,6 +5,14 @@
#include <jsonserver/JsonServer.h>
#include "JsonClientConnection.h"
// hyperion include
#include <hyperion/MessageForwarder.h>
// qt includes
#include <QTcpSocket>
#include <QJsonDocument>
#include <QByteArray>
JsonServer::JsonServer(uint16_t port)
: QObject()
, _server()
@ -28,17 +36,14 @@ JsonServer::JsonServer(uint16_t port)
// Set trigger for incoming connections
connect(&_server, SIGNAL(newConnection()), this, SLOT(newConnection()));
// connect delay timer and setup
connect(&_timer, SIGNAL(timeout()), this, SLOT(pushReq()));
_timer.setSingleShot(true);
_blockTimer.setSingleShot(true);
// register for hyprion state changes (bonjour, config, prioritymuxer, register/unregister source)
connect(_hyperion, SIGNAL(hyperionStateChanged()), this, SLOT(pushReq()));
// make sure the resources are loaded (they may be left out after static linking
Q_INIT_RESOURCE(JsonSchemas);
// receive state of forwarder
connect(_hyperion, &Hyperion::componentStateChanged, this, &JsonServer::componentStateChanged);
// initial connect TODO get initial state from config to stop messing
connect(_hyperion, &Hyperion::forwardJsonMessage, this, &JsonServer::forwardJsonMessage);
}
JsonServer::~JsonServer()
@ -63,9 +68,6 @@ void JsonServer::newConnection()
JsonClientConnection * connection = new JsonClientConnection(socket);
_openConnections.insert(connection);
// register for JSONClientConnection events
connect(connection, SIGNAL(pushReq()), this, SLOT(pushReq()));
// register slot for cleaning up after the connection closed
connect(connection, SIGNAL(connectionClosed(JsonClientConnection*)), this, SLOT(closedConnection(JsonClientConnection*)));
}
@ -80,17 +82,75 @@ void JsonServer::closedConnection(JsonClientConnection *connection)
connection->deleteLater();
}
void JsonServer::pushReq()
void JsonServer::componentStateChanged(const hyperion::Components component, bool enable)
{
if(_blockTimer.isActive())
if (component == hyperion::COMP_FORWARDER && _forwarder_enabled != enable)
{
_timer.start(250);
}
else
{
foreach (JsonClientConnection * connection, _openConnections) {
connection->forceServerInfo();
_forwarder_enabled = enable;
Info(_log, "forwarder change state to %s", (enable ? "enabled" : "disabled") );
if(_forwarder_enabled)
{
connect(_hyperion, &Hyperion::forwardJsonMessage, this, &JsonServer::forwardJsonMessage);
}
else
{
disconnect(_hyperion, &Hyperion::forwardJsonMessage, this, &JsonServer::forwardJsonMessage);
}
_blockTimer.start(250);
}
}
void JsonServer::forwardJsonMessage(const QJsonObject &message)
{
QTcpSocket client;
QList<MessageForwarder::JsonSlaveAddress> list = _hyperion->getForwarder()->getJsonSlaves();
for ( int i=0; i<list.size(); i++ )
{
client.connectToHost(list.at(i).addr, list.at(i).port);
if ( client.waitForConnected(500) )
{
sendMessage(message,&client);
client.close();
}
}
}
void JsonServer::sendMessage(const QJsonObject & message, QTcpSocket * socket)
{
// serialize message
QJsonDocument writer(message);
QByteArray serializedMessage = writer.toJson(QJsonDocument::Compact) + "\n";
// write message
socket->write(serializedMessage);
if (!socket->waitForBytesWritten())
{
Debug(_log, "Error while writing data to host");
return;
}
// read reply data
QByteArray serializedReply;
while (!serializedReply.contains('\n'))
{
// receive reply
if (!socket->waitForReadyRead())
{
Debug(_log, "Error while writing data from host");
return;
}
serializedReply += socket->readAll();
}
// parse reply data
QJsonParseError error;
QJsonDocument reply = QJsonDocument::fromJson(serializedReply ,&error);
if (error.error != QJsonParseError::NoError)
{
Error(_log, "Error while parsing reply: invalid json");
return;
}
}

View File

@ -6,6 +6,7 @@ SET(CURRENT_SOURCE_DIR ${CMAKE_SOURCE_DIR}/libsrc/utils)
SET(Utils_QT_HEADERS
${CURRENT_HEADER_DIR}/Logger.h
${CURRENT_HEADER_DIR}/Stats.h
${CURRENT_HEADER_DIR}/JsonProcessor.h
)
SET(Utils_HEADERS
@ -46,6 +47,7 @@ SET(Utils_SOURCES
${CURRENT_SOURCE_DIR}/RgbToRgbw.cpp
${CURRENT_SOURCE_DIR}/SysInfo.cpp
${CURRENT_SOURCE_DIR}/Stats.cpp
${CURRENT_SOURCE_DIR}/JsonProcessor.cpp
${CURRENT_SOURCE_DIR}/jsonschema/QJsonSchemaChecker.cpp
)

File diff suppressed because it is too large Load Diff

View File

@ -23,7 +23,7 @@ Stats::Stats()
{
if (!(interface.flags() & QNetworkInterface::IsLoopBack))
{
_hyperion->id = QString(QCryptographicHash::hash(interface.hardwareAddress().toLocal8Bit().append(_hyperion->getConfigFile().toLocal8Bit()),QCryptographicHash::Sha1).toHex());
_hyperion->id = QString(QCryptographicHash::hash(interface.hardwareAddress().toLocal8Bit().append(_hyperion->getConfigFileName().toLocal8Bit()),QCryptographicHash::Sha1).toHex());
_hash = QString(QCryptographicHash::hash(interface.hardwareAddress().toLocal8Bit(),QCryptographicHash::Sha1).toHex());
break;
}
@ -34,7 +34,7 @@ Stats::Stats()
{
Warning(_log, "No interface found, abort");
// fallback id
_hyperion->id = QString(QCryptographicHash::hash(_hyperion->getConfigFile().toLocal8Bit(),QCryptographicHash::Sha1).toHex());
_hyperion->id = QString(QCryptographicHash::hash(_hyperion->getConfigFileName().toLocal8Bit(),QCryptographicHash::Sha1).toHex());
return;
}