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

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