JsonCpp to QTJson (Part 4) (#266)

* Update ActiveEffectDefinition.h

* Update EffectDefinition.h

* Update EffectEngine.h

* Update Hyperion.h

* Update LedDevice.h

* Update QJsonFactory.h

* Update QJsonSchemaChecker.h

* Update Effect.cpp

* Update Effect.h

* Update EffectEngine.cpp

* Update Hyperion.cpp

* Update JsonClientConnection.cpp

* Update JsonClientConnection.h

* Update schema-config.json

* Update LedDevice.cpp

* Update QJsonSchemaChecker.cpp

* Update hyperion-remote.cpp

* Update JsonConnection.cpp

* Update JsonConnection.h

* Update hyperiond.cpp
This commit is contained in:
Paulchen Panther 2016-10-09 22:22:17 +02:00 committed by redPanther
parent 0a142b0e7d
commit d9c2a2d91a
20 changed files with 660 additions and 468 deletions

View File

@ -1,16 +1,14 @@
#pragma once
// stl include
#include <string>
// json include
#include <json/value.h>
// QT include
#include <QString>
#include <QJsonObject>
struct ActiveEffectDefinition
{
std::string script;
std::string name;
QString script;
QString name;
int priority;
int timeout;
Json::Value args;
QJsonObject args;
};

View File

@ -1,14 +1,12 @@
#pragma once
// stl include
#include <string>
// json include
#include <json/value.h>
// QT include
#include <QString>
#include <QJsonObject>
struct EffectDefinition
{
std::string name;
std::string script;
Json::Value args;
QString name;
QString script;
QJsonObject args;
};

View File

@ -3,9 +3,10 @@
// Qt includes
#include <QObject>
#include <QString>
// Json includes
#include <json/value.h>
#include <QJsonObject>
#include <QJsonValue>
#include <QJsonDocument>
#include <QJsonArray>
// Hyperion includes
#include <hyperion/Hyperion.h>
@ -24,7 +25,7 @@ class EffectEngine : public QObject
Q_OBJECT
public:
EffectEngine(Hyperion * hyperion, const Json::Value & jsonEffectConfig);
EffectEngine(Hyperion * hyperion, const QJsonObject & jsonEffectConfig);
virtual ~EffectEngine();
const std::list<EffectDefinition> & getEffects() const;
@ -35,10 +36,10 @@ public:
public slots:
/// Run the specified effect on the given priority channel and optionally specify a timeout
int runEffect(const std::string &effectName, int priority, int timeout = -1);
int runEffect(const QString &effectName, int priority, int timeout = -1);
/// Run the specified effect on the given priority channel and optionally specify a timeout
int runEffect(const std::string &effectName, const Json::Value & args, int priority, int timeout = -1);
int runEffect(const QString &effectName, const QJsonObject & args, int priority, int timeout = -1);
/// Clear any effect running on the provided channel
void channelCleared(int priority);
@ -51,7 +52,7 @@ private slots:
private:
/// Run the specified effect on the given priority channel and optionally specify a timeout
int runEffectScript(const std::string &script, const std::string &name, const Json::Value & args, int priority, int timeout = -1);
int runEffectScript(const QString &script, const QString &name, const QJsonObject & args, int priority, int timeout = -1);
private:
Hyperion * _hyperion;

View File

@ -128,6 +128,7 @@ public:
/// gets the current json config object
/// @return json config
const Json::Value& getJsonConfig() { return _jsonConfig; };
const QJsonObject& getQJsonConfig() { return _qjsonConfig; };
/// get filename of configfile
/// @return the current config filename
@ -261,14 +262,14 @@ public slots:
/// @param effectName Name of the effec to run
/// @param priority The priority channel of the effect
/// @param timout The timeout of the effect (after the timout, the effect will be cleared)
int setEffect(const std::string & effectName, int priority, int timeout = -1);
int setEffect(const QString & effectName, int priority, int timeout = -1);
/// Run the specified effect on the given priority channel and optionally specify a timeout
/// @param effectName Name of the effec to run
/// @param args arguments of the effect script
/// @param priority The priority channel of the effect
/// @param timout The timeout of the effect (after the timout, the effect will be cleared)
int setEffect(const std::string & effectName, const Json::Value & args, int priority, int timeout = -1);
int setEffect(const QString & effectName, const QJsonObject & args, int priority, int timeout = -1);
public:
static Hyperion *_hyperion;
@ -360,6 +361,7 @@ private:
// json configuration
const Json::Value& _jsonConfig;
const QJsonObject& _qjsonConfig;
// the name of config file
std::string _configFile;

View File

@ -52,7 +52,7 @@ public:
static const LedDeviceRegistry& getDeviceMap();
static void setActiveDevice(std::string dev);
static std::string activeDevice() { return _activeDevice; }
static Json::Value getLedDeviceSchemas();
static QJsonObject getLedDeviceSchemas();
static void setLedCount(int ledCount);
static int getLedCount() { return _ledCount; }
protected:

View File

@ -85,4 +85,16 @@ public:
file.close();
return doc.object();
}
static void writeJson(const QString& filename, QJsonObject& jsonTree)
{
QJsonDocument doc;
doc.setObject(jsonTree);
QByteArray configData = doc.toJson(QJsonDocument::Indented);
QFile configFile(filename);
configFile.open(QIODevice::WriteOnly | QIODevice::Truncate);
configFile.write(configData);
configFile.close();
}
};

View File

@ -43,7 +43,7 @@ public:
/// @param value The JSON value to check
/// @return true when the arguments is valid according to the schema
///
bool validate(const QJsonObject & value);
bool validate(const QJsonObject & value, bool ignoreRequired = false);
///
/// @return A list of error messages
@ -180,7 +180,8 @@ private:
private:
/// The schema of the entire json-configuration
QJsonObject _qSchema;
/// ignore the required value in json schema
bool _ignoreRequired;
/// The current location into a json-configuration structure being checked
std::list<std::string> _currentPath;
/// The result messages collected during the schema verification

View File

@ -63,7 +63,7 @@ void Effect::registerHyperionExtensionModule()
PyImport_AppendInittab("hyperion", &PyInit_hyperion);
}
Effect::Effect(PyThreadState * mainThreadState, int priority, int timeout, const QString & script, const QString & name, const Json::Value & args)
Effect::Effect(PyThreadState * mainThreadState, int priority, int timeout, const QString & script, const QString & name, const QJsonObject & args)
: QThread()
, _mainThreadState(mainThreadState)
, _priority(priority)
@ -178,43 +178,50 @@ void Effect::effectFinished()
emit effectFinished(this);
}
PyObject *Effect::json2python(const Json::Value &json) const
{
switch (json.type())
PyObject *Effect::json2python(const QJsonValue &jsonData) const
{
switch (jsonData.type())
{
case Json::nullValue:
return Py_BuildValue("");
case Json::realValue:
return Py_BuildValue("d", json.asDouble());
case Json::intValue:
case Json::uintValue:
return Py_BuildValue("i", json.asInt());
case Json::booleanValue:
return Py_BuildValue("i", json.asBool() ? 1 : 0);
case Json::stringValue:
return Py_BuildValue("s", json.asCString());
case Json::objectValue:
{
PyObject * dict= PyDict_New();
for (Json::Value::iterator i = json.begin(); i != json.end(); ++i)
case QJsonValue::Null:
return Py_BuildValue("");
case QJsonValue::Undefined:
return Py_BuildValue("");
case QJsonValue::Double:
{
PyObject * obj = json2python(*i);
PyDict_SetItemString(dict, i.memberName(), obj);
Py_XDECREF(obj);
if (rint(jsonData.toDouble()) != jsonData.toDouble())
Py_BuildValue("d", jsonData.toDouble());
else
return Py_BuildValue("i", jsonData.toInt());
}
return dict;
}
case Json::arrayValue:
{
PyObject * list = PyList_New(json.size());
for (Json::Value::iterator i = json.begin(); i != json.end(); ++i)
case QJsonValue::Bool:
return Py_BuildValue("i", jsonData.toBool() ? 1 : 0);
case QJsonValue::String:
return Py_BuildValue("s", jsonData.toString().toUtf8().constData());
case QJsonValue::Object:
{
PyObject * obj = json2python(*i);
PyList_SetItem(list, i.index(), obj);
Py_XDECREF(obj);
PyObject * dict= PyDict_New();
QJsonObject objectData = jsonData.toObject();
for (QJsonObject::iterator i = objectData.begin(); i != objectData.end(); ++i)
{
PyObject * obj = json2python(*i);
PyDict_SetItemString(dict, i.key().toStdString().c_str(), obj);
Py_XDECREF(obj);
}
return dict;
}
case QJsonValue::Array:
{
QJsonArray arrayData = jsonData.toArray();
PyObject * list = PyList_New(arrayData.size());
int index = 0;
for (QJsonArray::iterator i = arrayData.begin(); i != arrayData.end(); ++i, ++index)
{
PyObject * obj = json2python(*i);
PyList_SetItem(list, index, obj);
Py_XDECREF(obj);
}
return list;
}
return list;
}
}
assert(false);

View File

@ -17,7 +17,7 @@ class Effect : public QThread
Q_OBJECT
public:
Effect(PyThreadState * mainThreadState, int priority, int timeout, const QString & script, const QString & name, const Json::Value & args = Json::Value());
Effect(PyThreadState * mainThreadState, int priority, int timeout, const QString & script, const QString & name, const QJsonObject & args = QJsonObject());
virtual ~Effect();
virtual void run();
@ -29,7 +29,7 @@ public:
int getTimeout() const {return _timeout; }
Json::Value getArgs() const { return _args; }
QJsonObject getArgs() const { return _args; }
bool isAbortRequested() const;
@ -48,7 +48,7 @@ private slots:
void effectFinished();
private:
PyObject * json2python(const Json::Value & json) const;
PyObject * json2python(const QJsonValue & jsonData) const;
// Wrapper methods for Python interpreter extra buildin methods
static PyMethodDef effectMethods[];
@ -79,7 +79,7 @@ private:
const QString _script;
const QString _name;
const Json::Value _args;
const QJsonObject _args;
int64_t _endTime;

View File

@ -11,7 +11,7 @@
#include <QDir>
// hyperion util includes
#include <utils/jsonschema/JsonSchemaChecker.h>
#include <utils/jsonschema/QJsonSchemaChecker.h>
#include <utils/FileUtils.h>
// effect engine includes
@ -19,7 +19,7 @@
#include "Effect.h"
#include "HyperionConfig.h"
EffectEngine::EffectEngine(Hyperion * hyperion, const Json::Value & jsonEffectConfig)
EffectEngine::EffectEngine(Hyperion * hyperion, const QJsonObject & jsonEffectConfig)
: _hyperion(hyperion)
, _availableEffects()
, _activeEffects()
@ -34,23 +34,23 @@ EffectEngine::EffectEngine(Hyperion * hyperion, const Json::Value & jsonEffectCo
connect(_hyperion, SIGNAL(allChannelsCleared()), this, SLOT(allChannelsCleared()));
// read all effects
const Json::Value & paths = jsonEffectConfig["paths"];
const Json::Value & disabledEfx = jsonEffectConfig["disable"];
const QJsonArray & paths = jsonEffectConfig["paths"].toArray();
const QJsonArray & disabledEfx = jsonEffectConfig["disable"].toArray();
QStringList efxPathList;
efxPathList << ":/effects/";
for (Json::UInt i = 0; i < paths.size(); ++i)
{
efxPathList << QString::fromStdString(paths[i].asString());
}
QStringList disableList;
for (Json::UInt i = 0; i < disabledEfx.size(); ++i)
{
disableList << QString::fromStdString(disabledEfx[i].asString());
QJsonArray::ConstIterator iterPaths = paths.begin();
QJsonArray::ConstIterator iterDisabledEfx = disabledEfx.begin();
for(; iterPaths != paths.end() and iterDisabledEfx != disabledEfx.end() ; ++iterPaths, ++iterDisabledEfx)
{
efxPathList << (*iterPaths).toString();
disableList << (*iterDisabledEfx).toString();
}
std::map<std::string, EffectDefinition> availableEffects;
std::map<QString, EffectDefinition> availableEffects;
foreach (const QString & path, efxPathList )
{
QDir directory(path);
@ -65,12 +65,12 @@ EffectEngine::EffectEngine(Hyperion * hyperion, const Json::Value & jsonEffectCo
{
if (availableEffects.find(def.name) != availableEffects.end())
{
Info(_log, "effect overload effect '%s' is now taken from %s'", def.name.c_str(), path.toUtf8().constData() );
Info(_log, "effect overload effect '%s' is now taken from %s'", def.name.toUtf8().constData(), path.toUtf8().constData() );
}
if ( disableList.contains(QString::fromStdString(def.name)) )
if ( disableList.contains(def.name) )
{
Info(_log, "effect '%s' not loaded, because it is disabled in hyperion config", def.name.c_str());
Info(_log, "effect '%s' not loaded, because it is disabled in hyperion config", def.name.toUtf8().constData());
}
else
{
@ -121,8 +121,8 @@ const std::list<ActiveEffectDefinition> &EffectEngine::getActiveEffects()
for (Effect * effect : _activeEffects)
{
ActiveEffectDefinition activeEffectDefinition;
activeEffectDefinition.script = effect->getScript().toStdString();
activeEffectDefinition.name = effect->getName().toStdString();
activeEffectDefinition.script = effect->getScript();
activeEffectDefinition.name = effect->getName();
activeEffectDefinition.priority = effect->getPriority();
activeEffectDefinition.timeout = effect->getTimeout();
activeEffectDefinition.args = effect->getArgs();
@ -134,67 +134,117 @@ const std::list<ActiveEffectDefinition> &EffectEngine::getActiveEffects()
bool EffectEngine::loadEffectDefinition(const QString &path, const QString &effectConfigFile, EffectDefinition & effectDefinition)
{
QString fileName = path + QDir::separator() + effectConfigFile;
QFile file(fileName);
Logger * log = Logger::getInstance("EFFECTENGINE");
QString fileName = path + QDir::separator() + effectConfigFile;
QJsonParseError error;
// ---------- Read the effect json config file ----------
QFile file(fileName);
if (!file.open(QIODevice::ReadOnly))
{
Error( log, "Effect file '%s' could not be loaded", fileName.toUtf8().constData());
return false;
}
QByteArray fileContent = file.readAll();
// Read the json config file
Json::Reader jsonReader;
Json::Value config;
const char* fileContent_cStr = reinterpret_cast<const char *>(fileContent.constData());
QJsonDocument configEffect = QJsonDocument::fromJson(fileContent, &error);
if (! Json::Reader().parse(fileContent_cStr, fileContent_cStr+fileContent.size(), config, false) )
if (error.error != QJsonParseError::NoError)
{
Error( log, "Error while reading effect '%s': %s", fileName.toUtf8().constData(), jsonReader.getFormattedErrorMessages().c_str());
// report to the user the failure and their locations in the document.
int errorLine(0), errorColumn(0);
for( int i=0, count=qMin( error.offset,fileContent.size()); i<count; ++i )
{
++errorColumn;
if(fileContent.at(i) == '\n' )
{
errorColumn = 0;
++errorLine;
}
}
Error( log, "Error while reading effect: '%s' at Line: '%i' , Column: %i", error.errorString().toUtf8().constData(), errorLine, errorColumn);
}
file.close();
// ---------- Read the effect json schema file ----------
Q_INIT_RESOURCE(EffectEngine);
QFile schema(":effect-schema");
if (!schema.open(QIODevice::ReadOnly))
{
Error( log, "Schema not found: %s", schema.errorString().toUtf8().constData());
return false;
}
file.close();
// Read the json schema file
QResource schemaData(":effect-schema");
JsonSchemaChecker schemaChecker;
Json::Value schema;
Json::Reader().parse(reinterpret_cast<const char *>(schemaData.data()), reinterpret_cast<const char *>(schemaData.data()) + schemaData.size(), schema, false);
schemaChecker.setSchema(schema);
if (!schemaChecker.validate(config))
QByteArray schemaContent = schema.readAll();
QJsonDocument configSchema = QJsonDocument::fromJson(schemaContent, &error);
if (error.error != QJsonParseError::NoError)
{
// report to the user the failure and their locations in the document.
int errorLine(0), errorColumn(0);
for( int i=0, count=qMin( error.offset,schemaContent.size()); i<count; ++i )
{
++errorColumn;
if(schemaContent.at(i) == '\n' )
{
errorColumn = 0;
++errorLine;
}
}
Error( log, "ERROR: Json schema wrong: '%s' at Line: '%i' , Column: %i", error.errorString().toUtf8().constData(), errorLine, errorColumn);
}
schema.close();
// ---------- validate effect config with effect schema ----------
QJsonSchemaChecker schemaChecker;
schemaChecker.setSchema(configSchema.object());
if (!schemaChecker.validate(configEffect.object()))
{
const std::list<std::string> & errors = schemaChecker.getMessages();
foreach (const std::string & error, errors) {
foreach (const std::string & error, errors)
{
Error( log, "Error while checking '%s':%s", fileName.toUtf8().constData(), error.c_str());
}
return false;
}
// setup the definition
std::string scriptName = config["script"].asString();
effectDefinition.name = config["name"].asString();
if (scriptName.empty())
// ---------- setup the definition ----------
QJsonObject config = configEffect.object();
QString scriptName = config["script"].toString();
effectDefinition.name = config["name"].toString();
if (scriptName.isEmpty())
return false;
if (scriptName[0] == ':' )
effectDefinition.script = ":/effects/"+scriptName.substr(1);
if (scriptName.mid(0, 1) == ":" )
effectDefinition.script = ":/effects/"+scriptName.mid(1);
else
effectDefinition.script = path.toStdString() + QDir::separator().toLatin1() + scriptName;
effectDefinition.script = path + QDir::separator().toLatin1() + scriptName;
effectDefinition.args = config["args"];
effectDefinition.args = config["args"].toObject();
return true;
}
int EffectEngine::runEffect(const std::string &effectName, int priority, int timeout)
int EffectEngine::runEffect(const QString &effectName, int priority, int timeout)
{
return runEffect(effectName, Json::Value(Json::nullValue), priority, timeout);
return runEffect(effectName, QJsonObject(), priority, timeout);
}
int EffectEngine::runEffect(const std::string &effectName, const Json::Value &args, int priority, int timeout)
int EffectEngine::runEffect(const QString &effectName, const QJsonObject &args, int priority, int timeout)
{
Info( _log, "run effect %s on channel %d", effectName.c_str(), priority);
Info( _log, "run effect %s on channel %d", effectName.toUtf8().constData(), priority);
const EffectDefinition * effectDefinition = nullptr;
for (const EffectDefinition & e : _availableEffects)
@ -208,26 +258,26 @@ int EffectEngine::runEffect(const std::string &effectName, const Json::Value &ar
if (effectDefinition == nullptr)
{
// no such effect
Error(_log, "effect %s not found", effectName.c_str());
Error(_log, "effect %s not found", effectName.toUtf8().constData());
return -1;
}
return runEffectScript(effectDefinition->script, effectName, args.isNull() ? effectDefinition->args : args, priority, timeout);
return runEffectScript(effectDefinition->script, effectName, args.isEmpty() ? effectDefinition->args : args, priority, timeout);
}
int EffectEngine::runEffectScript(const std::string &script, const std::string &name, const Json::Value &args, int priority, int timeout)
int EffectEngine::runEffectScript(const QString &script, const QString &name, const QJsonObject &args, int priority, int timeout)
{
// clear current effect on the channel
channelCleared(priority);
// create the effect
Effect * effect = new Effect(_mainThreadState, priority, timeout, QString::fromStdString(script), QString::fromStdString(name), args);
Effect * effect = new Effect(_mainThreadState, priority, timeout, script, name, args);
connect(effect, SIGNAL(setColors(int,std::vector<ColorRgb>,int,bool)), _hyperion, SLOT(setColors(int,std::vector<ColorRgb>,int,bool)), Qt::QueuedConnection);
connect(effect, SIGNAL(effectFinished(Effect*)), this, SLOT(effectFinished(Effect*)));
_activeEffects.push_back(effect);
// start the effect
_hyperion->registerPriority("EFFECT: "+name, priority);
_hyperion->registerPriority("EFFECT: "+name.toStdString(), priority);
effect->start();
return 0;

View File

@ -633,6 +633,7 @@ Hyperion::Hyperion(const Json::Value &jsonConfig, const QJsonObject &qjsonConfig
, _effectEngine(nullptr)
, _messageForwarder(createMessageForwarder(qjsonConfig["forwarder"].toObject()))
, _jsonConfig(jsonConfig)
, _qjsonConfig(qjsonConfig)
, _configFile(configFile)
, _timer()
, _log(Logger::getInstance("Core"))
@ -682,7 +683,7 @@ Hyperion::Hyperion(const Json::Value &jsonConfig, const QJsonObject &qjsonConfig
QObject::connect(&_timer, SIGNAL(timeout()), this, SLOT(update()));
// create the effect engine
_effectEngine = new EffectEngine(this,jsonConfig["effects"]);
_effectEngine = new EffectEngine(this,qjsonConfig["effects"].toObject());
const QJsonObject& device = qjsonConfig["device"].toObject();
unsigned int hwLedCount = device["ledCount"].toInt(getLedCount());
@ -938,12 +939,12 @@ const std::list<ActiveEffectDefinition> & Hyperion::getActiveEffects()
return _effectEngine->getActiveEffects();
}
int Hyperion::setEffect(const std::string &effectName, int priority, int timeout)
int Hyperion::setEffect(const QString &effectName, int priority, int timeout)
{
return _effectEngine->runEffect(effectName, priority, timeout);
}
int Hyperion::setEffect(const std::string &effectName, const Json::Value &args, int priority, int timeout)
int Hyperion::setEffect(const QString &effectName, const QJsonObject &args, int priority, int timeout)
{
return _effectEngine->runEffect(effectName, args, priority, timeout);
}

File diff suppressed because it is too large Load Diff

View File

@ -7,14 +7,11 @@
#include <QByteArray>
#include <QTcpSocket>
// jsoncpp includes
#include <json/json.h>
// Hyperion includes
#include <hyperion/Hyperion.h>
// util includes
#include <utils/jsonschema/JsonSchemaChecker.h>
#include <utils/jsonschema/QJsonSchemaChecker.h>
#include <utils/Logger.h>
#include <utils/Components.h>
@ -69,113 +66,113 @@ private:
///
/// @param message the incoming message as string
///
void handleMessage(const std::string & message);
void handleMessage(const QString & message);
///
/// Handle an incoming JSON Color message
///
/// @param message the incoming message
///
void handleColorCommand(const Json::Value & message, const std::string &command, const int tan);
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 Json::Value & message, const std::string &command, const int tan);
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 Json::Value & message, const std::string &command, const int tan);
void handleEffectCommand(const QJsonObject & message, const QString &command, const int tan);
///
/// Handle an incoming JSON Server info message
///
/// @param message the incoming message
///
void handleServerInfoCommand(const Json::Value & message, const std::string &command, const int tan);
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 Json::Value & message, const std::string &command, const int tan);
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 Json::Value & message, const std::string &command, const int tan);
void handleClearallCommand(const QJsonObject & message, const QString &command, const int tan);
///
/// Handle an incoming JSON Transform message
///
/// @param message the incoming message
///
void handleTransformCommand(const Json::Value & message, const std::string &command, const int tan);
void handleTransformCommand(const QJsonObject & message, const QString &command, const int tan);
///
/// Handle an incoming JSON Temperature message
///
/// @param message the incoming message
///
void handleTemperatureCommand(const Json::Value & message, const std::string &command, const int tan);
void handleTemperatureCommand(const QJsonObject & message, const QString &command, const int tan);
///
/// Handle an incoming JSON Adjustment message
///
/// @param message the incoming message
///
void handleAdjustmentCommand(const Json::Value & message, const std::string &command, const int tan);
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 Json::Value & message, const std::string &command, const int tan);
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 Json::Value & message, const std::string &command, const int tan);
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 Json::Value & message, const std::string &command, const int tan);
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 Json::Value & message, const std::string &command, const int tan);
void handleConfigGetCommand(const QJsonObject & message, const QString &command, const int tan);
///
/// Handle an incoming JSON SetConfig message
///
void handleConfigSetCommand(const Json::Value & message, const std::string &command, const int tan);
void handleConfigSetCommand(const QJsonObject & message, const QString &command, const int tan);
///
/// Handle an incoming JSON Component State message
///
/// @param message the incoming message
///
void handleComponentStateCommand(const Json::Value & message, const std::string &command, const int tan);
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 Json::Value & message, const std::string &command, const int tan);
void handleLedColorsCommand(const QJsonObject & message, const QString &command, const int tan);
///
/// Handle an incoming JSON message of unknown type
@ -187,20 +184,20 @@ private:
///
/// @param message The JSON message to send
///
void sendMessage(const Json::Value & message);
void sendMessage(const Json::Value & message, QTcpSocket * socket);
void sendMessage(const QJsonObject & message);
void sendMessage(const QJsonObject & message, QTcpSocket * socket);
///
/// Send a standard reply indicating success
///
void sendSuccessReply(const std::string &command="", const int tan=0);
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 std::string & error, const std::string &command="", const int tan=0);
void sendErrorReply(const QString & error, const QString &command="", const int tan=0);
///
/// Do handshake for a websocket connection
@ -215,7 +212,7 @@ private:
///
/// forward json message
///
void forwardJsonMessage(const Json::Value & message);
void forwardJsonMessage(const QJsonObject & message);
private:
///
@ -228,7 +225,7 @@ private:
///
/// @return true if message conforms the given JSON schema
///
bool checkJson(const Json::Value & message, const QString &schemaResource, std::string & errors, bool ignoreRequired = false);
bool checkJson(const QJsonObject & message, const QString &schemaResource, QString & errors, bool ignoreRequired = false);
/// The TCP-Socket that is connected tot the Json-client
QTcpSocket * _socket;
@ -254,6 +251,6 @@ private:
///
QTimer _timer_ledcolors;
Json::Value _streaming_leds_reply;
QJsonObject _streaming_leds_reply;
};

View File

@ -17,12 +17,6 @@
},
"config": {
"type" : "object"
},
"create": {
"type" : "boolean"
},
"overwrite": {
"type" : "boolean"
}
},
"additionalProperties": false

View File

@ -1,9 +1,12 @@
#include <leddevice/LedDevice.h>
#include <sstream>
//QT include
#include <QResource>
#include <QStringList>
#include <QDir>
#include <json/json.h>
#include <QJsonObject>
#include <QJsonDocument>
LedDeviceRegistry LedDevice::_ledDeviceMap = LedDeviceRegistry();
std::string LedDevice::_activeDevice = "";
@ -43,29 +46,57 @@ void LedDevice::setActiveDevice(std::string dev)
_activeDevice = dev;
}
Json::Value LedDevice::getLedDeviceSchemas()
QJsonObject LedDevice::getLedDeviceSchemas()
{
// make sure the resources are loaded (they may be left out after static linking)
Q_INIT_RESOURCE(LedDeviceSchemas);
QJsonParseError error;
// read the json schema from the resource
QDir d(":/leddevices/");
QStringList l = d.entryList();
Json::Value result;
QJsonObject result, schemaJson;
for(QString &item : l)
{
QResource schemaData(QString(":/leddevices/")+item);
std::string devName = item.remove("schema-").toStdString();
Json::Value & schemaJson = result[devName];
QFile schemaData(QString(":/leddevices/")+item);
QString devName = item.remove("schema-");
Json::Reader jsonReader;
if (!jsonReader.parse(reinterpret_cast<const char *>(schemaData.data()), reinterpret_cast<const char *>(schemaData.data()) + schemaData.size(), schemaJson, false))
if (!schemaData.open(QIODevice::ReadOnly))
{
Error(Logger::getInstance("LedDevice"), "LedDevice JSON schema error in %s (%s)", item.toUtf8().constData(), jsonReader.getFormattedErrorMessages().c_str() );
throw std::runtime_error("ERROR: Json schema wrong: " + jsonReader.getFormattedErrorMessages()) ;
Error(Logger::getInstance("LedDevice"), "Schema not found: %s", item.toUtf8().constData());
throw std::runtime_error("ERROR: Schema not found: " + item.toStdString());
}
schemaJson["title"] = "LED Device Specific";
QByteArray schema = schemaData.readAll();
QJsonDocument doc = QJsonDocument::fromJson(schema, &error);
schemaData.close();
if (error.error != QJsonParseError::NoError)
{
// report to the user the failure and their locations in the document.
int errorLine(0), errorColumn(0);
for( int i=0, count=qMin( error.offset,schema.size()); i<count; ++i )
{
++errorColumn;
if(schema.at(i) == '\n' )
{
errorColumn = 0;
++errorLine;
}
}
std::stringstream sstream;
sstream << error.errorString().toStdString() << " at Line: " << errorLine << ", Column: " << errorColumn;
Error(Logger::getInstance("LedDevice"), "LedDevice JSON schema error in %s (%s)", item.toUtf8().constData(), sstream.str().c_str());
throw std::runtime_error("ERROR: Json schema wrong: " + sstream.str());
}
schemaJson = doc.object();
schemaJson["title"] = QString("LED Device Specific");
result[devName] = schemaJson;
}
return result;

View File

@ -26,9 +26,10 @@ bool QJsonSchemaChecker::setSchema(const QJsonObject & schema)
return true;
}
bool QJsonSchemaChecker::validate(const QJsonObject & value)
bool QJsonSchemaChecker::validate(const QJsonObject & value, bool ignoreRequired)
{
// initialize state
_ignoreRequired = ignoreRequired;
_error = false;
_messages.clear();
_currentPath.clear();
@ -183,7 +184,7 @@ void QJsonSchemaChecker::checkProperties(const QJsonObject & value, const QJsonO
{
validate(value[property], propertyValue.toObject());
}
else if (required != propertyValue.toObject().end() && required.value().toBool())
else if (required != propertyValue.toObject().end() && required.value().toBool() && !_ignoreRequired)
{
_error = true;
setMessage("missing member");

View File

@ -266,15 +266,13 @@ QString JsonConnection::getConfig(std::string type)
return QString();
}
void JsonConnection::setConfig(const QString &jsonString, bool create, bool overwrite)
void JsonConnection::setConfig(const QString &jsonString)
{
// create command
Json::Value command;
command["command"] = "config";
command["subcommand"] = "setconfig";
command["create"] = create;
command["overwrite"] = overwrite;
Json::Value & config = command["config"];
if (jsonString.size() > 0)
{

View File

@ -111,7 +111,7 @@ public:
/// @param jsonString The JSON String(s) to write
/// @param create Specifies whether the nonexistent json string to be created
///
void setConfig(const QString &jsonString, bool create, bool overwrite);
void setConfig(const QString &jsonString);
///
/// Set the color transform of the leds

View File

@ -91,10 +91,8 @@ int main(int argc, char * argv[])
BooleanOption & argSourceAuto = parser.add<BooleanOption>(0x0, "sourceAutoSelect", "Enables auto source, if disabled prio by manual selecting input source");
BooleanOption & argSourceOff = parser.add<BooleanOption>(0x0, "sourceOff", "select no source, this results in leds activly set to black (=off)");
BooleanOption & argConfigGet = parser.add<BooleanOption>(0x0, "configGet" , "Print the current loaded Hyperion configuration file");
Option & argSchemaGet = parser.add<Option> (0x0, "schemaGet" , "Print the json schema for Hyperion configuration");
BooleanOption & argSchemaGet = parser.add<BooleanOption>(0x0, "schemaGet" , "Print the json schema for Hyperion configuration");
Option & argConfigSet = parser.add<Option> ('W', "configSet", "Write to the actual loaded configuration file. Should be a Json object string.");
Option & argCreate = parser.add<Option> (0x0, "createkeys", "Create non exist Json Entry(s) in the actual loaded configuration file. Argument to use in combination with configSet.");
Option & argOverwriteConfig = parser.add<Option> (0x0, "overwrite", "Overwrite the actual loaded configuration file with the Json object string from configSet. Argument to use in combination with configSet.");
// parse all _options
parser.process(app);
@ -111,7 +109,7 @@ int main(int argc, char * argv[])
bool colorModding = colorTransform || colorAdjust || parser.isSet(argCorrection) || parser.isSet(argTemperature);
// check that exactly one command was given
int commandCount = count({parser.isSet(argColor), parser.isSet(argImage), parser.isSet(argEffect), parser.isSet(argServerInfo), parser.isSet(argClear), parser.isSet(argClearAll), parser.isSet(argEnableComponent), parser.isSet(argDisableComponent), colorModding, parser.isSet(argSource), parser.isSet(argSourceAuto), parser.isSet(argSourceOff), parser.isSet(argConfigGet)});
int commandCount = count({parser.isSet(argColor), parser.isSet(argImage), parser.isSet(argEffect), parser.isSet(argServerInfo), parser.isSet(argClear), parser.isSet(argClearAll), parser.isSet(argEnableComponent), parser.isSet(argDisableComponent), colorModding, parser.isSet(argSource), parser.isSet(argSourceAuto), parser.isSet(argSourceOff), parser.isSet(argConfigGet), parser.isSet(argSchemaGet), parser.isSet(argConfigSet)});
if (commandCount != 1)
{
qWarning() << (commandCount == 0 ? "No command found." : "Multiple commands found.") << " Provide exactly one of the following options:";
@ -210,7 +208,7 @@ int main(int argc, char * argv[])
}
else if (parser.isSet(argConfigSet))
{
connection.setConfig(argConfigSet.value(parser), parser.isSet(argCreate), parser.isSet(argOverwriteConfig));
connection.setConfig(argConfigSet.value(parser));
}
else if (colorModding)
{

View File

@ -56,7 +56,7 @@ HyperionDaemon::HyperionDaemon(QString configFile, QObject *parent)
_hyperion = Hyperion::initInstance(_config, _qconfig, configFile.toStdString());
/*
if (Logger::getLogLevel() == Logger::WARNING)
{
if (_qconfig.contains("logger"))
@ -75,7 +75,7 @@ HyperionDaemon::HyperionDaemon(QString configFile, QObject *parent)
{
WarningIf(_qconfig.contains("logger"), Logger::getInstance("LOGGER"), "Logger settings overriden by command line argument");
}
*/
Info(_log, "Hyperion initialised");
}
@ -137,6 +137,7 @@ void HyperionDaemon::loadConfig(const QString & configFile)
QByteArray schema = schemaData.readAll();
QJsonDocument schemaJson = QJsonDocument::fromJson(schema, &error);
schemaData.close();
if (error.error != QJsonParseError::NoError)
{
@ -214,12 +215,12 @@ void HyperionDaemon::startInitialEffect()
}
else if (! fgEffectConfig.isNull() && fgEffectConfig.isArray() && FGCONFIG_ARRAY.size() == 1 && FGCONFIG_ARRAY.at(0).isString())
{
const std::string fgEffectName = FGCONFIG_ARRAY.at(0).toString().toStdString();
const QString fgEffectName = FGCONFIG_ARRAY.at(0).toString();
int result = effectConfig.contains("foreground-effect-args")
// ? hyperion->setEffect(fgEffectName, effectConfig["foreground-effect-args"], FG_PRIORITY, fg_duration_ms)
? hyperion->setEffect(fgEffectName, _config["initialEffect"]["foreground-effect-args"], FG_PRIORITY, fg_duration_ms)
? hyperion->setEffect(fgEffectName, _qconfig["initialEffect"].toObject()["foreground-effect-args"].toObject(), FG_PRIORITY, fg_duration_ms)
: hyperion->setEffect(fgEffectName, FG_PRIORITY, fg_duration_ms);
Info(_log,"Inital foreground effect '%s' %s", fgEffectName.c_str(), ((result == 0) ? "started" : "failed"));
Info(_log,"Inital foreground effect '%s' %s", fgEffectName.toUtf8().constData(), ((result == 0) ? "started" : "failed"));
}
// initial background effect/color
@ -236,12 +237,12 @@ void HyperionDaemon::startInitialEffect()
}
else if (! bgEffectConfig.isNull() && bgEffectConfig.isArray() && BGCONFIG_ARRAY.size() == 1 && BGCONFIG_ARRAY.at(0).isString())
{
const std::string bgEffectName = BGCONFIG_ARRAY.at(0).toString().toStdString();
const QString bgEffectName = BGCONFIG_ARRAY.at(0).toString();
int result = effectConfig.contains("background-effect-args")
// ? hyperion->setEffect(bgEffectName, effectConfig["background-effect-args"], BG_PRIORITY, fg_duration_ms)
? hyperion->setEffect(bgEffectName, _config["initialEffect"]["background-effect-args"], BG_PRIORITY, DURATION_INFINITY)
? hyperion->setEffect(bgEffectName, _qconfig["initialEffect"].toObject()["background-effect-args"].toObject(), BG_PRIORITY, DURATION_INFINITY)
: hyperion->setEffect(bgEffectName, BG_PRIORITY, DURATION_INFINITY);
Info(_log,"Inital background effect '%s' %s", bgEffectName.c_str(), ((result == 0) ? "started" : "failed"));
Info(_log,"Inital background effect '%s' %s", bgEffectName.toUtf8().constData(), ((result == 0) ? "started" : "failed"));
}
}