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

@ -182,8 +182,6 @@ public:
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:
///
@ -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

@ -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);
@ -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

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,157 +111,8 @@ private slots:
private:
///
/// Handle an incoming JSON message
///
/// @param message the incoming message as string
///
void handleMessage(const QString & message);
///
/// 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);
/// new instance of JsonProcessor
JsonProcessor * _jsonProcessor;
///
/// Do handshake for a websocket connection
@ -312,32 +124,9 @@ private:
///
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;
@ -350,32 +139,9 @@ private:
/// 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;
}