From d24abfe3d02bab2379916a9efb80877642a96870 Mon Sep 17 00:00:00 2001 From: Michael Zanetti Date: Tue, 18 Jun 2019 14:23:20 +0200 Subject: [PATCH] Move devicemanager's implementation out of libnymea into libnymea-core --- debian/libnymea1-dev.install.in | 2 +- doc/create-setupmethods.qdoc | 10 +- doc/tutorials/your-first-plugin.qdoc | 2 +- libnymea-core/cloud/cloudnotifications.cpp | 18 +- libnymea-core/cloud/cloudnotifications.h | 8 +- libnymea-core/debugserverhandler.cpp | 13 - .../devices/devicemanagerimplementation.cpp | 697 ++++------ .../devices/devicemanagerimplementation.h | 155 +++ .../{ => devices}/stateevaluator.cpp | 2 +- libnymea-core/{ => devices}/stateevaluator.h | 0 .../devices}/translator.cpp | 7 +- .../devices}/translator.h | 6 +- .../network/upnp/upnpdiscoveryrequest.h | 1 + libnymea-core/jsonrpc/actionhandler.cpp | 12 +- libnymea-core/jsonrpc/actionhandler.h | 6 +- libnymea-core/jsonrpc/devicehandler.cpp | 72 +- libnymea-core/jsonrpc/devicehandler.h | 8 +- libnymea-core/jsonrpc/eventhandler.cpp | 4 +- libnymea-core/jsonrpc/jsonhandler.cpp | 4 +- libnymea-core/jsonrpc/jsonhandler.h | 2 +- libnymea-core/jsonrpc/jsonrpcserver.cpp | 10 +- libnymea-core/jsonrpc/jsonrpcserver.h | 2 +- libnymea-core/jsonrpc/jsontypes.cpp | 25 +- libnymea-core/jsonrpc/jsontypes.h | 12 +- libnymea-core/jsonrpc/ruleshandler.cpp | 2 +- libnymea-core/jsonrpc/statehandler.cpp | 4 +- libnymea-core/libnymea-core.pro | 28 +- libnymea-core/logging/logengine.h | 2 +- libnymea-core/nymeacore.cpp | 124 +- libnymea-core/nymeacore.h | 29 +- libnymea-core/{ => ruleengine}/rule.cpp | 0 libnymea-core/{ => ruleengine}/rule.h | 2 +- libnymea-core/{ => ruleengine}/ruleengine.cpp | 4 +- libnymea-core/{ => ruleengine}/ruleengine.h | 2 +- .../servers/rest/deviceclassesresource.cpp | 24 +- .../servers/rest/deviceclassesresource.h | 4 +- .../servers/rest/devicesresource.cpp | 77 +- libnymea-core/servers/rest/devicesresource.h | 11 +- .../servers/rest/pluginsresource.cpp | 12 +- libnymea-core/servers/rest/restresource.cpp | 4 +- libnymea-core/servers/rest/restresource.h | 2 +- .../servers/rest/vendorsresource.cpp | 4 +- libnymea-core/tagging/tagsstorage.cpp | 4 +- .../pushbuttondbusservice.cpp | 0 .../{ => usermanager}/pushbuttondbusservice.h | 0 libnymea-core/{ => usermanager}/tokeninfo.cpp | 0 libnymea-core/{ => usermanager}/tokeninfo.h | 0 .../{ => usermanager}/usermanager.cpp | 0 libnymea-core/{ => usermanager}/usermanager.h | 0 libnymea/devicemanager.h | 211 --- libnymea/{plugin => devices}/device.cpp | 106 +- libnymea/{plugin => devices}/device.h | 54 +- .../{plugin => devices}/devicedescriptor.cpp | 0 .../{plugin => devices}/devicedescriptor.h | 0 libnymea/devices/devicemanager.cpp | 41 + libnymea/devices/devicemanager.h | 91 ++ .../{plugin => devices}/devicepairinginfo.cpp | 0 .../{plugin => devices}/devicepairinginfo.h | 0 libnymea/devices/deviceplugin.cpp | 380 ++++++ libnymea/{plugin => devices}/deviceplugin.h | 69 +- libnymea/devices/deviceutils.cpp | 307 +++++ libnymea/devices/deviceutils.h | 48 + .../nymea-generateplugininfo | 0 libnymea/{plugin => devices}/plugin.pri | 0 libnymea/devices/pluginmetadata.cpp | 687 ++++++++++ libnymea/devices/pluginmetadata.h | 66 + libnymea/libnymea.pro | 32 +- libnymea/loggingcategories.cpp | 1 + libnymea/loggingcategories.h | 1 + libnymea/network/upnp/upnpdiscovery.h | 1 - libnymea/plugin/deviceplugin.cpp | 1145 ----------------- libnymea/types/deviceclass.cpp | 33 +- libnymea/types/deviceclass.h | 11 +- libnymea/types/interface.h | 2 +- libnymea/types/param.cpp | 12 + libnymea/types/param.h | 2 + libnymea/types/paramtype.cpp | 5 +- libnymea/types/vendor.cpp | 20 + libnymea/types/vendor.h | 10 + plugins/mock/devicepluginmock.cpp | 123 +- plugins/mock/devicepluginmock.h | 12 +- plugins/mock/httpdaemon.cpp | 4 +- plugins/plugins.pri | 4 +- server/main.cpp | 3 +- tests/auto/actions/testactions.cpp | 30 +- tests/auto/devices/testdevices.cpp | 160 +-- tests/auto/events/testevents.cpp | 10 +- tests/auto/logging/testlogging.cpp | 6 +- .../testrestdeviceclasses.cpp | 72 +- tests/auto/restdevices/testrestdevices.cpp | 54 +- tests/auto/restlogging/testrestlogging.cpp | 4 +- tests/auto/restplugins/testrestplugins.cpp | 2 +- tests/auto/restvendors/testrestvendors.cpp | 2 +- tests/auto/rules/testrules.cpp | 14 +- tests/auto/states/teststates.cpp | 10 +- tests/auto/userloading/testuserloading.cpp | 2 +- tests/testlib/nymeatestbase.h | 2 +- 97 files changed, 2816 insertions(+), 2450 deletions(-) rename libnymea/devicemanager.cpp => libnymea-core/devices/devicemanagerimplementation.cpp (67%) create mode 100644 libnymea-core/devices/devicemanagerimplementation.h rename libnymea-core/{ => devices}/stateevaluator.cpp (99%) rename libnymea-core/{ => devices}/stateevaluator.h (100%) rename {libnymea => libnymea-core/devices}/translator.cpp (96%) rename {libnymea => libnymea-core/devices}/translator.h (93%) rename libnymea-core/{ => ruleengine}/rule.cpp (100%) rename libnymea-core/{ => ruleengine}/rule.h (98%) rename libnymea-core/{ => ruleengine}/ruleengine.cpp (99%) rename libnymea-core/{ => ruleengine}/ruleengine.h (99%) rename libnymea-core/{ => usermanager}/pushbuttondbusservice.cpp (100%) rename libnymea-core/{ => usermanager}/pushbuttondbusservice.h (100%) rename libnymea-core/{ => usermanager}/tokeninfo.cpp (100%) rename libnymea-core/{ => usermanager}/tokeninfo.h (100%) rename libnymea-core/{ => usermanager}/usermanager.cpp (100%) rename libnymea-core/{ => usermanager}/usermanager.h (100%) delete mode 100644 libnymea/devicemanager.h rename libnymea/{plugin => devices}/device.cpp (72%) rename libnymea/{plugin => devices}/device.h (71%) rename libnymea/{plugin => devices}/devicedescriptor.cpp (100%) rename libnymea/{plugin => devices}/devicedescriptor.h (100%) create mode 100644 libnymea/devices/devicemanager.cpp create mode 100644 libnymea/devices/devicemanager.h rename libnymea/{plugin => devices}/devicepairinginfo.cpp (100%) rename libnymea/{plugin => devices}/devicepairinginfo.h (100%) create mode 100644 libnymea/devices/deviceplugin.cpp rename libnymea/{plugin => devices}/deviceplugin.h (65%) create mode 100644 libnymea/devices/deviceutils.cpp create mode 100644 libnymea/devices/deviceutils.h rename libnymea/{plugin => devices}/nymea-generateplugininfo (100%) rename libnymea/{plugin => devices}/plugin.pri (100%) create mode 100644 libnymea/devices/pluginmetadata.cpp create mode 100644 libnymea/devices/pluginmetadata.h delete mode 100644 libnymea/plugin/deviceplugin.cpp diff --git a/debian/libnymea1-dev.install.in b/debian/libnymea1-dev.install.in index cb9b9625..77a19f61 100644 --- a/debian/libnymea1-dev.install.in +++ b/debian/libnymea1-dev.install.in @@ -1,5 +1,5 @@ usr/lib/@DEB_HOST_MULTIARCH@/libnymea.so usr/include/nymea/* usr/include/nymea usr/bin/nymea-generateplugininfo usr/bin -libnymea/plugin/plugin.pri usr/include/nymea/ +libnymea/devices/plugin.pri usr/include/nymea/ usr/lib/@DEB_HOST_MULTIARCH@/pkgconfig/nymea.pc diff --git a/doc/create-setupmethods.qdoc b/doc/create-setupmethods.qdoc index 541e8328..2c84af7e 100644 --- a/doc/create-setupmethods.qdoc +++ b/doc/create-setupmethods.qdoc @@ -91,7 +91,7 @@ \li \b Discovery \list \li \b 1. | The user started to discover devices. The method \l{DevicePlugin::discoverDevices()}{discoverDevices()} will be called in the plugin. - \li \b 2. | Return \l{DeviceManager::DeviceError}{DeviceErrorAsync} and start the discovery in the source code. + \li \b 2. | Return \l{Device::DeviceError}{DeviceErrorAsync} and start the discovery in the source code. \li \b 3. | Once the discovery is finished, the plugin can emit the signal \l{DevicePlugin::devicesDiscovered} to inform the \l{DeviceManager} about the result. \endlist \li \b Setup @@ -110,7 +110,7 @@ \li \b Discovery \list \li \b 1. | The user started to discover devices. The method \l{DevicePlugin::discoverDevices()}{discoverDevices()} will be called in the plugin. - \li \b 2. | Return \l{DeviceManager::DeviceError}{DeviceErrorAsync} and start the discovery in the source code. + \li \b 2. | Return \l{Device::DeviceError}{DeviceErrorAsync} and start the discovery in the source code. \li \b 3. | Once the discovery is finished, the plugin can emit the signal \l{DevicePlugin::devicesDiscovered} to inform the \l{DeviceManager} about the result. \endlist \li \b Pairing @@ -135,7 +135,7 @@ \li \b Discovery \list \li \b 1. | The user started to discover devices. The method \l{DevicePlugin::discoverDevices()}{discoverDevices()} will be called in the plugin. - \li \b 2. | Return \l{DeviceManager::DeviceError}{DeviceErrorAsync} and start the discovery in the source code. + \li \b 2. | Return \l{Device::DeviceError}{DeviceErrorAsync} and start the discovery in the source code. \li \b 3. | Once the discovery is finished, the plugin can emit the signal \l{DevicePlugin::devicesDiscovered} to inform the \l{DeviceManager} about the result. \endlist \li \b Pairing @@ -161,13 +161,13 @@ \li \b Discovery \list \li \b 1. | The user started to discover devices. The method \l{DevicePlugin::discoverDevices()}{discoverDevices()} will be called in the plugin. - \li \b 2. | Return \l{DeviceManager::DeviceError}{DeviceErrorAsync} and start the discovery in the source code. + \li \b 2. | Return \l{Device::DeviceError}{DeviceErrorAsync} and start the discovery in the source code. \li \b 3. | Once the discovery is finished, the plugin can emit the signal \l{DevicePlugin::devicesDiscovered} to inform the \l{DeviceManager} about the result. \endlist \li \b{Display pin} \list \li \b 4. | Once the user selected one of the discovered devices the device manager will call the method \l{DevicePlugin::displayPin()} in the plugin. Here can be sent the command to display the pin on the device. The pin which will be displayed on the device will be passed as secret in the \l{DevicePlugin::confirmPairing()} method. - \li \b 5. | Returns the \l{DeviceManager::DeviceError} to inform about the result (sync or async). + \li \b 5. | Returns the \l{Device::DeviceError} to inform about the result (sync or async). \endlist \li \b Pairing \list diff --git a/doc/tutorials/your-first-plugin.qdoc b/doc/tutorials/your-first-plugin.qdoc index 04f6d0a6..ed30d2a6 100644 --- a/doc/tutorials/your-first-plugin.qdoc +++ b/doc/tutorials/your-first-plugin.qdoc @@ -131,7 +131,7 @@ In order to implement this simple action and emit the Event once the button will be pressed, you need to implement following code: \quotefromfile simplebutton/devicepluginsimplebutton.cpp - \skipto DeviceManager::DeviceError DevicePluginSimpleButton::executeAction + \skipto Device::DeviceError DevicePluginSimpleButton::executeAction \printuntil }\n In this code section you can see the implementation of the \tt executeAction method for this example tutorial. The method diff --git a/libnymea-core/cloud/cloudnotifications.cpp b/libnymea-core/cloud/cloudnotifications.cpp index 696d9df0..7c3aba25 100644 --- a/libnymea-core/cloud/cloudnotifications.cpp +++ b/libnymea-core/cloud/cloudnotifications.cpp @@ -22,6 +22,7 @@ #include "loggingcategories.h" #include +#include DeviceClassId cloudNotificationsDeviceClassId = DeviceClassId("81c1bbcc-543a-48fd-bd18-ab6a76f9c38d"); ParamTypeId cloudNotificationsDeviceClassUserParamId = ParamTypeId("5bdeaf08-91a9-42bc-a9f9-ef6b02ecaa3c"); @@ -42,7 +43,7 @@ CloudNotifications::CloudNotifications(AWSConnector* awsConnector, QObject *pare connect(m_awsConnector, &AWSConnector::pushNotificationSent, this, &CloudNotifications::pushNotificationSent); } -QJsonObject CloudNotifications::metaData() const +PluginMetadata CloudNotifications::metaData() const { QVariantMap pluginMetaData; pluginMetaData.insert("id", "ccc6dbc8-e352-48a1-8e87-3c89a4669fc2"); @@ -132,13 +133,10 @@ QJsonObject CloudNotifications::metaData() const vendors.append(guhVendor); pluginMetaData.insert("vendors", vendors); - // Mark this plugin as built-in - pluginMetaData.insert("builtIn", true); - - return QJsonObject::fromVariantMap(pluginMetaData); + return PluginMetadata(QJsonObject::fromVariantMap(pluginMetaData), true); } -DeviceManager::DeviceSetupStatus CloudNotifications::setupDevice(Device *device) +Device::DeviceSetupStatus CloudNotifications::setupDevice(Device *device) { device->setStateValue(connectedStateTypeId, m_awsConnector->isConnected()); qCDebug(dcCloud) << "Cloud Notifications Device setup:" << device->name() << "Connected:" << m_awsConnector->isConnected(); @@ -148,21 +146,21 @@ DeviceManager::DeviceSetupStatus CloudNotifications::setupDevice(Device *device) connect(m_awsConnector, &AWSConnector::disconnected, device, [device]() { device->setStateValue(connectedStateTypeId, false); }); - return DeviceManager::DeviceSetupStatusSuccess; + return Device::DeviceSetupStatusSuccess; } void CloudNotifications::startMonitoringAutoDevices() { } -DeviceManager::DeviceError CloudNotifications::executeAction(Device *device, const Action &action) +Device::DeviceError CloudNotifications::executeAction(Device *device, const Action &action) { qCDebug(dcCloud()) << "executeAction" << device << action.id() << action.params(); QString userId = device->paramValue(cloudNotificationsDeviceClassUserParamId).toString(); QString endpointId = device->paramValue(cloudNotificationsDeviceClassEndpointParamId).toString(); int id = m_awsConnector->sendPushNotification(userId, endpointId, action.param(notifyActionParamTitleId).value().toString(), action.param(notifyActionParamBodyId).value().toString()); m_pendingPushNotifications.insert(id, action.id()); - return DeviceManager::DeviceErrorAsync; + return Device::DeviceErrorAsync; } void CloudNotifications::pushNotificationEndpointsUpdated(const QList &endpoints) @@ -238,5 +236,5 @@ void CloudNotifications::pushNotificationSent(int id, int status) { qCDebug(dcCloud()) << "Push notification sent" << id << status; ActionId actionId = m_pendingPushNotifications.value(id); - emit actionExecutionFinished(actionId, status == 200 ? DeviceManager::DeviceErrorNoError : DeviceManager::DeviceErrorHardwareNotAvailable); + emit actionExecutionFinished(actionId, status == 200 ? Device::DeviceErrorNoError : Device::DeviceErrorHardwareNotAvailable); } diff --git a/libnymea-core/cloud/cloudnotifications.h b/libnymea-core/cloud/cloudnotifications.h index e89a80b2..f22631ee 100644 --- a/libnymea-core/cloud/cloudnotifications.h +++ b/libnymea-core/cloud/cloudnotifications.h @@ -21,7 +21,7 @@ #ifndef CLOUDNOTIFICATIONS_H #define CLOUDNOTIFICATIONS_H -#include "plugin/deviceplugin.h" +#include "devices/deviceplugin.h" #include "awsconnector.h" class CloudNotifications : public DevicePlugin @@ -34,11 +34,11 @@ class CloudNotifications : public DevicePlugin public: CloudNotifications(AWSConnector *awsConnector, QObject* parent = nullptr); - QJsonObject metaData() const; + PluginMetadata metaData() const; - DeviceManager::DeviceSetupStatus setupDevice(Device *device) override; + Device::DeviceSetupStatus setupDevice(Device *device) override; void startMonitoringAutoDevices() override; - DeviceManager::DeviceError executeAction(Device *device, const Action &action) override; + Device::DeviceError executeAction(Device *device, const Action &action) override; private slots: void pushNotificationEndpointsUpdated(const QList &endpoints); diff --git a/libnymea-core/debugserverhandler.cpp b/libnymea-core/debugserverhandler.cpp index 77a357ef..a0402f8b 100644 --- a/libnymea-core/debugserverhandler.cpp +++ b/libnymea-core/debugserverhandler.cpp @@ -978,19 +978,6 @@ QByteArray DebugServerHandler::createDebugXmlDocument() writer.writeTextElement("td", NymeaSettings(NymeaSettings::SettingsRoleGlobal).translationsPath()); writer.writeEndElement(); // tr - for (int i = 0; i < NymeaCore::instance()->deviceManager()->pluginSearchDirs().count(); i++) { - writer.writeStartElement("tr"); - writer.writeEndElement(); // tr - - if (i == 0) { - //: The plugins path description in the server infromation section of the debug interface - writer.writeTextElement("th", tr("Plugin paths")); - } else { - writer.writeTextElement("th", ""); - } - writer.writeTextElement("td", QFileInfo(NymeaCore::instance()->deviceManager()->pluginSearchDirs().at(i)).absoluteFilePath()); - } - writer.writeEndElement(); // table // Generate report diff --git a/libnymea/devicemanager.cpp b/libnymea-core/devices/devicemanagerimplementation.cpp similarity index 67% rename from libnymea/devicemanager.cpp rename to libnymea-core/devices/devicemanagerimplementation.cpp index 3f973d61..5dc10f80 100644 --- a/libnymea/devicemanager.cpp +++ b/libnymea-core/devices/devicemanagerimplementation.cpp @@ -21,85 +21,6 @@ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ -/*! - \class DeviceManager - \brief The main entry point when interacting with \l{Device}{Devices} - - \ingroup devices - \inmodule libnymea - - The DeviceManager hold s all information about supported and configured Devices in the system. - - It is also responsible for loading Plugins and managing common hardware resources between - \l{DevicePlugin}{device plugins}. -*/ - - -/*! \enum DeviceManager::DeviceError - - This enum type specifies the errors that can happen when working with \l{Device}{Devices}. - - \value DeviceErrorNoError - No Error. Everything went fine. - \value DeviceErrorPluginNotFound - Couldn't find the Plugin for the given id. - \value DeviceErrorVendorNotFound - Couldn't find the Vendor for the given id. - \value DeviceErrorDeviceNotFound - Couldn't find a \l{Device} for the given id. - \value DeviceErrorDeviceClassNotFound - Couldn't find a \l{DeviceClass} for the given id. - \value DeviceErrorActionTypeNotFound - Couldn't find the \l{ActionType} for the given id. - \value DeviceErrorStateTypeNotFound - Couldn't find the \l{StateType} for the given id. - \value DeviceErrorEventTypeNotFound - Couldn't find the \l{EventType} for the given id. - \value DeviceErrorDeviceDescriptorNotFound - Couldn't find the \l{DeviceDescriptor} for the given id. - \value DeviceErrorMissingParameter - Parameters do not comply to the template. - \value DeviceErrorInvalidParameter - One of the given parameter is not valid. - \value DeviceErrorSetupFailed - Error setting up the \l{Device}. It will not be functional. - \value DeviceErrorDuplicateUuid - Error setting up the \l{Device}. The given DeviceId already exists. - \value DeviceErrorCreationMethodNotSupported - Error setting up the \l{Device}. This \l{DeviceClass}{CreateMethod} is not supported for this \l{Device}. - \value DeviceErrorSetupMethodNotSupported - Error setting up the \l{Device}. This \l{DeviceClass}{SetupMethod} is not supported for this \l{Device}. - \value DeviceErrorHardwareNotAvailable - The Hardware of the \l{Device} is not available. - \value DeviceErrorHardwareFailure - The Hardware of the \l{Device} has an error. - \value DeviceErrorAsync - The response of the \l{Device} will be asynchronously. - \value DeviceErrorDeviceInUse - The \l{Device} is currently bussy. - \value DeviceErrorPairingTransactionIdNotFound - Couldn't find the PairingTransactionId for the given id. - \value DeviceErrorAuthentificationFailure - The device could not authentificate with something. - \value DeviceErrorDeviceIsChild - The device is a child device and can not be deleted directly. - \value DeviceErrorDeviceInRule - The device is in a rule and can not be deleted withou \l{nymeaserver::RuleEngine::RemovePolicy}. - \value DeviceErrorParameterNotWritable - One of the given device params is not writable. -*/ - -/*! \enum DeviceManager::DeviceSetupStatus - - This enum type specifies the setup status of a \l{Device}. - - \value DeviceSetupStatusSuccess - No Error. Everything went fine. - \value DeviceSetupStatusFailure - Something went wrong during the setup. - \value DeviceSetupStatusAsync - The status of the \l{Device} setup will be emitted asynchronous. -*/ // Signals @@ -117,7 +38,7 @@ /*! \fn void DeviceManager::deviceSetupFinished(Device *device, DeviceError status); This signal is emitted when the setup of a \a device is finished. The \a status parameter describes the - \l{DeviceManager::DeviceError}{DeviceError} that occurred. + \l{Device::DeviceError}{DeviceError} that occurred. */ /*! \fn void DeviceManager::deviceStateChanged(Device *device, const QUuid &stateTypeId, const QVariant &value); @@ -147,7 +68,7 @@ /*! \fn void DeviceManager::deviceReconfigurationFinished(Device *device, DeviceError status); This signal is emitted when the edit process of a \a device is finished. The \a status parameter describes the - \l{DeviceManager::DeviceError}{DeviceError} that occurred. + \l{Device::DeviceError}{DeviceError} that occurred. */ /*! \fn void DeviceManager::devicesDiscovered(const DeviceClassId &deviceClassId, const QList &devices); @@ -158,12 +79,12 @@ /*! \fn void DeviceManager::actionExecutionFinished(const ActionId &actionId, DeviceError status); The DeviceManager will emit a this signal when the \l{Action} with the given \a actionId is finished. - The \a status of the \l{Action} execution will be described as \l{DeviceManager::DeviceError}{DeviceError}. + The \a status of the \l{Action} execution will be described as \l{Device::DeviceError}{DeviceError}. */ /*! \fn void DeviceManager::pairingFinished(const PairingTransactionId &pairingTransactionId, DeviceError status, const DeviceId &deviceId = DeviceId()); The DeviceManager will emit a this signal when the pairing of a \l{Device} with the \a deviceId and \a pairingTransactionId is finished. - The \a status of the pairing will be described as \l{DeviceManager::DeviceError}{DeviceError}. + The \a status of the pairing will be described as \l{Device::DeviceError}{DeviceError}. */ /*! \fn void DeviceManager::eventTriggered(const Event &event) @@ -173,15 +94,18 @@ or similar, but you should never directly react to this in a \l{DevicePlugin}. */ -#include "devicemanager.h" -#include "loggingcategories.h" +#include "devicemanagerimplementation.h" +#include "translator.h" -#include "plugin/devicepairinginfo.h" -#include "plugin/deviceplugin.h" +#include "loggingcategories.h" #include "typeutils.h" #include "nymeasettings.h" -#include "unistd.h" -#include "translator.h" + +#include "devices/devicepairinginfo.h" +#include "devices/deviceplugin.h" +#include "devices/deviceutils.h" + +//#include "unistd.h" #include "plugintimer.h" @@ -196,8 +120,8 @@ /*! Constructs the DeviceManager with the given \a{hardwareManager}, \a locale and \a parent. There should only be one DeviceManager in the system created by \l{nymeaserver::NymeaCore}. * Use \c nymeaserver::NymeaCore::instance()->deviceManager() instead to access the DeviceManager. */ -DeviceManager::DeviceManager(HardwareManager *hardwareManager, const QLocale &locale, QObject *parent) : - QObject(parent), +DeviceManagerImplementation::DeviceManagerImplementation(HardwareManager *hardwareManager, const QLocale &locale, QObject *parent) : + DeviceManager(parent), m_hardwareManager(hardwareManager), m_locale(locale), m_translator(new Translator(this)) @@ -205,7 +129,7 @@ DeviceManager::DeviceManager(HardwareManager *hardwareManager, const QLocale &lo qRegisterMetaType(); qRegisterMetaType(); - foreach (const Interface &interface, DevicePlugin::allInterfaces()) { + foreach (const Interface &interface, DeviceUtils::allInterfaces()) { m_supportedInterfaces.insert(interface.name(), interface); } @@ -218,8 +142,8 @@ DeviceManager::DeviceManager(HardwareManager *hardwareManager, const QLocale &lo QMetaObject::invokeMethod(this, "onLoaded", Qt::QueuedConnection); } -/*! Destructor of the DeviceManager. Each loaded \l{DevicePlugin} will be deleted. */ -DeviceManager::~DeviceManager() +/*! Destructor of the DeviceManagerImplementation. Each loaded \l{DevicePlugin} will be deleted. */ +DeviceManagerImplementation::~DeviceManagerImplementation() { delete m_translator; @@ -238,7 +162,7 @@ DeviceManager::~DeviceManager() } /*! Returns the list of search direcorys where \l{DevicePlugin} will be searched. */ -QStringList DeviceManager::pluginSearchDirs() +QStringList DeviceManagerImplementation::pluginSearchDirs() { QStringList searchDirs; QByteArray envPath = qgetenv("NYMEA_PLUGINS_PATH"); @@ -256,7 +180,7 @@ QStringList DeviceManager::pluginSearchDirs() } /*! Returns the list of json objects containing the metadata of the installed plugins. */ -QList DeviceManager::pluginsMetadata() +QList DeviceManagerImplementation::pluginsMetadata() { QList pluginList; foreach (const QString &path, pluginSearchDirs()) { @@ -279,56 +203,39 @@ QList DeviceManager::pluginsMetadata() } /*! Register a DevicePlugin class. This can be used to create devices internally from the guh system without having to create a full plugin. - The \a metaData contains the static plugin configurations. The DeviceManager takes ownership of the object \a plugin and will clean it up when exiting. Do not delete the object yourself. */ -void DeviceManager::registerStaticPlugin(DevicePlugin *plugin, const QJsonObject &metaData) + The \a metaData contains the static plugin configurations. The DeviceManagerImplementation takes ownership of the object \a plugin and will clean it up when exiting. Do not delete the object yourself. */ +void DeviceManagerImplementation::registerStaticPlugin(DevicePlugin *plugin, const PluginMetadata &metaData) { - if (!verifyPluginMetadata(metaData)) { - qCWarning(dcDeviceManager()) << "Failed to verify plugin metadata. Not loading static plugin:" << plugin->pluginName(); + if (!metaData.isValid()) { + qCWarning(dcDeviceManager()) << "Plugin metadata not valid. Not loading static plugin:" << plugin->pluginName(); return; } - plugin->setParent(this); - plugin->setMetaData(metaData); - loadPlugin(plugin); -} - -/*! Returns the pointer to the \l{HardwareManager} of the system. - - \sa HardwareManager -*/ -HardwareManager *DeviceManager::hardwareManager() const -{ - return m_hardwareManager; + loadPlugin(plugin, metaData); } /*! Returns all the \l{DevicePlugin}{DevicePlugins} loaded in the system. */ -QList DeviceManager::plugins() const +DevicePlugins DeviceManagerImplementation::plugins() const { return m_devicePlugins.values(); } -/*! Returns the \l{DevicePlugin} with the given \a id. Null if the id couldn't be found. */ -DevicePlugin *DeviceManager::plugin(const PluginId &id) const -{ - return m_devicePlugins.value(id); -} - /*! Returns a certain \l{DeviceError} and sets the configuration of the plugin with the given \a pluginId * and the given \a pluginConfig. */ -DeviceManager::DeviceError DeviceManager::setPluginConfig(const PluginId &pluginId, const ParamList &pluginConfig) +Device::DeviceError DeviceManagerImplementation::setPluginConfig(const PluginId &pluginId, const ParamList &pluginConfig) { DevicePlugin *plugin = m_devicePlugins.value(pluginId); if (!plugin) { qCWarning(dcDeviceManager()) << "Could not set plugin configuration. There is no plugin with id" << pluginId.toString(); - return DeviceErrorPluginNotFound; + return Device::DeviceErrorPluginNotFound; } ParamList params = pluginConfig; - DeviceError verify = verifyParams(plugin->configurationDescription(), params); - if (verify != DeviceErrorNoError) + Device::DeviceError verify = DeviceUtils::verifyParams(plugin->configurationDescription(), params); + if (verify != Device::DeviceErrorNoError) return verify; - DeviceError result = plugin->setConfiguration(params); - if (result != DeviceErrorNoError) + Device::DeviceError result = plugin->setConfiguration(params); + if (result != Device::DeviceErrorNoError) return result; NymeaSettings settings(NymeaSettings::SettingsRolePlugins); @@ -349,26 +256,20 @@ DeviceManager::DeviceError DeviceManager::setPluginConfig(const PluginId &plugin } /*! Returns all the \l{Vendor}s loaded in the system. */ -QList DeviceManager::supportedVendors() const +Vendors DeviceManagerImplementation::supportedVendors() const { return m_supportedVendors.values(); } /*! Returns the list of all supported \l{Interfaces for DeviceClasses}{interfaces}. */ -Interfaces DeviceManager::supportedInterfaces() const +Interfaces DeviceManagerImplementation::supportedInterfaces() const { return m_supportedInterfaces.values(); } -/*! Returns the interface with the given \a name. If the interface can't be found it will return an invalid interface. */ -Interface DeviceManager::findInterface(const QString &name) -{ - return m_supportedInterfaces.value(name); -} - /*! Returns all the supported \l{DeviceClass}{DeviceClasses} by all \l{DevicePlugin}{DevicePlugins} loaded in the system. * Optionally filtered by \a vendorId. */ -QList DeviceManager::supportedDevices(const VendorId &vendorId) const +DeviceClasses DeviceManagerImplementation::supportedDevices(const VendorId &vendorId) const { if (vendorId.isNull()) { return m_supportedDevices.values(); @@ -384,29 +285,29 @@ QList DeviceManager::supportedDevices(const VendorId &vendorId) con } /*! Returns a certain \l{DeviceError} and starts the discovering process of the \l{Device} with the given \a deviceClassId * and the given \a params.*/ -DeviceManager::DeviceError DeviceManager::discoverDevices(const DeviceClassId &deviceClassId, const ParamList ¶ms) +Device::DeviceError DeviceManagerImplementation::discoverDevices(const DeviceClassId &deviceClassId, const ParamList ¶ms) { qCDebug(dcDeviceManager) << "discover devices" << params; // Create a copy of the parameter list because we might modify it (fillig in default values etc) ParamList effectiveParams = params; DeviceClass deviceClass = findDeviceClass(deviceClassId); if (!deviceClass.isValid()) { - return DeviceErrorDeviceClassNotFound; + return Device::DeviceErrorDeviceClassNotFound; } if (!deviceClass.createMethods().testFlag(DeviceClass::CreateMethodDiscovery)) { - return DeviceErrorCreationMethodNotSupported; + return Device::DeviceErrorCreationMethodNotSupported; } - DeviceError result = verifyParams(deviceClass.discoveryParamTypes(), effectiveParams); - if (result != DeviceErrorNoError) { + Device::DeviceError result = DeviceUtils::verifyParams(deviceClass.discoveryParamTypes(), effectiveParams); + if (result != Device::DeviceErrorNoError) { return result; } DevicePlugin *plugin = m_devicePlugins.value(deviceClass.pluginId()); if (!plugin) { - return DeviceErrorPluginNotFound; + return Device::DeviceErrorPluginNotFound; } m_discoveringPlugins.append(plugin); - DeviceError ret = plugin->discoverDevices(deviceClassId, effectiveParams); - if (ret != DeviceErrorAsync) { + Device::DeviceError ret = plugin->discoverDevices(deviceClassId, effectiveParams); + if (ret != Device::DeviceErrorAsync) { m_discoveringPlugins.removeOne(plugin); } return ret; @@ -417,16 +318,16 @@ DeviceManager::DeviceError DeviceManager::discoverDevices(const DeviceClassId &d * Optionally you can supply an id yourself if you must keep track of the added device. If you don't supply it, a new one will * be generated. Only devices with \l{DeviceClass}{CreateMethodUser} can be created using this method. * Returns \l{DeviceError} to inform about the result. */ -DeviceManager::DeviceError DeviceManager::addConfiguredDevice(const DeviceClassId &deviceClassId, const QString &name, const ParamList ¶ms, const DeviceId id) +Device::DeviceError DeviceManagerImplementation::addConfiguredDevice(const DeviceClassId &deviceClassId, const QString &name, const ParamList ¶ms, const DeviceId id) { DeviceClass deviceClass = findDeviceClass(deviceClassId); if (!deviceClass.isValid()) { - return DeviceErrorDeviceClassNotFound; + return Device::DeviceErrorDeviceClassNotFound; } if (deviceClass.createMethods().testFlag(DeviceClass::CreateMethodUser)) { return addConfiguredDeviceInternal(deviceClassId, name, params, id); } - return DeviceErrorCreationMethodNotSupported; + return Device::DeviceErrorCreationMethodNotSupported; } /*! Add a new configured device for the given \l{DeviceClass} the given DeviceDescriptorId and \a deviceId. Only devices with \l{DeviceClass}{CreateMethodDiscovery} @@ -435,19 +336,19 @@ DeviceManager::DeviceError DeviceManager::addConfiguredDevice(const DeviceClassI * are used but can be overridden here. * * Returns \l{DeviceError} to inform about the result. */ -DeviceManager::DeviceError DeviceManager::addConfiguredDevice(const DeviceClassId &deviceClassId, const QString &name, const DeviceDescriptorId &deviceDescriptorId, const ParamList ¶ms, const DeviceId &deviceId) +Device::DeviceError DeviceManagerImplementation::addConfiguredDevice(const DeviceClassId &deviceClassId, const QString &name, const DeviceDescriptorId &deviceDescriptorId, const ParamList ¶ms, const DeviceId &deviceId) { DeviceClass deviceClass = findDeviceClass(deviceClassId); if (!deviceClass.isValid()) { - return DeviceErrorDeviceClassNotFound; + return Device::DeviceErrorDeviceClassNotFound; } if (!deviceClass.createMethods().testFlag(DeviceClass::CreateMethodDiscovery)) { - return DeviceErrorCreationMethodNotSupported; + return Device::DeviceErrorCreationMethodNotSupported; } DeviceDescriptor descriptor = m_discoveredDevices.take(deviceDescriptorId); if (!descriptor.isValid()) { - return DeviceErrorDeviceDescriptorNotFound; + return Device::DeviceErrorDeviceDescriptorNotFound; } // Merge params from discovered descriptor and additional overrides provided on API call. User provided params have higher priority than discovery params. @@ -469,25 +370,25 @@ DeviceManager::DeviceError DeviceManager::addConfiguredDevice(const DeviceClassI * from a discovery or if the user set them. If it came from discovery not writable parameters (readOnly) will be changed too. * * Returns \l{DeviceError} to inform about the result. */ -DeviceManager::DeviceError DeviceManager::reconfigureDevice(const DeviceId &deviceId, const ParamList ¶ms, bool fromDiscoveryOrAuto) +Device::DeviceError DeviceManagerImplementation::reconfigureDevice(const DeviceId &deviceId, const ParamList ¶ms, bool fromDiscoveryOrAuto) { Device *device = findConfiguredDevice(deviceId); if (!device) { qCWarning(dcDeviceManager()) << "Cannot reconfigure device. Device with id" << deviceId.toString() << "not found."; - return DeviceErrorDeviceNotFound; + return Device::DeviceErrorDeviceNotFound; } ParamList effectiveParams = params; DeviceClass deviceClass = findDeviceClass(device->deviceClassId()); if (deviceClass.id().isNull()) { qCWarning(dcDeviceManager()) << "Cannot reconfigure device. DeviceClass for device" << device->name() << deviceId.toString() << "not found."; - return DeviceErrorDeviceClassNotFound; + return Device::DeviceErrorDeviceClassNotFound; } DevicePlugin *plugin = m_devicePlugins.value(deviceClass.pluginId()); if (!plugin) { qCWarning(dcDeviceManager()) << "Cannot reconfigure device. Plugin for DeviceClass" << deviceClass.displayName() << deviceClass.id().toString() << "not found."; - return DeviceErrorPluginNotFound; + return Device::DeviceErrorPluginNotFound; } // if the params are discovered and not set by the user @@ -498,15 +399,15 @@ DeviceManager::DeviceError DeviceManager::reconfigureDevice(const DeviceId &devi if (paramType.id() == param.paramTypeId()) { if (paramType.readOnly()) { qCWarning(dcDeviceManager()) << "Cannot reconfigure device. Read-only parameters set by user."; - return DeviceErrorParameterNotWritable; + return Device::DeviceErrorParameterNotWritable; } } } } } - DeviceError result = verifyParams(deviceClass.paramTypes(), effectiveParams, false); - if (result != DeviceErrorNoError) { + Device::DeviceError result = DeviceUtils::verifyParams(deviceClass.paramTypes(), effectiveParams, false); + if (result != Device::DeviceErrorNoError) { qCWarning(dcDeviceManager()) << "Cannot reconfigure device. Params failed validation."; return result; } @@ -523,15 +424,15 @@ DeviceManager::DeviceError DeviceManager::reconfigureDevice(const DeviceId &devi } // try to setup the device with the new params - DeviceSetupStatus status = plugin->setupDevice(device); + Device::DeviceSetupStatus status = plugin->setupDevice(device); switch (status) { - case DeviceSetupStatusFailure: + case Device::DeviceSetupStatusFailure: qCWarning(dcDeviceManager) << "Device reconfiguration failed. Not saving changes of device parameters. Device setup incomplete."; - return DeviceErrorSetupFailed; - case DeviceSetupStatusAsync: + return Device::DeviceErrorSetupFailed; + case Device::DeviceSetupStatusAsync: m_asyncDeviceReconfiguration.append(device); - return DeviceErrorAsync; - case DeviceSetupStatusSuccess: + return Device::DeviceErrorAsync; + case Device::DeviceSetupStatusSuccess: qCDebug(dcDeviceManager) << "Device reconfiguration succeeded."; break; } @@ -541,7 +442,7 @@ DeviceManager::DeviceError DeviceManager::reconfigureDevice(const DeviceId &devi device->setupCompleted(); emit deviceChanged(device); - return DeviceErrorNoError; + return Device::DeviceErrorNoError; } /*! Edit the \l{Param}{Params} of a configured device to the \l{Param}{Params} of the DeviceDescriptor with the @@ -551,72 +452,72 @@ DeviceManager::DeviceError DeviceManager::reconfigureDevice(const DeviceId &devi * This method allows to rediscover a device and update it's \l{Param}{Params}. * * Returns \l{DeviceError} to inform about the result. */ -DeviceManager::DeviceError DeviceManager::reconfigureDevice(const DeviceId &deviceId, const DeviceDescriptorId &deviceDescriptorId) +Device::DeviceError DeviceManagerImplementation::reconfigureDevice(const DeviceId &deviceId, const DeviceDescriptorId &deviceDescriptorId) { Device *device = findConfiguredDevice(deviceId); if (!device) { - return DeviceErrorDeviceNotFound; + return Device::DeviceErrorDeviceNotFound; } DeviceClass deviceClass = findDeviceClass(device->deviceClassId()); if (!deviceClass.isValid()) { - return DeviceErrorDeviceClassNotFound; + return Device::DeviceErrorDeviceClassNotFound; } if (!deviceClass.createMethods().testFlag(DeviceClass::CreateMethodDiscovery)) { - return DeviceErrorCreationMethodNotSupported; + return Device::DeviceErrorCreationMethodNotSupported; } DeviceDescriptor descriptor = m_discoveredDevices.take(deviceDescriptorId); if (!descriptor.isValid()) { - return DeviceErrorDeviceDescriptorNotFound; + return Device::DeviceErrorDeviceDescriptorNotFound; } return reconfigureDevice(deviceId, descriptor.params(), true); } /*! Edit the \a name of the \l{Device} with the given \a deviceId. - Returns \l{DeviceManager::DeviceError}{DeviceError} to inform about the result. + Returns \l{Device::DeviceError}{DeviceError} to inform about the result. */ -DeviceManager::DeviceError DeviceManager::editDevice(const DeviceId &deviceId, const QString &name) +Device::DeviceError DeviceManagerImplementation::editDevice(const DeviceId &deviceId, const QString &name) { Device *device = findConfiguredDevice(deviceId); if (!device) - return DeviceErrorDeviceNotFound; + return Device::DeviceErrorDeviceNotFound; device->setName(name); storeConfiguredDevices(); emit deviceChanged(device); - return DeviceErrorNoError; + return Device::DeviceErrorNoError; } -DeviceManager::DeviceError DeviceManager::setDeviceSettings(const DeviceId &deviceId, const ParamList &settings) +Device::DeviceError DeviceManagerImplementation::setDeviceSettings(const DeviceId &deviceId, const ParamList &settings) { Device *device = findConfiguredDevice(deviceId); if (!device) { qCWarning(dcDeviceManager()) << "Cannot set device settings. Device" << deviceId.toString() << "not found"; - return DeviceErrorDeviceNotFound; + return Device::DeviceErrorDeviceNotFound; } ParamList effectiveSettings = settings; - DeviceManager::DeviceError status = verifyParams(findDeviceClass(device->deviceClassId()).settingsTypes(), effectiveSettings); - if (status != DeviceManager::DeviceErrorNoError) { + Device::DeviceError status = DeviceUtils::verifyParams(findDeviceClass(device->deviceClassId()).settingsTypes(), effectiveSettings); + if (status != Device::DeviceErrorNoError) { qCWarning(dcDeviceManager()) << "Error setting device settings for device" << device->name() << device->id().toString(); return status; } foreach (const Param &setting, settings) { device->setSettingValue(setting.paramTypeId(), setting.value()); } - return DeviceErrorNoError; + return Device::DeviceErrorNoError; } /*! Initiates a pairing with a \l{DeviceClass}{Device} with the given \a pairingTransactionId, \a deviceClassId, \a name and \a params. - * Returns \l{DeviceManager::DeviceError}{DeviceError} to inform about the result. */ -DeviceManager::DeviceError DeviceManager::pairDevice(const PairingTransactionId &pairingTransactionId, const DeviceClassId &deviceClassId, const QString &name, const ParamList ¶ms) + * Returns \l{Device::DeviceError}{DeviceError} to inform about the result. */ +Device::DeviceError DeviceManagerImplementation::pairDevice(const PairingTransactionId &pairingTransactionId, const DeviceClassId &deviceClassId, const QString &name, const ParamList ¶ms) { DeviceClass deviceClass = findDeviceClass(deviceClassId); if (deviceClass.id().isNull()) { qCWarning(dcDeviceManager) << "Cannot find a device class with id" << deviceClassId; - return DeviceErrorDeviceClassNotFound; + return Device::DeviceErrorDeviceClassNotFound; } Q_UNUSED(pairingTransactionId) @@ -625,39 +526,39 @@ DeviceManager::DeviceError DeviceManager::pairDevice(const PairingTransactionId switch (deviceClass.setupMethod()) { case DeviceClass::SetupMethodJustAdd: qCWarning(dcDeviceManager) << "Cannot setup this device this way. No need to pair this device."; - return DeviceErrorSetupMethodNotSupported; + return Device::DeviceErrorSetupMethodNotSupported; case DeviceClass::SetupMethodDisplayPin: qCWarning(dcDeviceManager) << "SetupMethodDisplayPin not implemented yet for this CreateMethod"; - return DeviceErrorSetupFailed; + return Device::DeviceErrorSetupFailed; case DeviceClass::SetupMethodEnterPin: qCWarning(dcDeviceManager) << "SetupMethodEnterPin not implemented yet for this CreateMethod"; - return DeviceErrorSetupFailed; + return Device::DeviceErrorSetupFailed; case DeviceClass::SetupMethodPushButton: qCWarning(dcDeviceManager) << "SetupMethodPushButton not implemented yet for this CreateMethod"; - return DeviceErrorSetupFailed; + return Device::DeviceErrorSetupFailed; } - return DeviceErrorNoError; + return Device::DeviceErrorNoError; } /*! Initiates a pairing with a \l{DeviceClass}{Device} with the given \a pairingTransactionId, \a deviceClassId, \a name and \a deviceDescriptorId. - * Returns \l{DeviceManager::DeviceError}{DeviceError} to inform about the result. */ -DeviceManager::DeviceError DeviceManager::pairDevice(const PairingTransactionId &pairingTransactionId, const DeviceClassId &deviceClassId, const QString &name, const DeviceDescriptorId &deviceDescriptorId) + * Returns \l{Device::DeviceError}{DeviceError} to inform about the result. */ +Device::DeviceError DeviceManagerImplementation::pairDevice(const PairingTransactionId &pairingTransactionId, const DeviceClassId &deviceClassId, const QString &name, const DeviceDescriptorId &deviceDescriptorId) { DeviceClass deviceClass = findDeviceClass(deviceClassId); if (deviceClass.id().isNull()) { qCWarning(dcDeviceManager) << "Cannot find a device class with id" << deviceClassId; - return DeviceErrorDeviceClassNotFound; + return Device::DeviceErrorDeviceClassNotFound; } if (deviceClass.setupMethod() == DeviceClass::SetupMethodJustAdd) { qCWarning(dcDeviceManager) << "Cannot setup this device this way. No need to pair this device."; - return DeviceErrorCreationMethodNotSupported; + return Device::DeviceErrorCreationMethodNotSupported; } if (!m_discoveredDevices.contains(deviceDescriptorId)) { qCWarning(dcDeviceManager) << "Cannot find a DeviceDescriptor with ID" << deviceClassId.toString(); - return DeviceErrorDeviceDescriptorNotFound; + return Device::DeviceErrorDeviceDescriptorNotFound; } m_pairingsDiscovery.insert(pairingTransactionId, DevicePairingInfo(deviceClassId, name, deviceDescriptorId)); @@ -668,23 +569,23 @@ DeviceManager::DeviceError DeviceManager::pairDevice(const PairingTransactionId DevicePlugin *plugin = m_devicePlugins.value(m_supportedDevices.value(deviceClassId).pluginId()); if (!plugin) { qCWarning(dcDeviceManager()) << "Can't find a plugin for this device class"; - return DeviceErrorPluginNotFound; + return Device::DeviceErrorPluginNotFound; } return plugin->displayPin(pairingTransactionId, deviceDescriptor); } - return DeviceErrorNoError; + return Device::DeviceErrorNoError; } /*! Confirms the pairing of a \l{Device} with the given \a pairingTransactionId and \a secret. - * Returns \l{DeviceManager::DeviceError}{DeviceError} to inform about the result. */ -DeviceManager::DeviceError DeviceManager::confirmPairing(const PairingTransactionId &pairingTransactionId, const QString &secret) + * Returns \l{Device::DeviceError}{DeviceError} to inform about the result. */ +Device::DeviceError DeviceManagerImplementation::confirmPairing(const PairingTransactionId &pairingTransactionId, const QString &secret) { if (m_pairingsJustAdd.contains(pairingTransactionId)) { qCWarning(dcDeviceManager) << "This SetupMethod is not implemented yet"; m_pairingsJustAdd.remove(pairingTransactionId); - return DeviceErrorSetupFailed; + return Device::DeviceErrorSetupFailed; } if (m_pairingsDiscovery.contains(pairingTransactionId)) { @@ -696,57 +597,57 @@ DeviceManager::DeviceError DeviceManager::confirmPairing(const PairingTransactio if (!plugin) { qCWarning(dcDeviceManager) << "Can't find a plugin for this device class"; - return DeviceErrorPluginNotFound; + return Device::DeviceErrorPluginNotFound; } - DeviceSetupStatus status = plugin->confirmPairing(pairingTransactionId, deviceClassId, deviceDescriptor.params(), secret); + Device::DeviceSetupStatus status = plugin->confirmPairing(pairingTransactionId, deviceClassId, deviceDescriptor.params(), secret); switch (status) { - case DeviceSetupStatusSuccess: + case Device::DeviceSetupStatusSuccess: m_pairingsDiscovery.remove(pairingTransactionId); // TODO: setup the device if the pairing status can be fetched directly - return DeviceErrorNoError; - case DeviceSetupStatusFailure: + return Device::DeviceErrorNoError; + case Device::DeviceSetupStatusFailure: m_pairingsDiscovery.remove(pairingTransactionId); - return DeviceErrorSetupFailed; - case DeviceSetupStatusAsync: - return DeviceErrorAsync; + return Device::DeviceErrorSetupFailed; + case Device::DeviceSetupStatusAsync: + return Device::DeviceErrorAsync; } } - return DeviceErrorPairingTransactionIdNotFound; + return Device::DeviceErrorPairingTransactionIdNotFound; } -/*! This method will only be used from the DeviceManager in order to add a \l{Device} with the given \a deviceClassId, \a name, \a params and \ id. +/*! This method will only be used from the DeviceManagerImplementation in order to add a \l{Device} with the given \a deviceClassId, \a name, \a params and \ id. * Returns \l{DeviceError} to inform about the result. */ -DeviceManager::DeviceError DeviceManager::addConfiguredDeviceInternal(const DeviceClassId &deviceClassId, const QString &name, const ParamList ¶ms, const DeviceId id) +Device::DeviceError DeviceManagerImplementation::addConfiguredDeviceInternal(const DeviceClassId &deviceClassId, const QString &name, const ParamList ¶ms, const DeviceId id) { DeviceClass deviceClass = findDeviceClass(deviceClassId); if (deviceClass.id().isNull()) { - return DeviceErrorDeviceClassNotFound; + return Device::DeviceErrorDeviceClassNotFound; } if (deviceClass.setupMethod() != DeviceClass::SetupMethodJustAdd) { - return DeviceErrorCreationMethodNotSupported; + return Device::DeviceErrorCreationMethodNotSupported; } foreach(Device *device, m_configuredDevices) { if (device->id() == id) { - return DeviceErrorDuplicateUuid; + return Device::DeviceErrorDuplicateUuid; } } DevicePlugin *plugin = m_devicePlugins.value(deviceClass.pluginId()); if (!plugin) { - return DeviceErrorPluginNotFound; + return Device::DeviceErrorPluginNotFound; } ParamList effectiveParams = params; - DeviceError paramsResult = verifyParams(deviceClass.paramTypes(), effectiveParams); - if (paramsResult != DeviceErrorNoError) { + Device::DeviceError paramsResult = DeviceUtils::verifyParams(deviceClass.paramTypes(), effectiveParams); + if (paramsResult != Device::DeviceErrorNoError) { return paramsResult; } - Device *device = new Device(plugin->pluginId(), id, deviceClassId, this); + Device *device = new Device(plugin, deviceClass, id, this); if (name.isEmpty()) { device->setName(deviceClass.name()); } else { @@ -755,19 +656,19 @@ DeviceManager::DeviceError DeviceManager::addConfiguredDeviceInternal(const Devi device->setParams(effectiveParams); ParamList settings; - verifyParams(deviceClass.settingsTypes(), settings); + DeviceUtils::verifyParams(deviceClass.settingsTypes(), settings); qCDebug(dcDeviceManager()) << "Adding device settings" << settings; device->setSettings(settings); - DeviceSetupStatus status = setupDevice(device); + Device::DeviceSetupStatus status = setupDevice(device); switch (status) { - case DeviceSetupStatusFailure: + case Device::DeviceSetupStatusFailure: qCWarning(dcDeviceManager) << "Device setup failed. Not adding device to system."; delete device; - return DeviceErrorSetupFailed; - case DeviceSetupStatusAsync: - return DeviceErrorAsync; - case DeviceSetupStatusSuccess: + return Device::DeviceErrorSetupFailed; + case Device::DeviceSetupStatusAsync: + return Device::DeviceErrorAsync; + case Device::DeviceSetupStatusSuccess: qCDebug(dcDeviceManager) << "Device setup complete."; break; } @@ -778,17 +679,17 @@ DeviceManager::DeviceError DeviceManager::addConfiguredDeviceInternal(const Devi emit deviceAdded(device); - return DeviceErrorNoError; + return Device::DeviceErrorNoError; } /*! Removes a \l{Device} with the given \a deviceId from the list of configured \l{Device}{Devices}. * This method also deletes all saved settings of the \l{Device}. * Returns \l{DeviceError} to inform about the result. */ -DeviceManager::DeviceError DeviceManager::removeConfiguredDevice(const DeviceId &deviceId) +Device::DeviceError DeviceManagerImplementation::removeConfiguredDevice(const DeviceId &deviceId) { Device *device = m_configuredDevices.take(deviceId); if (!device) { - return DeviceErrorDeviceNotFound; + return Device::DeviceErrorDeviceNotFound; } m_devicePlugins.value(device->pluginId())->deviceRemoved(device); @@ -805,11 +706,16 @@ DeviceManager::DeviceError DeviceManager::removeConfiguredDevice(const DeviceId emit deviceRemoved(deviceId); - return DeviceErrorNoError; + return Device::DeviceErrorNoError; +} + +QString DeviceManagerImplementation::translate(const PluginId &pluginId, const QString &string, const QLocale &locale) +{ + return m_translator->translate(pluginId, string, locale); } /*! Returns the \l{Device} with the given \a id. Null if the id couldn't be found. */ -Device *DeviceManager::findConfiguredDevice(const DeviceId &id) const +Device *DeviceManagerImplementation::findConfiguredDevice(const DeviceId &id) const { foreach (Device *device, m_configuredDevices) { if (device->id() == id) { @@ -820,13 +726,13 @@ Device *DeviceManager::findConfiguredDevice(const DeviceId &id) const } /*! Returns all configured \{Device}{Devices} in the system. */ -QList DeviceManager::configuredDevices() const +Devices DeviceManagerImplementation::configuredDevices() const { return m_configuredDevices.values(); } /*! Returns all \l{Device}{Devices} matching the \l{DeviceClass} referred by \a deviceClassId. */ -QList DeviceManager::findConfiguredDevices(const DeviceClassId &deviceClassId) const +Devices DeviceManagerImplementation::findConfiguredDevices(const DeviceClassId &deviceClassId) const { QList ret; foreach (Device *device, m_configuredDevices) { @@ -838,7 +744,7 @@ QList DeviceManager::findConfiguredDevices(const DeviceClassId &device } /*! Returns all \l{Device}{Devices} with the given \a interface. See also \l{Interfaces for DeviceClasses}{interfaces}. */ -QList DeviceManager::findConfiguredDevices(const QString &interface) const +Devices DeviceManagerImplementation::findConfiguredDevices(const QString &interface) const { QList ret; foreach (Device *device, m_configuredDevices) { @@ -851,7 +757,7 @@ QList DeviceManager::findConfiguredDevices(const QString &interface) c } /*! Returns all child \l{Device}{Devices} of the \l{Device} with the given \a id. */ -QList DeviceManager::findChildDevices(const DeviceId &id) const +Devices DeviceManagerImplementation::findChildDevices(const DeviceId &id) const { QList ret; foreach (Device *d, m_configuredDevices) { @@ -864,7 +770,7 @@ QList DeviceManager::findChildDevices(const DeviceId &id) const /*! For conveninece, this returns the \l{DeviceClass} with the id given by \a deviceClassId. * Note: The returned \l{DeviceClass} may be invalid. */ -DeviceClass DeviceManager::findDeviceClass(const DeviceClassId &deviceClassId) const +DeviceClass DeviceManagerImplementation::findDeviceClass(const DeviceClassId &deviceClassId) const { foreach (const DeviceClass &deviceClass, m_supportedDevices) { if (deviceClass.id() == deviceClassId) { @@ -874,138 +780,10 @@ DeviceClass DeviceManager::findDeviceClass(const DeviceClassId &deviceClassId) c return DeviceClass(); } -/*! Verify if the given \a params matches the given \a paramTypes. Ith \a requireAll - * is true, all \l{ParamList}{Params} has to be valid. Returns \l{DeviceError} to inform about the result.*/ -DeviceManager::DeviceError DeviceManager::verifyParams(const QList paramTypes, ParamList ¶ms, bool requireAll) -{ - foreach (const Param ¶m, params) { - DeviceManager::DeviceError result = verifyParam(paramTypes, param); - if (result != DeviceErrorNoError) { - return result; - } - } - if (!requireAll) { - return DeviceErrorNoError; - } - foreach (const ParamType ¶mType, paramTypes) { - bool found = false; - foreach (const Param ¶m, params) { - if (paramType.id() == param.paramTypeId()) { - found = true; - } - } - - // This paramType has a default value... lets fill in that one. - if (!paramType.defaultValue().isNull() && !found) { - found = true; - params.append(Param(paramType.id(), paramType.defaultValue())); - } - - if (!found) { - qCWarning(dcDeviceManager) << "Missing parameter:" << paramType.name(); - return DeviceErrorMissingParameter; - } - } - return DeviceErrorNoError; -} - -/*! Verify if the given \a param matches one of the given \a paramTypes. Returns \l{DeviceError} to inform about the result.*/ -DeviceManager::DeviceError DeviceManager::verifyParam(const QList paramTypes, const Param ¶m) -{ - foreach (const ParamType ¶mType, paramTypes) { - if (paramType.id() == param.paramTypeId()) { - return verifyParam(paramType, param); - } - } - - qCWarning(dcDeviceManager) << "Invalid parameter" << param.paramTypeId().toString() << "in parameter list"; - return DeviceErrorInvalidParameter; -} - -/*! Verify if the given \a param matches the given \a paramType. Returns \l{DeviceError} to inform about the result.*/ -DeviceManager::DeviceError DeviceManager::verifyParam(const ParamType ¶mType, const Param ¶m) -{ - if (paramType.id() != param.paramTypeId()) { - qCWarning(dcDeviceManager) << "Parameter id" << param.paramTypeId().toString() << "does not match with ParamType id" << paramType.id().toString(); - return DeviceErrorInvalidParameter; - } - - if (!param.value().canConvert(static_cast(paramType.type()))) { - qCWarning(dcDeviceManager) << "Wrong parameter type for param" << param.paramTypeId().toString() << " Got:" << param.value() << " Expected:" << QVariant::typeToName(static_cast(paramType.type())); - return DeviceErrorInvalidParameter; - } - - if (!param.value().convert(static_cast(paramType.type()))) { - qCWarning(dcDeviceManager) << "Could not convert value of param" << param.paramTypeId().toString() << " to:" << QVariant::typeToName(static_cast(paramType.type())) << " Got:" << param.value(); - return DeviceErrorInvalidParameter; - } - - if (paramType.type() == QVariant::Int) { - if (paramType.maxValue().isValid() && param.value().toInt() > paramType.maxValue().toInt()) { - qCWarning(dcDeviceManager) << "Value out of range for param" << param.paramTypeId().toString() << " Got:" << param.value() << " Max:" << paramType.maxValue(); - return DeviceErrorInvalidParameter; - } - - if (paramType.minValue().isValid() && param.value().toInt() < paramType.minValue().toInt()) { - qCWarning(dcDeviceManager) << "Value out of range for param" << param.paramTypeId().toString() << " Got:" << param.value() << " Min:" << paramType.minValue(); - return DeviceErrorInvalidParameter; - } - } else if (paramType.type() == QVariant::UInt) { - if (paramType.maxValue().isValid() && param.value().toUInt() > paramType.maxValue().toUInt()) { - qCWarning(dcDeviceManager) << "Value out of range for param" << param.paramTypeId().toString() << " Got:" << param.value() << " Max:" << paramType.maxValue(); - return DeviceErrorInvalidParameter; - } - - if (paramType.minValue().isValid() && param.value().toUInt() < paramType.minValue().toUInt()) { - qCWarning(dcDeviceManager) << "Value out of range for param" << param.paramTypeId().toString() << " Got:" << param.value() << " Min:" << paramType.minValue(); - return DeviceErrorInvalidParameter; - } - } else if (paramType.type() == QVariant::Double) { - if (paramType.maxValue().isValid() && param.value().toDouble() > paramType.maxValue().toDouble()) { - qCWarning(dcDeviceManager) << "Value out of range for param" << param.paramTypeId().toString() << " Got:" << param.value() << " Max:" << paramType.maxValue(); - return DeviceErrorInvalidParameter; - } - - if (paramType.minValue().isValid() && param.value().toDouble() < paramType.minValue().toDouble()) { - qCWarning(dcDeviceManager) << "Value out of range for param" << param.paramTypeId().toString() << " Got:" << param.value() << " Min:" << paramType.minValue(); - return DeviceErrorInvalidParameter; - } - } else { - if (paramType.maxValue().isValid() && param.value() > paramType.maxValue()) { - qCWarning(dcDeviceManager) << "Value out of range for param" << param.paramTypeId().toString() << " Got:" << param.value() << " Max:" << paramType.maxValue(); - return DeviceErrorInvalidParameter; - } - - if (paramType.minValue().isValid() && param.value() < paramType.minValue()) { - qCWarning(dcDeviceManager) << "Value out of range for param" << param.paramTypeId().toString() << " Got:" << param.value() << " Min:" << paramType.minValue(); - return DeviceErrorInvalidParameter; - } - } - - if (!paramType.allowedValues().isEmpty() && !paramType.allowedValues().contains(param.value())) { - QStringList allowedValues; - foreach (const QVariant &value, paramType.allowedValues()) { - allowedValues.append(value.toString()); - } - - qCWarning(dcDeviceManager) << "Value not in allowed values for param" << param.paramTypeId().toString() << " Got:" << param.value() << " Allowed:" << allowedValues.join(","); - return DeviceErrorInvalidParameter; - } - - return DeviceErrorNoError; -} - -/*! Returns the translator. The translator can be used to translate plugin data. - * */ -Translator *DeviceManager::translator() const -{ - return m_translator; -} - /*! Execute the given \l{Action}. * This will find the \l{Device} \a action refers to the \l{Action}{deviceId()} and * its \l{DevicePlugin}. Then will dispatch the execution to the \l{DevicePlugin}.*/ -DeviceManager::DeviceError DeviceManager::executeAction(const Action &action) +Device::DeviceError DeviceManagerImplementation::executeAction(const Action &action) { Action finalAction = action; foreach (Device *device, m_configuredDevices) { @@ -1018,8 +796,8 @@ DeviceManager::DeviceError DeviceManager::executeAction(const Action &action) foreach (const ActionType &actionType, deviceClass.actionTypes()) { if (actionType.id() == action.actionTypeId()) { ParamList finalParams = action.params(); - DeviceError paramCheck = verifyParams(actionType.paramTypes(), finalParams); - if (paramCheck != DeviceErrorNoError) { + Device::DeviceError paramCheck = DeviceUtils::verifyParams(actionType.paramTypes(), finalParams); + if (paramCheck != Device::DeviceErrorNoError) { return paramCheck; } finalAction.setParams(finalParams); @@ -1028,22 +806,22 @@ DeviceManager::DeviceError DeviceManager::executeAction(const Action &action) } } if (!found) { - return DeviceErrorActionTypeNotFound; + return Device::DeviceErrorActionTypeNotFound; } return m_devicePlugins.value(device->pluginId())->executeAction(device, finalAction); } } - return DeviceErrorDeviceNotFound; + return Device::DeviceErrorDeviceNotFound; } /*! Centralized time tick for the NymeaTimer resource. Ticks every second. */ -void DeviceManager::timeTick() +void DeviceManagerImplementation::timeTick() { } -void DeviceManager::loadPlugins() +void DeviceManagerImplementation::loadPlugins() { foreach (const QString &path, pluginSearchDirs()) { QDir dir(path); @@ -1069,30 +847,30 @@ void DeviceManager::loadPlugins() continue; } + PluginMetadata metaData(loader.metaData().value("MetaData").toObject()); + if (!metaData.isValid()) { + qCWarning(dcDeviceManager()) << "Plugin metadata not valid for" << entry; + continue; + } + DevicePlugin *pluginIface = qobject_cast(loader.instance()); if (!pluginIface) { qCWarning(dcDeviceManager) << "Could not get plugin instance of" << entry; continue; } - pluginIface->setParent(this); - - if (!verifyPluginMetadata(loader.metaData().value("MetaData").toObject())) - continue; - - pluginIface->setMetaData(loader.metaData().value("MetaData").toObject()); - - loadPlugin(pluginIface); + loadPlugin(pluginIface, metaData); } } } -void DeviceManager::loadPlugin(DevicePlugin *pluginIface) +void DeviceManagerImplementation::loadPlugin(DevicePlugin *pluginIface, const PluginMetadata &metaData) { - pluginIface->initPlugin(this); + pluginIface->setParent(this); + pluginIface->initPlugin(metaData, this, m_hardwareManager); qCDebug(dcDeviceManager) << "**** Loaded plugin" << pluginIface->pluginName(); foreach (const Vendor &vendor, pluginIface->supportedVendors()) { - qCDebug(dcDeviceManager) << "* Loaded vendor:" << vendor.name(); + qCDebug(dcDeviceManager) << "* Loaded vendor:" << vendor.name() << vendor.id(); if (m_supportedVendors.contains(vendor.id())) continue; @@ -1150,8 +928,8 @@ void DeviceManager::loadPlugin(DevicePlugin *pluginIface) settings.endGroup(); if (params.count() > 0) { - DeviceError status = pluginIface->setConfiguration(params); - if (status != DeviceErrorNoError) { + Device::DeviceError status = pluginIface->setConfiguration(params); + if (status != Device::DeviceErrorNoError) { qCWarning(dcDeviceManager) << "Error setting params to plugin. Broken configuration?"; } } @@ -1161,35 +939,43 @@ void DeviceManager::loadPlugin(DevicePlugin *pluginIface) m_devicePlugins.insert(pluginIface->pluginId(), pluginIface); - connect(pluginIface, &DevicePlugin::emitEvent, this, &DeviceManager::eventTriggered); - connect(pluginIface, &DevicePlugin::devicesDiscovered, this, &DeviceManager::slotDevicesDiscovered, Qt::QueuedConnection); - connect(pluginIface, &DevicePlugin::deviceSetupFinished, this, &DeviceManager::slotDeviceSetupFinished); - connect(pluginIface, &DevicePlugin::actionExecutionFinished, this, &DeviceManager::actionExecutionFinished); - connect(pluginIface, &DevicePlugin::pairingFinished, this, &DeviceManager::slotPairingFinished); - connect(pluginIface, &DevicePlugin::autoDevicesAppeared, this, &DeviceManager::onAutoDevicesAppeared); - connect(pluginIface, &DevicePlugin::autoDeviceDisappeared, this, &DeviceManager::onAutoDeviceDisappeared); + connect(pluginIface, &DevicePlugin::emitEvent, this, &DeviceManagerImplementation::eventTriggered); + connect(pluginIface, &DevicePlugin::devicesDiscovered, this, &DeviceManagerImplementation::slotDevicesDiscovered, Qt::QueuedConnection); + connect(pluginIface, &DevicePlugin::deviceSetupFinished, this, &DeviceManagerImplementation::slotDeviceSetupFinished); + connect(pluginIface, &DevicePlugin::actionExecutionFinished, this, &DeviceManagerImplementation::actionExecutionFinished); + connect(pluginIface, &DevicePlugin::pairingFinished, this, &DeviceManagerImplementation::slotPairingFinished); + connect(pluginIface, &DevicePlugin::autoDevicesAppeared, this, &DeviceManagerImplementation::onAutoDevicesAppeared); + connect(pluginIface, &DevicePlugin::autoDeviceDisappeared, this, &DeviceManagerImplementation::onAutoDeviceDisappeared); } -void DeviceManager::loadConfiguredDevices() +void DeviceManagerImplementation::loadConfiguredDevices() { NymeaSettings settings(NymeaSettings::SettingsRoleDevices); settings.beginGroup("DeviceConfig"); qCDebug(dcDeviceManager) << "Loading devices from" << settings.fileName(); foreach (const QString &idString, settings.childGroups()) { settings.beginGroup(idString); - Device *device = new Device(PluginId(settings.value("pluginid").toString()), DeviceId(idString), DeviceClassId(settings.value("deviceClassId").toString()), this); - device->m_autoCreated = settings.value("autoCreated").toBool(); - device->setName(settings.value("devicename").toString()); - device->setParentId(DeviceId(settings.value("parentid", QUuid()).toString())); - - DeviceClass deviceClass = findDeviceClass(device->deviceClassId()); - if (!deviceClass.isValid()) { - qCWarning(dcDeviceManager()) << "Not loading device" << device << "because the device class for this device could not be found."; + QString deviceName = settings.value("devicename").toString(); + DevicePlugin *plugin = m_devicePlugins.value(PluginId(settings.value("pluginid").toString())); + if (!plugin) { + qCWarning(dcDeviceManager()) << "Not loading device" << deviceName << idString << "because the plugin for this device could not be found."; settings.endGroup(); // DeviceId continue; } + DeviceClass deviceClass = findDeviceClass(DeviceClassId(settings.value("deviceClassId").toString())); + if (!deviceClass.isValid()) { + qCWarning(dcDeviceManager()) << "Not loading device" << deviceName << idString << "because the device class for this device could not be found."; + settings.endGroup(); // DeviceId + continue; + } + + Device *device = new Device(plugin, deviceClass, DeviceId(idString), this); + device->m_autoCreated = settings.value("autoCreated").toBool(); + device->setName(deviceName); + device->setParentId(DeviceId(settings.value("parentid", QUuid()).toString())); + ParamList params; settings.beginGroup("Params"); @@ -1242,7 +1028,7 @@ void DeviceManager::loadConfiguredDevices() params.append(Param(ParamTypeId(paramTypeIdString), settings.value(paramTypeIdString))); } } - verifyParams(deviceClass.settingsTypes(), deviceSettings); + DeviceUtils::verifyParams(deviceClass.settingsTypes(), deviceSettings); device->setSettings(deviceSettings); settings.endGroup(); // Settings @@ -1267,14 +1053,14 @@ void DeviceManager::loadConfiguredDevices() } Q_ASSERT(device != nullptr); - DeviceSetupStatus status = setupDevice(device); - if (status == DeviceSetupStatus::DeviceSetupStatusSuccess) + Device::DeviceSetupStatus status = setupDevice(device); + if (status == Device::DeviceSetupStatusSuccess) postSetupDevice(device); } } -void DeviceManager::storeConfiguredDevices() +void DeviceManagerImplementation::storeConfiguredDevices() { NymeaSettings settings(NymeaSettings::SettingsRoleDevices); settings.beginGroup("DeviceConfig"); @@ -1313,14 +1099,14 @@ void DeviceManager::storeConfiguredDevices() settings.endGroup(); // DeviceConfig } -void DeviceManager::startMonitoringAutoDevices() +void DeviceManagerImplementation::startMonitoringAutoDevices() { foreach (DevicePlugin *plugin, m_devicePlugins) { plugin->startMonitoringAutoDevices(); } } -void DeviceManager::slotDevicesDiscovered(const DeviceClassId &deviceClassId, const QList deviceDescriptors) +void DeviceManagerImplementation::slotDevicesDiscovered(const DeviceClassId &deviceClassId, const QList deviceDescriptors) { DevicePlugin *plugin = static_cast(sender()); if (!m_discoveringPlugins.contains(plugin)) { @@ -1335,7 +1121,7 @@ void DeviceManager::slotDevicesDiscovered(const DeviceClassId &deviceClassId, co emit devicesDiscovered(deviceClassId, deviceDescriptors); } -void DeviceManager::slotDeviceSetupFinished(Device *device, DeviceManager::DeviceSetupStatus status) +void DeviceManagerImplementation::slotDeviceSetupFinished(Device *device, Device::DeviceSetupStatus status) { Q_ASSERT_X(device, "DeviceManager", "Device must be a valid pointer."); if (!device) { @@ -1348,13 +1134,13 @@ void DeviceManager::slotDeviceSetupFinished(Device *device, DeviceManager::Devic return; } - Q_ASSERT_X(status != DeviceSetupStatusAsync, "DeviceManager", "Bad plugin implementation. You should not emit deviceSetupFinished with status DeviceSetupStatusAsync."); - if (status == DeviceSetupStatusAsync) { + Q_ASSERT_X(status != Device::DeviceSetupStatusAsync, "DeviceManager", "Bad plugin implementation. You should not emit deviceSetupFinished with status DeviceSetupStatusAsync."); + if (status == Device::DeviceSetupStatusAsync) { qCWarning(dcDeviceManager) << "Bad plugin implementation. Received a deviceSetupFinished event with status Async... ignoring..."; return; } - if (status == DeviceSetupStatusFailure) { + if (status == Device::DeviceSetupStatusFailure) { if (m_configuredDevices.contains(device->id())) { if (m_asyncDeviceReconfiguration.contains(device)) { m_asyncDeviceReconfiguration.removeAll(device); @@ -1365,14 +1151,14 @@ void DeviceManager::slotDeviceSetupFinished(Device *device, DeviceManager::Devic // TODO: recover old params.?? emit deviceChanged(device); - emit deviceReconfigurationFinished(device, DeviceError::DeviceErrorSetupFailed); + emit deviceReconfigurationFinished(device, Device::DeviceErrorSetupFailed); } qCWarning(dcDeviceManager) << QString("Error in device setup. Device %1 (%2) will not be functional.").arg(device->name()).arg(device->id().toString()); - emit deviceSetupFinished(device, DeviceError::DeviceErrorSetupFailed); + emit deviceSetupFinished(device, Device::DeviceErrorSetupFailed); return; } else { qCWarning(dcDeviceManager) << QString("Error in device setup. Device %1 (%2) will not be added to the configured devices.").arg(device->name()).arg(device->id().toString()); - emit deviceSetupFinished(device, DeviceError::DeviceErrorSetupFailed); + emit deviceSetupFinished(device, Device::DeviceErrorSetupFailed); return; } } @@ -1391,18 +1177,18 @@ void DeviceManager::slotDeviceSetupFinished(Device *device, DeviceManager::Devic storeConfiguredDevices(); device->setupCompleted(); emit deviceChanged(device); - emit deviceReconfigurationFinished(device, DeviceManager::DeviceErrorNoError); + emit deviceReconfigurationFinished(device, Device::DeviceErrorNoError); return; } - connect(device, &Device::stateValueChanged, this, &DeviceManager::slotDeviceStateValueChanged); - connect(device, &Device::settingChanged, this, &DeviceManager::slotDeviceSettingChanged); + connect(device, &Device::stateValueChanged, this, &DeviceManagerImplementation::slotDeviceStateValueChanged); + connect(device, &Device::settingChanged, this, &DeviceManagerImplementation::slotDeviceSettingChanged); device->setupCompleted(); - emit deviceSetupFinished(device, DeviceManager::DeviceErrorNoError); + emit deviceSetupFinished(device, Device::DeviceErrorNoError); } -void DeviceManager::slotPairingFinished(const PairingTransactionId &pairingTransactionId, DeviceManager::DeviceSetupStatus status) +void DeviceManagerImplementation::slotPairingFinished(const PairingTransactionId &pairingTransactionId, Device::DeviceSetupStatus status) { if (!m_pairingsJustAdd.contains(pairingTransactionId) && !m_pairingsDiscovery.contains(pairingTransactionId)) { DevicePlugin *plugin = dynamic_cast(sender()); @@ -1439,8 +1225,8 @@ void DeviceManager::slotPairingFinished(const PairingTransactionId &pairingTrans deviceId = descriptor.deviceId(); } - if (status != DeviceSetupStatusSuccess) { - emit pairingFinished(pairingTransactionId, DeviceErrorSetupFailed); + if (status != Device::DeviceSetupStatusSuccess) { + emit pairingFinished(pairingTransactionId, Device::DeviceErrorSetupFailed); return; } @@ -1448,7 +1234,7 @@ void DeviceManager::slotPairingFinished(const PairingTransactionId &pairingTrans DevicePlugin *plugin = m_devicePlugins.value(deviceClass.pluginId()); if (!plugin) { qCWarning(dcDeviceManager) << "Cannot find a plugin for this device class!"; - emit pairingFinished(pairingTransactionId, DeviceErrorPluginNotFound, deviceClass.pluginId().toString()); + emit pairingFinished(pairingTransactionId, Device::DeviceErrorPluginNotFound, deviceClass.pluginId().toString()); return; } @@ -1457,7 +1243,7 @@ void DeviceManager::slotPairingFinished(const PairingTransactionId &pairingTrans if (!addNewDevice && !m_configuredDevices.contains(deviceId)) { qCWarning(dcDeviceManager) << "The device to be reconfigured has disappeared!"; - emit pairingFinished(pairingTransactionId, DeviceErrorDeviceNotFound, deviceId); + emit pairingFinished(pairingTransactionId, Device::DeviceErrorDeviceNotFound, deviceId); return; } @@ -1467,7 +1253,7 @@ void DeviceManager::slotPairingFinished(const PairingTransactionId &pairingTrans if (addNewDevice) { deviceId = DeviceId::createDeviceId(); qCDebug(dcDeviceManager()) << "Creating new device with ID" << deviceId; - device = new Device(plugin->pluginId(), deviceId, deviceClassId, this); + device = new Device(plugin, deviceClass, deviceId, this); if (deviceName.isEmpty()) { device->setName(deviceClass.name()); } else { @@ -1477,24 +1263,24 @@ void DeviceManager::slotPairingFinished(const PairingTransactionId &pairingTrans device = m_configuredDevices.value(deviceId); qCDebug(dcDeviceManager()) << "Reconfiguring device" << device; } - emit pairingFinished(pairingTransactionId, DeviceErrorNoError, deviceId); + emit pairingFinished(pairingTransactionId, Device::DeviceErrorNoError, deviceId); device->setParams(params); ParamList settings; // Use verifyParams to populate it with defaults - verifyParams(deviceClass.settingsTypes(), settings); + DeviceUtils::verifyParams(deviceClass.settingsTypes(), settings); device->setSettings(settings); - DeviceSetupStatus setupStatus = setupDevice(device); + Device::DeviceSetupStatus setupStatus = setupDevice(device); switch (setupStatus) { - case DeviceSetupStatusFailure: + case Device::DeviceSetupStatusFailure: qCWarning(dcDeviceManager) << "Device setup failed. Not adding device to system."; - emit deviceSetupFinished(device, DeviceError::DeviceErrorSetupFailed); + emit deviceSetupFinished(device, Device::DeviceErrorSetupFailed); delete device; break; - case DeviceSetupStatusAsync: + case Device::DeviceSetupStatusAsync: return; - case DeviceSetupStatusSuccess: + case Device::DeviceSetupStatusSuccess: qCDebug(dcDeviceManager) << "Device setup complete."; break; } @@ -1508,11 +1294,11 @@ void DeviceManager::slotPairingFinished(const PairingTransactionId &pairingTrans } storeConfiguredDevices(); - emit deviceSetupFinished(device, DeviceError::DeviceErrorNoError); + emit deviceSetupFinished(device, Device::DeviceErrorNoError); postSetupDevice(device); } -void DeviceManager::onAutoDevicesAppeared(const DeviceClassId &deviceClassId, const QList &deviceDescriptors) +void DeviceManagerImplementation::onAutoDevicesAppeared(const DeviceClassId &deviceClassId, const QList &deviceDescriptors) { DeviceClass deviceClass = findDeviceClass(deviceClassId); if (!deviceClass.isValid()) { @@ -1545,29 +1331,29 @@ void DeviceManager::onAutoDevicesAppeared(const DeviceClassId &deviceClassId, co continue; } - device = new Device(plugin->pluginId(), deviceClassId, this); + device = new Device(plugin, deviceClass, this); device->m_autoCreated = true; device->setName(deviceDescriptor.title()); device->setParams(deviceDescriptor.params()); ParamList settings; - verifyParams(deviceClass.settingsTypes(), settings); + DeviceUtils::verifyParams(deviceClass.settingsTypes(), settings); device->setSettings(settings); device->setParentId(deviceDescriptor.parentDeviceId()); - DeviceSetupStatus setupStatus = setupDevice(device); + Device::DeviceSetupStatus setupStatus = setupDevice(device); switch (setupStatus) { - case DeviceSetupStatusFailure: + case Device::DeviceSetupStatusFailure: qCWarning(dcDeviceManager) << "Device setup failed. Not adding device to system."; - emit deviceSetupFinished(device, DeviceError::DeviceErrorSetupFailed); + emit deviceSetupFinished(device, Device::DeviceErrorSetupFailed); delete device; break; - case DeviceSetupStatusAsync: + case Device::DeviceSetupStatusAsync: break; - case DeviceSetupStatusSuccess: + case Device::DeviceSetupStatusSuccess: qCDebug(dcDeviceManager) << "Device setup complete."; m_configuredDevices.insert(device->id(), device); storeConfiguredDevices(); - emit deviceSetupFinished(device, DeviceError::DeviceErrorNoError); + emit deviceSetupFinished(device, Device::DeviceErrorNoError); emit deviceAdded(device); postSetupDevice(device); break; @@ -1575,7 +1361,7 @@ void DeviceManager::onAutoDevicesAppeared(const DeviceClassId &deviceClassId, co } } -void DeviceManager::onAutoDeviceDisappeared(const DeviceId &deviceId) +void DeviceManagerImplementation::onAutoDeviceDisappeared(const DeviceId &deviceId) { DevicePlugin *plugin = static_cast(sender()); Device *device = m_configuredDevices.value(deviceId); @@ -1600,7 +1386,7 @@ void DeviceManager::onAutoDeviceDisappeared(const DeviceId &deviceId) emit deviceDisappeared(deviceId); } -void DeviceManager::onLoaded() +void DeviceManagerImplementation::onLoaded() { qCDebug(dcDeviceManager()) << "Done loading plugins and devices."; emit loaded(); @@ -1609,7 +1395,7 @@ void DeviceManager::onLoaded() QTimer::singleShot(0, this, SLOT(cleanupDeviceStateCache())); } -void DeviceManager::cleanupDeviceStateCache() +void DeviceManagerImplementation::cleanupDeviceStateCache() { NymeaSettings settings(NymeaSettings::SettingsRoleDeviceStates); foreach (const QString &entry, settings.childGroups()) { @@ -1621,7 +1407,7 @@ void DeviceManager::cleanupDeviceStateCache() } } -void DeviceManager::slotDeviceStateValueChanged(const StateTypeId &stateTypeId, const QVariant &value) +void DeviceManagerImplementation::slotDeviceStateValueChanged(const StateTypeId &stateTypeId, const QVariant &value) { Device *device = qobject_cast(sender()); if (!device) { @@ -1634,7 +1420,7 @@ void DeviceManager::slotDeviceStateValueChanged(const StateTypeId &stateTypeId, emit eventTriggered(event); } -void DeviceManager::slotDeviceSettingChanged(const ParamTypeId ¶mTypeId, const QVariant &value) +void DeviceManagerImplementation::slotDeviceSettingChanged(const ParamTypeId ¶mTypeId, const QVariant &value) { Device *device = qobject_cast(sender()); if (!device) { @@ -1644,29 +1430,14 @@ void DeviceManager::slotDeviceSettingChanged(const ParamTypeId ¶mTypeId, con emit deviceSettingChanged(device->id(), paramTypeId, value); } -bool DeviceManager::verifyPluginMetadata(const QJsonObject &data) -{ - QStringList requiredFields; - requiredFields << "name" << "id" << "vendors"; - - foreach (const QString &field, requiredFields) { - if (!data.contains(field)) { - qCWarning(dcDeviceManager) << "Error loading plugin. Incomplete metadata. Missing field:" << field; - qCWarning(dcDeviceManager) << data; - return false; - } - } - return true; -} - -DeviceManager::DeviceSetupStatus DeviceManager::setupDevice(Device *device) +Device::DeviceSetupStatus DeviceManagerImplementation::setupDevice(Device *device) { DeviceClass deviceClass = findDeviceClass(device->deviceClassId()); DevicePlugin *plugin = m_devicePlugins.value(deviceClass.pluginId()); if (!plugin) { qCWarning(dcDeviceManager) << "Can't find a plugin for this device" << device->id(); - return DeviceSetupStatusFailure; + return Device::DeviceSetupStatusFailure; } QList states; @@ -1677,19 +1448,19 @@ DeviceManager::DeviceSetupStatus DeviceManager::setupDevice(Device *device) device->setStates(states); loadDeviceStates(device); - DeviceSetupStatus status = plugin->setupDevice(device); - if (status != DeviceSetupStatusSuccess) { + Device::DeviceSetupStatus status = plugin->setupDevice(device); + if (status != Device::DeviceSetupStatusSuccess) { return status; } - connect(device, &Device::stateValueChanged, this, &DeviceManager::slotDeviceStateValueChanged); - connect(device, &Device::settingChanged, this, &DeviceManager::slotDeviceSettingChanged); + connect(device, &Device::stateValueChanged, this, &DeviceManagerImplementation::slotDeviceStateValueChanged); + connect(device, &Device::settingChanged, this, &DeviceManagerImplementation::slotDeviceSettingChanged); device->setupCompleted(); return status; } -void DeviceManager::postSetupDevice(Device *device) +void DeviceManagerImplementation::postSetupDevice(Device *device) { DeviceClass deviceClass = findDeviceClass(device->deviceClassId()); DevicePlugin *plugin = m_devicePlugins.value(deviceClass.pluginId()); @@ -1697,7 +1468,7 @@ void DeviceManager::postSetupDevice(Device *device) plugin->postSetupDevice(device); } -void DeviceManager::loadDeviceStates(Device *device) +void DeviceManagerImplementation::loadDeviceStates(Device *device) { NymeaSettings settings(NymeaSettings::SettingsRoleDeviceStates); settings.beginGroup(device->id().toString()); @@ -1722,7 +1493,7 @@ void DeviceManager::loadDeviceStates(Device *device) settings.endGroup(); } -void DeviceManager::storeDeviceStates(Device *device) +void DeviceManagerImplementation::storeDeviceStates(Device *device) { NymeaSettings settings(NymeaSettings::SettingsRoleDeviceStates); settings.beginGroup(device->id().toString()); diff --git a/libnymea-core/devices/devicemanagerimplementation.h b/libnymea-core/devices/devicemanagerimplementation.h new file mode 100644 index 00000000..608e5a70 --- /dev/null +++ b/libnymea-core/devices/devicemanagerimplementation.h @@ -0,0 +1,155 @@ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * + * * + * Copyright (C) 2015-2018 Simon Stürz * + * Copyright (C) 2014 Michael Zanetti * + * * + * This file is part of nymea. * + * * + * This library is free software; you can redistribute it and/or * + * modify it under the terms of the GNU Lesser General Public * + * License as published by the Free Software Foundation; either * + * version 2.1 of the License, or (at your option) any later version. * + * * + * This library is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * + * Lesser General Public License for more details. * + * * + * You should have received a copy of the GNU Lesser General Public * + * License along with this library; If not, see * + * . * + * * + * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +#ifndef DEVICEMANAGERIMPLEMENTATION_H +#define DEVICEMANAGERIMPLEMENTATION_H + +#include "libnymea.h" + +#include "devices/device.h" +#include "devices/devicedescriptor.h" +#include "devices/pluginmetadata.h" + +#include "types/deviceclass.h" +#include "types/interface.h" +#include "types/event.h" +#include "types/action.h" +#include "types/vendor.h" + +#include +#include +#include +#include +#include + +#include "hardwaremanager.h" + +#include "devices/devicemanager.h" + +class Device; +class DevicePlugin; +class DevicePairingInfo; +class HardwareManager; +class Translator; + +class DeviceManagerImplementation: public DeviceManager +{ + Q_OBJECT + + friend class DevicePlugin; + +public: + explicit DeviceManagerImplementation(HardwareManager *hardwareManager, const QLocale &locale, QObject *parent = nullptr); + ~DeviceManagerImplementation(); + + static QStringList pluginSearchDirs(); + static QList pluginsMetadata(); + void registerStaticPlugin(DevicePlugin* plugin, const PluginMetadata &metaData); + + DevicePlugins plugins() const override; + Device::DeviceError setPluginConfig(const PluginId &pluginId, const ParamList &pluginConfig) override; + + Vendors supportedVendors() const override; + Interfaces supportedInterfaces() const override; + DeviceClasses supportedDevices(const VendorId &vendorId = VendorId()) const override; + + Devices configuredDevices() const override; + Device* findConfiguredDevice(const DeviceId &id) const override; + Devices findConfiguredDevices(const DeviceClassId &deviceClassId) const override; + Devices findConfiguredDevices(const QString &interface) const override; + Devices findChildDevices(const DeviceId &id) const override; + DeviceClass findDeviceClass(const DeviceClassId &deviceClassId) const override; + + Device::DeviceError discoverDevices(const DeviceClassId &deviceClassId, const ParamList ¶ms) override; + + Device::DeviceError addConfiguredDevice(const DeviceClassId &deviceClassId, const QString &name, const ParamList ¶ms, const DeviceId id = DeviceId::createDeviceId()) override; + Device::DeviceError addConfiguredDevice(const DeviceClassId &deviceClassId, const QString &name, const DeviceDescriptorId &deviceDescriptorId, const ParamList ¶ms = ParamList(), const DeviceId &deviceId = DeviceId::createDeviceId()) override; + + Device::DeviceError reconfigureDevice(const DeviceId &deviceId, const ParamList ¶ms, bool fromDiscoveryOrAuto = false) override; + Device::DeviceError reconfigureDevice(const DeviceId &deviceId, const DeviceDescriptorId &deviceDescriptorId) override; + + Device::DeviceError editDevice(const DeviceId &deviceId, const QString &name) override; + Device::DeviceError setDeviceSettings(const DeviceId &deviceId, const ParamList &settings) override; + + Device::DeviceError pairDevice(const PairingTransactionId &pairingTransactionId, const DeviceClassId &deviceClassId, const QString &name, const ParamList ¶ms) override; + Device::DeviceError pairDevice(const PairingTransactionId &pairingTransactionId, const DeviceClassId &deviceClassId, const QString &name, const DeviceDescriptorId &deviceDescriptorId) override; + Device::DeviceError confirmPairing(const PairingTransactionId &pairingTransactionId, const QString &secret = QString()) override; + + Device::DeviceError removeConfiguredDevice(const DeviceId &deviceId) override; + + QString translate(const PluginId &pluginId, const QString &string, const QLocale &locale) override; + +signals: + void loaded(); + +public slots: + Device::DeviceError executeAction(const Action &action); + void timeTick(); + +private slots: + void loadPlugins(); + void loadPlugin(DevicePlugin *pluginIface, const PluginMetadata &metaData); + void loadConfiguredDevices(); + void storeConfiguredDevices(); + void startMonitoringAutoDevices(); + void slotDevicesDiscovered(const DeviceClassId &deviceClassId, const QList deviceDescriptors); + void slotDeviceSetupFinished(Device *device, Device::DeviceSetupStatus status); + void slotPairingFinished(const PairingTransactionId &pairingTransactionId, Device::DeviceSetupStatus status); + void onAutoDevicesAppeared(const DeviceClassId &deviceClassId, const QList &deviceDescriptors); + void onAutoDeviceDisappeared(const DeviceId &deviceId); + void onLoaded(); + void cleanupDeviceStateCache(); + + // Only connect this to Devices. It will query the sender() + void slotDeviceStateValueChanged(const StateTypeId &stateTypeId, const QVariant &value); + void slotDeviceSettingChanged(const ParamTypeId ¶mTypeId, const QVariant &value); + +private: + Device::DeviceError addConfiguredDeviceInternal(const DeviceClassId &deviceClassId, const QString &name, const ParamList ¶ms, const DeviceId id = DeviceId::createDeviceId()); + Device::DeviceSetupStatus setupDevice(Device *device); + void postSetupDevice(Device *device); + void storeDeviceStates(Device *device); + void loadDeviceStates(Device *device); + +private: + HardwareManager *m_hardwareManager; + + QLocale m_locale; + Translator *m_translator = nullptr; + QHash m_supportedVendors; + QHash m_supportedInterfaces; + QHash > m_vendorDeviceMap; + QHash m_supportedDevices; + QHash m_configuredDevices; + QHash m_discoveredDevices; + + QHash m_devicePlugins; + + QHash m_pairingsJustAdd; + QHash m_pairingsDiscovery; + + QList m_asyncDeviceReconfiguration; + QList m_discoveringPlugins; +}; + +#endif // DEVICEMANAGERIMPLEMENTATION_H diff --git a/libnymea-core/stateevaluator.cpp b/libnymea-core/devices/stateevaluator.cpp similarity index 99% rename from libnymea-core/stateevaluator.cpp rename to libnymea-core/devices/stateevaluator.cpp index 8dc053b7..4a9a7d90 100644 --- a/libnymea-core/stateevaluator.cpp +++ b/libnymea-core/devices/stateevaluator.cpp @@ -36,7 +36,7 @@ #include "stateevaluator.h" #include "nymeacore.h" -#include "devicemanager.h" +#include "devices/devicemanager.h" #include "loggingcategories.h" #include "nymeasettings.h" diff --git a/libnymea-core/stateevaluator.h b/libnymea-core/devices/stateevaluator.h similarity index 100% rename from libnymea-core/stateevaluator.h rename to libnymea-core/devices/stateevaluator.h diff --git a/libnymea/translator.cpp b/libnymea-core/devices/translator.cpp similarity index 96% rename from libnymea/translator.cpp rename to libnymea-core/devices/translator.cpp index 586c0a21..e9fed79f 100644 --- a/libnymea/translator.cpp +++ b/libnymea-core/devices/translator.cpp @@ -22,13 +22,14 @@ #include "translator.h" #include "nymeasettings.h" +#include "devicemanagerimplementation.h" #include "loggingcategories.h" -#include "plugin/deviceplugin.h" +#include "devices/deviceplugin.h" #include #include -Translator::Translator(DeviceManager *deviceManager): +Translator::Translator(DeviceManagerImplementation *deviceManager): m_deviceManager(deviceManager) { @@ -46,7 +47,7 @@ Translator::~Translator() QString Translator::translate(const PluginId &pluginId, const QString &string, const QLocale &locale) { - DevicePlugin *plugin = m_deviceManager->plugin(pluginId); + DevicePlugin *plugin = m_deviceManager->plugins().findById(pluginId); if (!m_translatorContexts.contains(plugin->pluginId()) || !m_translatorContexts.value(plugin->pluginId()).translators.contains(locale.name())) { loadTranslator(plugin, locale); diff --git a/libnymea/translator.h b/libnymea-core/devices/translator.h similarity index 93% rename from libnymea/translator.h rename to libnymea-core/devices/translator.h index 9c000266..d02340f5 100644 --- a/libnymea/translator.h +++ b/libnymea-core/devices/translator.h @@ -29,12 +29,12 @@ #include class DevicePlugin; -class DeviceManager; +class DeviceManagerImplementation; class Translator { public: - Translator(DeviceManager *deviceManager); + Translator(DeviceManagerImplementation *deviceManager); ~Translator(); QString translate(const PluginId &pluginId, const QString &string, const QLocale &locale); @@ -43,7 +43,7 @@ private: void loadTranslator(DevicePlugin *plugin, const QLocale &locale); private: - DeviceManager *m_deviceManager = nullptr; + DeviceManagerImplementation *m_deviceManager = nullptr; struct TranslatorContext { PluginId pluginId; diff --git a/libnymea-core/hardware/network/upnp/upnpdiscoveryrequest.h b/libnymea-core/hardware/network/upnp/upnpdiscoveryrequest.h index b370c3a0..57069de7 100644 --- a/libnymea-core/hardware/network/upnp/upnpdiscoveryrequest.h +++ b/libnymea-core/hardware/network/upnp/upnpdiscoveryrequest.h @@ -27,6 +27,7 @@ #include #include #include +#include #include "upnpdiscoveryreplyimplementation.h" #include "network/upnp/upnpdiscovery.h" diff --git a/libnymea-core/jsonrpc/actionhandler.cpp b/libnymea-core/jsonrpc/actionhandler.cpp index d0616441..2105e994 100644 --- a/libnymea-core/jsonrpc/actionhandler.cpp +++ b/libnymea-core/jsonrpc/actionhandler.cpp @@ -35,7 +35,7 @@ #include "actionhandler.h" #include "nymeacore.h" -#include "devicemanager.h" +#include "devices/devicemanager.h" #include "types/action.h" #include "loggingcategories.h" @@ -80,8 +80,8 @@ JsonReply* ActionHandler::ExecuteAction(const QVariantMap ¶ms) Action action(actionTypeId, deviceId); action.setParams(actionParams); - DeviceManager::DeviceError status = NymeaCore::instance()->executeAction(action); - if (status == DeviceManager::DeviceErrorAsync) { + Device::DeviceError status = NymeaCore::instance()->executeAction(action); + if (status == Device::DeviceErrorAsync) { JsonReply *reply = createAsyncReply("ExecuteAction"); ActionId id = action.id(); connect(reply, &JsonReply::finished, [this, id](){ m_asyncActionExecutions.remove(id); }); @@ -99,16 +99,16 @@ JsonReply *ActionHandler::GetActionType(const QVariantMap ¶ms) const foreach (const DeviceClass &deviceClass, NymeaCore::instance()->deviceManager()->supportedDevices()) { foreach (const ActionType &actionType, deviceClass.actionTypes()) { if (actionType.id() == actionTypeId) { - QVariantMap data = statusToReply(DeviceManager::DeviceErrorNoError); + QVariantMap data = statusToReply(Device::DeviceErrorNoError); data.insert("actionType", JsonTypes::packActionType(actionType, deviceClass.pluginId(), params.value("locale").toLocale())); return createReply(data); } } } - return createReply(statusToReply(DeviceManager::DeviceErrorActionTypeNotFound)); + return createReply(statusToReply(Device::DeviceErrorActionTypeNotFound)); } -void ActionHandler::actionExecuted(const ActionId &id, DeviceManager::DeviceError status) +void ActionHandler::actionExecuted(const ActionId &id, Device::DeviceError status) { if (!m_asyncActionExecutions.contains(id)) { return; // Not the action we are waiting for. diff --git a/libnymea-core/jsonrpc/actionhandler.h b/libnymea-core/jsonrpc/actionhandler.h index e3607fb0..d641c917 100644 --- a/libnymea-core/jsonrpc/actionhandler.h +++ b/libnymea-core/jsonrpc/actionhandler.h @@ -23,7 +23,7 @@ #define ACTIONHANDLER_H #include "jsonhandler.h" -#include "devicemanager.h" +#include "devices/devicemanager.h" namespace nymeaserver { @@ -31,7 +31,7 @@ class ActionHandler : public JsonHandler { Q_OBJECT public: - explicit ActionHandler(QObject *parent = 0); + explicit ActionHandler(QObject *parent = nullptr); QString name() const; @@ -39,7 +39,7 @@ public: Q_INVOKABLE JsonReply *GetActionType(const QVariantMap ¶ms) const; private slots: - void actionExecuted(const ActionId &id, DeviceManager::DeviceError status); + void actionExecuted(const ActionId &id, Device::DeviceError status); private: QHash m_asyncActionExecutions; diff --git a/libnymea-core/jsonrpc/devicehandler.cpp b/libnymea-core/jsonrpc/devicehandler.cpp index 53463c0a..1de015e7 100644 --- a/libnymea-core/jsonrpc/devicehandler.cpp +++ b/libnymea-core/jsonrpc/devicehandler.cpp @@ -55,12 +55,12 @@ #include "devicehandler.h" #include "nymeacore.h" -#include "devicemanager.h" +#include "devices/devicemanager.h" +#include "devices/device.h" +#include "devices/deviceplugin.h" #include "loggingcategories.h" #include "types/deviceclass.h" -#include "plugin/device.h" -#include "plugin/deviceplugin.h" -#include "translator.h" +#include "devices/translator.h" #include @@ -361,8 +361,8 @@ JsonReply *DeviceHandler::GetDiscoveredDevices(const QVariantMap ¶ms) const ParamList discoveryParams = JsonTypes::unpackParams(params.value("discoveryParams").toList()); - DeviceManager::DeviceError status = NymeaCore::instance()->deviceManager()->discoverDevices(deviceClassId, discoveryParams); - if (status == DeviceManager::DeviceErrorAsync ) { + Device::DeviceError status = NymeaCore::instance()->deviceManager()->discoverDevices(deviceClassId, discoveryParams); + if (status == Device::DeviceErrorAsync ) { JsonReply *reply = createAsyncReply("GetDiscoveredDevices"); connect(reply, &JsonReply::finished, this, [this, deviceClassId](){ m_discoverRequests.remove(deviceClassId); }); m_discoverRequests.insert(deviceClassId, reply); @@ -385,9 +385,9 @@ JsonReply *DeviceHandler::GetPluginConfiguration(const QVariantMap ¶ms) cons { QVariantMap returns; - DevicePlugin *plugin = NymeaCore::instance()->deviceManager()->plugin(PluginId(params.value("pluginId").toString())); + DevicePlugin *plugin = NymeaCore::instance()->deviceManager()->plugins().findById(PluginId(params.value("pluginId").toString())); if (!plugin) { - returns.insert("deviceError", JsonTypes::deviceErrorToString(DeviceManager::DeviceErrorPluginNotFound)); + returns.insert("deviceError", JsonTypes::deviceErrorToString(Device::DeviceErrorPluginNotFound)); return createReply(returns); } @@ -396,7 +396,7 @@ JsonReply *DeviceHandler::GetPluginConfiguration(const QVariantMap ¶ms) cons paramVariantList.append(JsonTypes::packParam(param)); } returns.insert("configuration", paramVariantList); - returns.insert("deviceError", JsonTypes::deviceErrorToString(DeviceManager::DeviceErrorNoError)); + returns.insert("deviceError", JsonTypes::deviceErrorToString(Device::DeviceErrorNoError)); return createReply(returns); } @@ -405,7 +405,7 @@ JsonReply* DeviceHandler::SetPluginConfiguration(const QVariantMap ¶ms) QVariantMap returns; PluginId pluginId = PluginId(params.value("pluginId").toString()); ParamList pluginParams = JsonTypes::unpackParams(params.value("configuration").toList()); - DeviceManager::DeviceError result = NymeaCore::instance()->deviceManager()->setPluginConfig(pluginId, pluginParams); + Device::DeviceError result = NymeaCore::instance()->deviceManager()->setPluginConfig(pluginId, pluginParams); returns.insert("deviceError", JsonTypes::deviceErrorToString(result)); return createReply(returns); } @@ -417,7 +417,7 @@ JsonReply* DeviceHandler::AddConfiguredDevice(const QVariantMap ¶ms) ParamList deviceParams = JsonTypes::unpackParams(params.value("deviceParams").toList()); DeviceDescriptorId deviceDescriptorId(params.value("deviceDescriptorId").toString()); DeviceId newDeviceId = DeviceId::createDeviceId(); - DeviceManager::DeviceError status; + Device::DeviceError status; if (deviceDescriptorId.isNull()) { status = NymeaCore::instance()->deviceManager()->addConfiguredDevice(deviceClass, deviceName, deviceParams, newDeviceId); } else { @@ -425,13 +425,13 @@ JsonReply* DeviceHandler::AddConfiguredDevice(const QVariantMap ¶ms) } QVariantMap returns; switch (status) { - case DeviceManager::DeviceErrorAsync: { + case Device::DeviceErrorAsync: { JsonReply *asyncReply = createAsyncReply("AddConfiguredDevice"); connect(asyncReply, &JsonReply::finished, [this, newDeviceId](){ m_asynDeviceAdditions.remove(newDeviceId); }); m_asynDeviceAdditions.insert(newDeviceId, asyncReply); return asyncReply; } - case DeviceManager::DeviceErrorNoError: + case Device::DeviceErrorNoError: returns.insert("deviceId", newDeviceId); returns.insert("deviceError", JsonTypes::deviceErrorToString(status)); break; @@ -447,7 +447,7 @@ JsonReply *DeviceHandler::PairDevice(const QVariantMap ¶ms) QString deviceName = params.value("name").toString(); DeviceClass deviceClass = NymeaCore::instance()->deviceManager()->findDeviceClass(deviceClassId); - DeviceManager::DeviceError status; + Device::DeviceError status; PairingTransactionId pairingTransactionId = PairingTransactionId::createPairingTransactionId(); if (params.contains("deviceDescriptorId")) { DeviceDescriptorId deviceDescriptorId(params.value("deviceDescriptorId").toString()); @@ -459,8 +459,8 @@ JsonReply *DeviceHandler::PairDevice(const QVariantMap ¶ms) QVariantMap returns; returns.insert("deviceError", JsonTypes::deviceErrorToString(status)); - if (status == DeviceManager::DeviceErrorNoError) { - returns.insert("displayMessage", NymeaCore::instance()->deviceManager()->translator()->translate(deviceClass.pluginId(), deviceClass.pairingInfo(), params.value("locale").toLocale())); + if (status == Device::DeviceErrorNoError) { + returns.insert("displayMessage", NymeaCore::instance()->deviceManager()->translate(deviceClass.pluginId(), deviceClass.pairingInfo(), params.value("locale").toLocale())); returns.insert("pairingTransactionId", pairingTransactionId.toString()); returns.insert("setupMethod", JsonTypes::setupMethod().at(deviceClass.setupMethod())); } @@ -471,10 +471,10 @@ JsonReply *DeviceHandler::ConfirmPairing(const QVariantMap ¶ms) { PairingTransactionId pairingTransactionId = PairingTransactionId(params.value("pairingTransactionId").toString()); QString secret = params.value("secret").toString(); - DeviceManager::DeviceError status = NymeaCore::instance()->deviceManager()->confirmPairing(pairingTransactionId, secret); + Device::DeviceError status = NymeaCore::instance()->deviceManager()->confirmPairing(pairingTransactionId, secret); JsonReply *reply = nullptr; - if (status == DeviceManager::DeviceErrorAsync) { + if (status == Device::DeviceErrorAsync) { reply = createAsyncReply("ConfirmPairing"); connect(reply, &JsonReply::finished, [this, pairingTransactionId](){ m_asyncPairingRequests.remove(pairingTransactionId); }); m_asyncPairingRequests.insert(pairingTransactionId, reply); @@ -493,7 +493,7 @@ JsonReply* DeviceHandler::GetConfiguredDevices(const QVariantMap ¶ms) const if (params.contains("deviceId")) { Device *device = NymeaCore::instance()->deviceManager()->findConfiguredDevice(DeviceId(params.value("deviceId").toString())); if (!device) { - returns.insert("deviceError", JsonTypes::deviceErrorToString(DeviceManager::DeviceErrorDeviceNotFound)); + returns.insert("deviceError", JsonTypes::deviceErrorToString(Device::DeviceErrorDeviceNotFound)); return createReply(returns); } else { configuredDeviceList.append(JsonTypes::packDevice(device)); @@ -513,7 +513,7 @@ JsonReply *DeviceHandler::ReconfigureDevice(const QVariantMap ¶ms) DeviceId deviceId = DeviceId(params.value("deviceId").toString()); ParamList deviceParams = JsonTypes::unpackParams(params.value("deviceParams").toList()); - DeviceManager::DeviceError status; + Device::DeviceError status; DeviceDescriptorId deviceDescriptorId(params.value("deviceDescriptorId").toString()); if (deviceDescriptorId.isNull()) { status = NymeaCore::instance()->deviceManager()->reconfigureDevice(deviceId, deviceParams); @@ -521,7 +521,7 @@ JsonReply *DeviceHandler::ReconfigureDevice(const QVariantMap ¶ms) status = NymeaCore::instance()->deviceManager()->reconfigureDevice(deviceId, deviceDescriptorId); } - if (status == DeviceManager::DeviceErrorAsync) { + if (status == Device::DeviceErrorAsync) { JsonReply *asyncReply = createAsyncReply("ReconfigureDevice"); connect(asyncReply, &JsonReply::finished, [this, deviceId](){ m_asynDeviceEditAdditions.remove(deviceId); }); m_asynDeviceEditAdditions.insert(deviceId, asyncReply); @@ -540,7 +540,7 @@ JsonReply *DeviceHandler::EditDevice(const QVariantMap ¶ms) qCDebug(dcJsonRpc()) << "Edit device" << deviceId << name; - DeviceManager::DeviceError status = NymeaCore::instance()->deviceManager()->editDevice(deviceId, name); + Device::DeviceError status = NymeaCore::instance()->deviceManager()->editDevice(deviceId, name); QVariantMap returns; returns.insert("deviceError", JsonTypes::deviceErrorToString(status)); @@ -555,7 +555,7 @@ JsonReply* DeviceHandler::RemoveConfiguredDevice(const QVariantMap ¶ms) // global removePolicy has priority if (params.contains("removePolicy")) { RuleEngine::RemovePolicy removePolicy = params.value("removePolicy").toString() == "RemovePolicyCascade" ? RuleEngine::RemovePolicyCascade : RuleEngine::RemovePolicyUpdate; - DeviceManager::DeviceError status = NymeaCore::instance()->removeConfiguredDevice(deviceId, removePolicy); + Device::DeviceError status = NymeaCore::instance()->removeConfiguredDevice(deviceId, removePolicy); returns.insert("deviceError", JsonTypes::deviceErrorToString(status)); return createReply(returns); } @@ -567,7 +567,7 @@ JsonReply* DeviceHandler::RemoveConfiguredDevice(const QVariantMap ¶ms) removePolicyList.insert(ruleId, policy); } - QPair > status = NymeaCore::instance()->removeConfiguredDevice(deviceId, removePolicyList); + QPair > status = NymeaCore::instance()->removeConfiguredDevice(deviceId, removePolicyList); returns.insert("deviceError", JsonTypes::deviceErrorToString(status.first)); if (!status.second.isEmpty()) { @@ -586,7 +586,7 @@ JsonReply *DeviceHandler::SetDeviceSettings(const QVariantMap ¶ms) QVariantMap returns; DeviceId deviceId = DeviceId(params.value("deviceId").toString()); ParamList settings = JsonTypes::unpackParams(params.value("settings").toList()); - DeviceManager::DeviceError status = NymeaCore::instance()->deviceManager()->setDeviceSettings(deviceId, settings); + Device::DeviceError status = NymeaCore::instance()->deviceManager()->setDeviceSettings(deviceId, settings); returns.insert("deviceError", JsonTypes::deviceErrorToString(status)); return createReply(returns); } @@ -636,16 +636,16 @@ JsonReply* DeviceHandler::GetStateValue(const QVariantMap ¶ms) const Device *device = NymeaCore::instance()->deviceManager()->findConfiguredDevice(DeviceId(params.value("deviceId").toString())); if (!device) { - returns.insert("deviceError", JsonTypes::deviceErrorToString(DeviceManager::DeviceErrorDeviceNotFound)); + returns.insert("deviceError", JsonTypes::deviceErrorToString(Device::DeviceErrorDeviceNotFound)); return createReply(returns); } StateTypeId stateTypeId = StateTypeId(params.value("stateTypeId").toString()); if (!device->hasState(stateTypeId)) { - returns.insert("deviceError", JsonTypes::deviceErrorToString(DeviceManager::DeviceErrorStateTypeNotFound)); + returns.insert("deviceError", JsonTypes::deviceErrorToString(Device::DeviceErrorStateTypeNotFound)); return createReply(returns); } - returns.insert("deviceError", JsonTypes::deviceErrorToString(DeviceManager::DeviceErrorNoError)); + returns.insert("deviceError", JsonTypes::deviceErrorToString(Device::DeviceErrorNoError)); returns.insert("value", device->state(stateTypeId).value()); return createReply(returns); } @@ -656,11 +656,11 @@ JsonReply *DeviceHandler::GetStateValues(const QVariantMap ¶ms) const Device *device = NymeaCore::instance()->deviceManager()->findConfiguredDevice(DeviceId(params.value("deviceId").toString())); if (!device) { - returns.insert("deviceError", JsonTypes::deviceErrorToString(DeviceManager::DeviceErrorDeviceNotFound)); + returns.insert("deviceError", JsonTypes::deviceErrorToString(Device::DeviceErrorDeviceNotFound)); return createReply(returns); } - returns.insert("deviceError", JsonTypes::deviceErrorToString(DeviceManager::DeviceErrorNoError)); + returns.insert("deviceError", JsonTypes::deviceErrorToString(Device::DeviceErrorNoError)); returns.insert("values", JsonTypes::packDeviceStates(device)); return createReply(returns); } @@ -733,13 +733,13 @@ void DeviceHandler::devicesDiscovered(const DeviceClassId &deviceClassId, const QVariantMap returns; returns.insert("deviceDescriptors", JsonTypes::packDeviceDescriptors(deviceDescriptors)); - returns.insert("deviceError", JsonTypes::deviceErrorToString(DeviceManager::DeviceErrorNoError)); + returns.insert("deviceError", JsonTypes::deviceErrorToString(Device::DeviceErrorNoError)); reply->setData(returns); reply->finished(); } -void DeviceHandler::deviceSetupFinished(Device *device, DeviceManager::DeviceError status) +void DeviceHandler::deviceSetupFinished(Device *device, Device::DeviceError status) { qCDebug(dcJsonRpc) << "Got a device setup finished" << device->name() << device->id(); if (!m_asynDeviceAdditions.contains(device->id())) { @@ -751,14 +751,14 @@ void DeviceHandler::deviceSetupFinished(Device *device, DeviceManager::DeviceErr QVariantMap returns; returns.insert("deviceError", JsonTypes::deviceErrorToString(status)); - if(status == DeviceManager::DeviceErrorNoError) { + if(status == Device::DeviceErrorNoError) { returns.insert("deviceId", device->id()); } reply->setData(returns); reply->finished(); } -void DeviceHandler::deviceReconfigurationFinished(Device *device, DeviceManager::DeviceError status) +void DeviceHandler::deviceReconfigurationFinished(Device *device, Device::DeviceError status) { qCDebug(dcJsonRpc) << "Got async device reconfiguration finished"; if (!m_asynDeviceEditAdditions.contains(device->id())) { @@ -772,7 +772,7 @@ void DeviceHandler::deviceReconfigurationFinished(Device *device, DeviceManager: reply->finished(); } -void DeviceHandler::pairingFinished(const PairingTransactionId &pairingTransactionId, DeviceManager::DeviceError status, const DeviceId &deviceId) +void DeviceHandler::pairingFinished(const PairingTransactionId &pairingTransactionId, Device::DeviceError status, const DeviceId &deviceId) { qCDebug(dcJsonRpc) << "Got pairing finished"; JsonReply *reply = m_asyncPairingRequests.take(pairingTransactionId); @@ -780,7 +780,7 @@ void DeviceHandler::pairingFinished(const PairingTransactionId &pairingTransacti return; } - if (status != DeviceManager::DeviceErrorNoError) { + if (status != Device::DeviceErrorNoError) { QVariantMap returns; returns.insert("deviceError", JsonTypes::deviceErrorToString(status)); reply->setData(returns); diff --git a/libnymea-core/jsonrpc/devicehandler.h b/libnymea-core/jsonrpc/devicehandler.h index c06a7bc7..7d8af31d 100644 --- a/libnymea-core/jsonrpc/devicehandler.h +++ b/libnymea-core/jsonrpc/devicehandler.h @@ -23,7 +23,7 @@ #define DEVICEHANDLER_H #include "jsonhandler.h" -#include "devicemanager.h" +#include "devices/devicemanager.h" namespace nymeaserver { @@ -80,11 +80,11 @@ private slots: void devicesDiscovered(const DeviceClassId &deviceClassId, const QList deviceDescriptors); - void deviceSetupFinished(Device *device, DeviceManager::DeviceError status); + void deviceSetupFinished(Device *device, Device::DeviceError status); - void deviceReconfigurationFinished(Device *device, DeviceManager::DeviceError status); + void deviceReconfigurationFinished(Device *device, Device::DeviceError status); - void pairingFinished(const PairingTransactionId &pairingTransactionId, DeviceManager::DeviceError status, const DeviceId &deviceId); + void pairingFinished(const PairingTransactionId &pairingTransactionId, Device::DeviceError status, const DeviceId &deviceId); private: // A cache for async replies diff --git a/libnymea-core/jsonrpc/eventhandler.cpp b/libnymea-core/jsonrpc/eventhandler.cpp index 430e698c..12c784a5 100644 --- a/libnymea-core/jsonrpc/eventhandler.cpp +++ b/libnymea-core/jsonrpc/eventhandler.cpp @@ -87,13 +87,13 @@ JsonReply* EventHandler::GetEventType(const QVariantMap ¶ms) const foreach (const DeviceClass &deviceClass, NymeaCore::instance()->deviceManager()->supportedDevices()) { foreach (const EventType &eventType, deviceClass.eventTypes()) { if (eventType.id() == eventTypeId) { - QVariantMap data = statusToReply(DeviceManager::DeviceErrorNoError); + QVariantMap data = statusToReply(Device::DeviceErrorNoError); data.insert("eventType", JsonTypes::packEventType(eventType, deviceClass.pluginId(), params.value("locale").toLocale())); return createReply(data); } } } - return createReply(statusToReply(DeviceManager::DeviceErrorEventTypeNotFound)); + return createReply(statusToReply(Device::DeviceErrorEventTypeNotFound)); } } diff --git a/libnymea-core/jsonrpc/jsonhandler.cpp b/libnymea-core/jsonrpc/jsonhandler.cpp index 1fe2a3a1..81093f90 100644 --- a/libnymea-core/jsonrpc/jsonhandler.cpp +++ b/libnymea-core/jsonrpc/jsonhandler.cpp @@ -173,9 +173,9 @@ JsonReply* JsonHandler::createAsyncReply(const QString &method) const /*! Returns the formated error map for the given \a status. * - * \sa DeviceManager::DeviceError + * \sa Device::DeviceError */ -QVariantMap JsonHandler::statusToReply(DeviceManager::DeviceError status) const +QVariantMap JsonHandler::statusToReply(Device::DeviceError status) const { QVariantMap returns; returns.insert("deviceError", JsonTypes::deviceErrorToString(status)); diff --git a/libnymea-core/jsonrpc/jsonhandler.h b/libnymea-core/jsonrpc/jsonhandler.h index 1111e452..bf6f099d 100644 --- a/libnymea-core/jsonrpc/jsonhandler.h +++ b/libnymea-core/jsonrpc/jsonhandler.h @@ -108,7 +108,7 @@ protected: JsonReply *createReply(const QVariantMap &data) const; JsonReply *createAsyncReply(const QString &method) const; - QVariantMap statusToReply(DeviceManager::DeviceError status) const; + QVariantMap statusToReply(Device::DeviceError status) const; QVariantMap statusToReply(RuleEngine::RuleError status) const; QVariantMap statusToReply(Logging::LoggingError status) const; QVariantMap statusToReply(NymeaConfiguration::ConfigurationError status) const; diff --git a/libnymea-core/jsonrpc/jsonrpcserver.cpp b/libnymea-core/jsonrpc/jsonrpcserver.cpp index d0a73216..6f34f682 100644 --- a/libnymea-core/jsonrpc/jsonrpcserver.cpp +++ b/libnymea-core/jsonrpc/jsonrpcserver.cpp @@ -40,12 +40,12 @@ #include "jsontypes.h" #include "jsonhandler.h" #include "nymeacore.h" -#include "devicemanager.h" -#include "plugin/deviceplugin.h" +#include "devices/devicemanager.h" +#include "devices/deviceplugin.h" +#include "devices/device.h" #include "types/deviceclass.h" -#include "plugin/device.h" -#include "rule.h" -#include "ruleengine.h" +#include "ruleengine/rule.h" +#include "ruleengine/ruleengine.h" #include "loggingcategories.h" #include "platform/platform.h" diff --git a/libnymea-core/jsonrpc/jsonrpcserver.h b/libnymea-core/jsonrpc/jsonrpcserver.h index 0730b3c0..3920f487 100644 --- a/libnymea-core/jsonrpc/jsonrpcserver.h +++ b/libnymea-core/jsonrpc/jsonrpcserver.h @@ -24,7 +24,7 @@ #include "jsonhandler.h" #include "transportinterface.h" -#include "usermanager.h" +#include "usermanager/usermanager.h" #include "types/deviceclass.h" #include "types/action.h" diff --git a/libnymea-core/jsonrpc/jsontypes.cpp b/libnymea-core/jsonrpc/jsontypes.cpp index 4c19bab5..089175de 100644 --- a/libnymea-core/jsonrpc/jsontypes.cpp +++ b/libnymea-core/jsonrpc/jsontypes.cpp @@ -50,14 +50,13 @@ #include "jsontypes.h" -#include "plugin/device.h" -#include "devicemanager.h" +#include "devices/device.h" +#include "devices/devicemanager.h" +#include "devices/deviceplugin.h" #include "nymeacore.h" -#include "ruleengine.h" +#include "ruleengine/ruleengine.h" #include "loggingcategories.h" #include "logging/logvaluetool.h" -#include "translator.h" -#include "plugin/deviceplugin.h" #include #include @@ -140,7 +139,7 @@ void JsonTypes::init() s_createMethod = enumToStrings(DeviceClass::staticMetaObject, "CreateMethod"); s_setupMethod = enumToStrings(DeviceClass::staticMetaObject, "SetupMethod"); s_removePolicy = enumToStrings(RuleEngine::staticMetaObject, "RemovePolicy"); - s_deviceError = enumToStrings(DeviceManager::staticMetaObject, "DeviceError"); + s_deviceError = enumToStrings(Device::staticMetaObject, "DeviceError"); s_ruleError = enumToStrings(RuleEngine::staticMetaObject, "RuleError"); s_loggingError = enumToStrings(Logging::staticMetaObject, "LoggingError"); s_loggingSource = enumToStrings(Logging::staticMetaObject, "LoggingSource"); @@ -512,7 +511,7 @@ QVariantMap JsonTypes::packEventType(const EventType &eventType, const PluginId QVariantMap variant; variant.insert("id", eventType.id().toString()); variant.insert("name", eventType.name()); - variant.insert("displayName", NymeaCore::instance()->deviceManager()->translator()->translate(pluginId, eventType.displayName(), locale)); + variant.insert("displayName", NymeaCore::instance()->deviceManager()->translate(pluginId, eventType.displayName(), locale)); variant.insert("index", eventType.index()); QVariantList paramTypes; @@ -562,7 +561,7 @@ QVariantMap JsonTypes::packActionType(const ActionType &actionType, const Plugin QVariantMap variantMap; variantMap.insert("id", actionType.id().toString()); variantMap.insert("name", actionType.name()); - variantMap.insert("displayName", NymeaCore::instance()->deviceManager()->translator()->translate(pluginId, actionType.displayName(), locale)); + variantMap.insert("displayName", NymeaCore::instance()->deviceManager()->translate(pluginId, actionType.displayName(), locale)); variantMap.insert("index", actionType.index()); QVariantList paramTypes; foreach (const ParamType ¶mType, actionType.paramTypes()) @@ -642,7 +641,7 @@ QVariantMap JsonTypes::packStateType(const StateType &stateType, const PluginId QVariantMap variantMap; variantMap.insert("id", stateType.id().toString()); variantMap.insert("name", stateType.name()); - variantMap.insert("displayName", NymeaCore::instance()->deviceManager()->translator()->translate(pluginId, stateType.displayName(), locale)); + variantMap.insert("displayName", NymeaCore::instance()->deviceManager()->translate(pluginId, stateType.displayName(), locale)); variantMap.insert("index", stateType.index()); variantMap.insert("type", basicTypeToString(stateType.type())); variantMap.insert("defaultValue", stateType.defaultValue()); @@ -736,7 +735,7 @@ QVariantMap JsonTypes::packParamType(const ParamType ¶mType, const PluginId QVariantMap variantMap; variantMap.insert("id", paramType.id().toString()); variantMap.insert("name", paramType.name()); - variantMap.insert("displayName", NymeaCore::instance()->deviceManager()->translator()->translate(pluginId, paramType.displayName(), locale)); + variantMap.insert("displayName", NymeaCore::instance()->deviceManager()->translate(pluginId, paramType.displayName(), locale)); variantMap.insert("type", basicTypeToString(paramType.type())); variantMap.insert("index", paramType.index()); @@ -777,7 +776,7 @@ QVariantMap JsonTypes::packVendor(const Vendor &vendor, const QLocale &locale) QVariantMap variantMap; variantMap.insert("id", vendor.id().toString()); variantMap.insert("name", vendor.name()); - variantMap.insert("displayName", NymeaCore::instance()->deviceManager()->translator()->translate(plugin->pluginId(), vendor.displayName(), locale)); + variantMap.insert("displayName", NymeaCore::instance()->deviceManager()->translate(plugin->pluginId(), vendor.displayName(), locale)); return variantMap; } @@ -787,7 +786,7 @@ QVariantMap JsonTypes::packDeviceClass(const DeviceClass &deviceClass, const QLo QVariantMap variant; variant.insert("id", deviceClass.id().toString()); variant.insert("name", deviceClass.name()); - variant.insert("displayName", NymeaCore::instance()->deviceManager()->translator()->translate(deviceClass.pluginId(), deviceClass.displayName(), locale)); + variant.insert("displayName", NymeaCore::instance()->deviceManager()->translate(deviceClass.pluginId(), deviceClass.displayName(), locale)); variant.insert("vendorId", deviceClass.vendorId().toString()); variant.insert("pluginId", deviceClass.pluginId().toString()); variant.insert("interfaces", deviceClass.interfaces()); @@ -833,7 +832,7 @@ QVariantMap JsonTypes::packPlugin(DevicePlugin *plugin, const QLocale &locale) QVariantMap pluginMap; pluginMap.insert("id", plugin->pluginId().toString()); pluginMap.insert("name", plugin->pluginName()); - pluginMap.insert("displayName", NymeaCore::instance()->deviceManager()->translator()->translate(plugin->pluginId(), plugin->pluginDisplayName(), locale)); + pluginMap.insert("displayName", NymeaCore::instance()->deviceManager()->translate(plugin->pluginId(), plugin->pluginDisplayName(), locale)); QVariantList params; foreach (const ParamType ¶m, plugin->configurationDescription()) diff --git a/libnymea-core/jsonrpc/jsontypes.h b/libnymea-core/jsonrpc/jsontypes.h index fcf31e93..cacb1636 100644 --- a/libnymea-core/jsonrpc/jsontypes.h +++ b/libnymea-core/jsonrpc/jsontypes.h @@ -23,12 +23,12 @@ #ifndef JSONTYPES_H #define JSONTYPES_H -#include "plugin/devicedescriptor.h" -#include "rule.h" -#include "devicemanager.h" -#include "ruleengine.h" +#include "devices/devicedescriptor.h" +#include "devices/devicemanager.h" +#include "ruleengine/rule.h" +#include "ruleengine/ruleengine.h" #include "nymeaconfiguration.h" -#include "usermanager.h" +#include "usermanager/usermanager.h" #include "types/deviceclass.h" #include "types/event.h" @@ -128,7 +128,7 @@ public: DECLARE_TYPE(unit, "Unit", Types, Unit) DECLARE_TYPE(createMethod, "CreateMethod", DeviceClass, CreateMethod) DECLARE_TYPE(setupMethod, "SetupMethod", DeviceClass, SetupMethod) - DECLARE_TYPE(deviceError, "DeviceError", DeviceManager, DeviceError) + DECLARE_TYPE(deviceError, "DeviceError", Device, DeviceError) DECLARE_TYPE(removePolicy, "RemovePolicy", RuleEngine, RemovePolicy) DECLARE_TYPE(ruleError, "RuleError", RuleEngine, RuleError) DECLARE_TYPE(loggingError, "LoggingError", Logging, LoggingError) diff --git a/libnymea-core/jsonrpc/ruleshandler.cpp b/libnymea-core/jsonrpc/ruleshandler.cpp index 3ef7ff61..c1bf8d00 100644 --- a/libnymea-core/jsonrpc/ruleshandler.cpp +++ b/libnymea-core/jsonrpc/ruleshandler.cpp @@ -54,7 +54,7 @@ #include "ruleshandler.h" #include "nymeacore.h" -#include "ruleengine.h" +#include "ruleengine/ruleengine.h" #include "loggingcategories.h" #include diff --git a/libnymea-core/jsonrpc/statehandler.cpp b/libnymea-core/jsonrpc/statehandler.cpp index 4b34641e..a25e2b52 100644 --- a/libnymea-core/jsonrpc/statehandler.cpp +++ b/libnymea-core/jsonrpc/statehandler.cpp @@ -67,13 +67,13 @@ JsonReply* StateHandler::GetStateType(const QVariantMap ¶ms) const foreach (const DeviceClass &deviceClass, NymeaCore::instance()->deviceManager()->supportedDevices()) { foreach (const StateType &stateType, deviceClass.stateTypes()) { if (stateType.id() == stateTypeId) { - QVariantMap data = statusToReply(DeviceManager::DeviceErrorNoError); + QVariantMap data = statusToReply(Device::DeviceErrorNoError); data.insert("stateType", JsonTypes::packStateType(stateType, deviceClass.pluginId(), params.value("locale").toLocale())); return createReply(data); } } } - return createReply(statusToReply(DeviceManager::DeviceErrorStateTypeNotFound)); + return createReply(statusToReply(Device::DeviceErrorStateTypeNotFound)); } } diff --git a/libnymea-core/libnymea-core.pro b/libnymea-core/libnymea-core.pro index c01ec338..d539ac5b 100644 --- a/libnymea-core/libnymea-core.pro +++ b/libnymea-core/libnymea-core.pro @@ -16,9 +16,11 @@ RESOURCES += $$top_srcdir/icons.qrc \ HEADERS += nymeacore.h \ - ruleengine.h \ - rule.h \ - stateevaluator.h \ + devices/devicemanagerimplementation.h \ + devices/translator.h \ + devices/stateevaluator.h \ + ruleengine/ruleengine.h \ + ruleengine/rule.h \ transportinterface.h \ nymeaconfiguration.h \ servermanager.h \ @@ -67,13 +69,13 @@ HEADERS += nymeacore.h \ networkmanager/networksettings.h \ networkmanager/networkconnection.h \ networkmanager/wirednetworkdevice.h \ - usermanager.h \ - tokeninfo.h \ + usermanager/usermanager.h \ + usermanager/tokeninfo.h \ + usermanager/pushbuttondbusservice.h \ certificategenerator.h \ cloud/awsconnector.h \ cloud/cloudmanager.h \ cloud/cloudnotifications.h \ - pushbuttondbusservice.h \ hardwaremanagerimplementation.h \ hardware/plugintimermanagerimplementation.h \ hardware/radio433/radio433brennenstuhl.h \ @@ -98,9 +100,11 @@ HEADERS += nymeacore.h \ jsonrpc/systemhandler.h SOURCES += nymeacore.cpp \ - ruleengine.cpp \ - rule.cpp \ - stateevaluator.cpp \ + devices/devicemanagerimplementation.cpp \ + devices/translator.cpp \ + devices/stateevaluator.cpp \ + ruleengine/ruleengine.cpp \ + ruleengine/rule.cpp \ transportinterface.cpp \ nymeaconfiguration.cpp \ servermanager.cpp \ @@ -147,13 +151,13 @@ SOURCES += nymeacore.cpp \ networkmanager/networksettings.cpp \ networkmanager/networkconnection.cpp \ networkmanager/wirednetworkdevice.cpp \ - usermanager.cpp \ - tokeninfo.cpp \ + usermanager/usermanager.cpp \ + usermanager/tokeninfo.cpp \ + usermanager/pushbuttondbusservice.cpp \ certificategenerator.cpp \ cloud/awsconnector.cpp \ cloud/cloudmanager.cpp \ cloud/cloudnotifications.cpp \ - pushbuttondbusservice.cpp \ hardwaremanagerimplementation.cpp \ hardware/plugintimermanagerimplementation.cpp \ hardware/radio433/radio433brennenstuhl.cpp \ diff --git a/libnymea-core/logging/logengine.h b/libnymea-core/logging/logengine.h index 3537c444..7115ecca 100644 --- a/libnymea-core/logging/logengine.h +++ b/libnymea-core/logging/logengine.h @@ -26,7 +26,7 @@ #include "logfilter.h" #include "types/event.h" #include "types/action.h" -#include "rule.h" +#include "ruleengine/rule.h" #include #include diff --git a/libnymea-core/nymeacore.cpp b/libnymea-core/nymeacore.cpp index 5ab176a1..102276f6 100644 --- a/libnymea-core/nymeacore.cpp +++ b/libnymea-core/nymeacore.cpp @@ -50,9 +50,9 @@ This signal is emitted when the \l{ParamList}{Params} of a \a device have been changed. */ -/*! \fn void nymeaserver::NymeaCore::actionExecuted(const ActionId &id, DeviceManager::DeviceError status); +/*! \fn void nymeaserver::NymeaCore::actionExecuted(const ActionId &id, Device::DeviceError status); This signal is emitted when the \l{Action} with the given \a id is finished. - The \a status of the \l{Action} execution will be described as \l{DeviceManager::DeviceError}{DeviceError}. + The \a status of the \l{Action} execution will be described as \l{Device::DeviceError}{DeviceError}. */ /*! \fn void nymeaserver::NymeaCore::devicesDiscovered(const DeviceClassId &deviceClassId, const QList deviceDescriptors); @@ -61,19 +61,19 @@ \sa DeviceManager::discoverDevices() */ -/*! \fn void nymeaserver::NymeaCore::deviceSetupFinished(Device *device, DeviceManager::DeviceError status); +/*! \fn void nymeaserver::NymeaCore::deviceSetupFinished(Device *device, Device::DeviceError status); This signal is emitted when the setup of a \a device is finished. The \a status parameter describes the - \l{DeviceManager::DeviceError}{DeviceError} that occurred. + \l{Device::DeviceError}{DeviceError} that occurred. */ -/*! \fn void nymeaserver::NymeaCore::deviceReconfigurationFinished(Device *device, DeviceManager::DeviceError status); +/*! \fn void nymeaserver::NymeaCore::deviceReconfigurationFinished(Device *device, Device::DeviceError status); This signal is emitted when the edit request of a \a device is finished. The \a status of the edit request will be - described as \l{DeviceManager::DeviceError}{DeviceError}. + described as \l{Device::DeviceError}{DeviceError}. */ -/*! \fn void nymeaserver::NymeaCore::pairingFinished(const PairingTransactionId &pairingTransactionId, DeviceManager::DeviceError status, const DeviceId &deviceId); +/*! \fn void nymeaserver::NymeaCore::pairingFinished(const PairingTransactionId &pairingTransactionId, Device::DeviceError status, const DeviceId &deviceId); The DeviceManager will emit a this Signal when the pairing of a \l{Device} with the \a deviceId and \a pairingTransactionId is finished. - The \a status of the pairing will be described as \l{DeviceManager::DeviceError}{DeviceError}. + The \a status of the pairing will be described as \l{Device::DeviceError}{DeviceError}. */ /*! \fn void nymeaserver::NymeaCore::ruleRemoved(const RuleId &ruleId); @@ -108,14 +108,14 @@ #include "loggingcategories.h" #include "platform/platform.h" #include "jsonrpc/jsonrpcserver.h" -#include "ruleengine.h" +#include "ruleengine/ruleengine.h" #include "networkmanager/networkmanager.h" #include "nymeasettings.h" #include "tagging/tagsstorage.h" #include "platform/platform.h" -#include "devicemanager.h" -#include "plugin/device.h" +#include "devices/devicemanagerimplementation.h" +#include "devices/device.h" #include "cloud/cloudnotifications.h" #include "cloud/cloudtransport.h" @@ -167,7 +167,7 @@ void NymeaCore::init() { m_hardwareManager = new HardwareManagerImplementation(m_platform, m_serverManager->mqttBroker(), this); qCDebug(dcApplication) << "Creating Device Manager (locale:" << m_configuration->locale() << ")"; - m_deviceManager = new DeviceManager(m_hardwareManager, m_configuration->locale(), this); + m_deviceManager = new DeviceManagerImplementation(m_hardwareManager, m_configuration->locale(), this); qCDebug(dcApplication) << "Creating Rule Engine"; m_ruleEngine = new RuleEngine(this); @@ -192,27 +192,27 @@ void NymeaCore::init() { connect(m_configuration, &NymeaConfiguration::serverNameChanged, m_serverManager, &ServerManager::setServerName); - connect(m_deviceManager, &DeviceManager::pluginConfigChanged, this, &NymeaCore::pluginConfigChanged); - connect(m_deviceManager, &DeviceManager::eventTriggered, this, &NymeaCore::gotEvent); - connect(m_deviceManager, &DeviceManager::deviceStateChanged, this, &NymeaCore::deviceStateChanged); - connect(m_deviceManager, &DeviceManager::deviceAdded, this, &NymeaCore::deviceAdded); - connect(m_deviceManager, &DeviceManager::deviceChanged, this, &NymeaCore::deviceChanged); - connect(m_deviceManager, &DeviceManager::deviceSettingChanged, this, &NymeaCore::deviceSettingChanged); - connect(m_deviceManager, &DeviceManager::deviceRemoved, this, &NymeaCore::deviceRemoved); - connect(m_deviceManager, &DeviceManager::deviceDisappeared, this, &NymeaCore::onDeviceDisappeared); - connect(m_deviceManager, &DeviceManager::actionExecutionFinished, this, &NymeaCore::actionExecutionFinished); - connect(m_deviceManager, &DeviceManager::devicesDiscovered, this, &NymeaCore::devicesDiscovered); - connect(m_deviceManager, &DeviceManager::deviceSetupFinished, this, &NymeaCore::deviceSetupFinished); - connect(m_deviceManager, &DeviceManager::deviceReconfigurationFinished, this, &NymeaCore::deviceReconfigurationFinished); - connect(m_deviceManager, &DeviceManager::pairingFinished, this, &NymeaCore::pairingFinished); - connect(m_deviceManager, &DeviceManager::loaded, this, &NymeaCore::deviceManagerLoaded); + connect(m_deviceManager, &DeviceManagerImplementation::pluginConfigChanged, this, &NymeaCore::pluginConfigChanged); + connect(m_deviceManager, &DeviceManagerImplementation::eventTriggered, this, &NymeaCore::gotEvent); + connect(m_deviceManager, &DeviceManagerImplementation::deviceStateChanged, this, &NymeaCore::deviceStateChanged); + connect(m_deviceManager, &DeviceManagerImplementation::deviceAdded, this, &NymeaCore::deviceAdded); + connect(m_deviceManager, &DeviceManagerImplementation::deviceChanged, this, &NymeaCore::deviceChanged); + connect(m_deviceManager, &DeviceManagerImplementation::deviceSettingChanged, this, &NymeaCore::deviceSettingChanged); + connect(m_deviceManager, &DeviceManagerImplementation::deviceRemoved, this, &NymeaCore::deviceRemoved); + connect(m_deviceManager, &DeviceManagerImplementation::deviceDisappeared, this, &NymeaCore::onDeviceDisappeared); + connect(m_deviceManager, &DeviceManagerImplementation::actionExecutionFinished, this, &NymeaCore::actionExecutionFinished); + connect(m_deviceManager, &DeviceManagerImplementation::devicesDiscovered, this, &NymeaCore::devicesDiscovered); + connect(m_deviceManager, &DeviceManagerImplementation::deviceSetupFinished, this, &NymeaCore::deviceSetupFinished); + connect(m_deviceManager, &DeviceManagerImplementation::deviceReconfigurationFinished, this, &NymeaCore::deviceReconfigurationFinished); + connect(m_deviceManager, &DeviceManagerImplementation::pairingFinished, this, &NymeaCore::pairingFinished); + connect(m_deviceManager, &DeviceManagerImplementation::loaded, this, &NymeaCore::deviceManagerLoaded); connect(m_ruleEngine, &RuleEngine::ruleAdded, this, &NymeaCore::ruleAdded); connect(m_ruleEngine, &RuleEngine::ruleRemoved, this, &NymeaCore::ruleRemoved); connect(m_ruleEngine, &RuleEngine::ruleConfigurationChanged, this, &NymeaCore::ruleConfigurationChanged); connect(m_timeManager, &TimeManager::dateTimeChanged, this, &NymeaCore::onDateTimeChanged); - connect(m_timeManager, &TimeManager::tick, m_deviceManager, &DeviceManager::timeTick); + connect(m_timeManager, &TimeManager::tick, m_deviceManager, &DeviceManagerImplementation::timeTick); m_logger->logSystemEvent(m_timeManager->currentDateTime(), true); } @@ -262,24 +262,24 @@ void NymeaCore::destroy() } /*! Removes a configured \l{Device} with the given \a deviceId and \a removePolicyList. */ -QPair > NymeaCore::removeConfiguredDevice(const DeviceId &deviceId, const QHash &removePolicyList) +QPair > NymeaCore::removeConfiguredDevice(const DeviceId &deviceId, const QHash &removePolicyList) { Device *device = m_deviceManager->findConfiguredDevice(deviceId); if (!device) { - return QPair > (DeviceManager::DeviceErrorDeviceNotFound, QList()); + return QPair > (Device::DeviceErrorDeviceNotFound, QList()); } // Check if this is a child device if (!device->parentId().isNull()) { qCWarning(dcDeviceManager) << "The device is a child of" << device->parentId().toString() << ". Please remove the parent device."; - return QPair > (DeviceManager::DeviceErrorDeviceIsChild, QList()); + return QPair > (Device::DeviceErrorDeviceIsChild, QList()); } // FIXME: Let's remove this for now. It will come back with more fine grained control, presumably introducing a RemoveMethod flag in the DeviceClass // if (device->autoCreated()) { // qCWarning(dcDeviceManager) << "This device has been auto-created and cannot be deleted manually."; -// return QPair >(DeviceManager::DeviceErrorCreationMethodNotSupported, {}); +// return QPair >(Device::DeviceErrorCreationMethodNotSupported, {}); // } // Check if this device has child devices @@ -326,7 +326,7 @@ QPair > NymeaCore::removeConfiguredDev if (!unhandledRules.isEmpty()) { qCWarning(dcDeviceManager) << "There are unhandled rules which depend on this device:\n" << unhandledRules; - return QPair > (DeviceManager::DeviceErrorDeviceInRule, unhandledRules); + return QPair > (Device::DeviceErrorDeviceInRule, unhandledRules); } // Update the rules... @@ -342,41 +342,41 @@ QPair > NymeaCore::removeConfiguredDev // remove the child devices foreach (Device *d, childDevices) { - DeviceManager::DeviceError removeError = m_deviceManager->removeConfiguredDevice(d->id()); - if (removeError == DeviceManager::DeviceErrorNoError) { + Device::DeviceError removeError = m_deviceManager->removeConfiguredDevice(d->id()); + if (removeError == Device::DeviceErrorNoError) { m_logger->removeDeviceLogs(d->id()); } } // delete the devices - DeviceManager::DeviceError removeError = m_deviceManager->removeConfiguredDevice(deviceId); - if (removeError == DeviceManager::DeviceErrorNoError) { + Device::DeviceError removeError = m_deviceManager->removeConfiguredDevice(deviceId); + if (removeError == Device::DeviceErrorNoError) { m_logger->removeDeviceLogs(deviceId); } - return QPair > (DeviceManager::DeviceErrorNoError, QList()); + return QPair > (Device::DeviceErrorNoError, QList()); } /*! Removes a configured \l{Device} with the given \a deviceId and \a removePolicy. */ -DeviceManager::DeviceError NymeaCore::removeConfiguredDevice(const DeviceId &deviceId, const RuleEngine::RemovePolicy &removePolicy) +Device::DeviceError NymeaCore::removeConfiguredDevice(const DeviceId &deviceId, const RuleEngine::RemovePolicy &removePolicy) { Device *device = m_deviceManager->findConfiguredDevice(deviceId); if (!device) { - return DeviceManager::DeviceErrorDeviceNotFound; + return Device::DeviceErrorDeviceNotFound; } // Check if this is a child device if (!device->parentId().isNull()) { qCWarning(dcDeviceManager) << "The device is a child of" << device->parentId().toString() << ". Please remove the parent device."; - return DeviceManager::DeviceErrorDeviceIsChild; + return Device::DeviceErrorDeviceIsChild; } // FIXME: Let's remove this for now. It will come back with more fine grained control, presumably introducing a RemoveMethod flag in the DeviceClass // if (device->autoCreated()) { // qCWarning(dcDeviceManager) << "This device has been auto-created and cannot be deleted manually."; -// return DeviceManager::DeviceErrorCreationMethodNotSupported; +// return Device::DeviceErrorCreationMethodNotSupported; // } // Check if this device has child devices @@ -417,15 +417,15 @@ DeviceManager::DeviceError NymeaCore::removeConfiguredDevice(const DeviceId &dev // remove the child devices foreach (Device *d, childDevices) { - DeviceManager::DeviceError removeError = m_deviceManager->removeConfiguredDevice(d->id()); - if (removeError == DeviceManager::DeviceErrorNoError) { + Device::DeviceError removeError = m_deviceManager->removeConfiguredDevice(d->id()); + if (removeError == Device::DeviceErrorNoError) { m_logger->removeDeviceLogs(d->id()); } } // delete the devices - DeviceManager::DeviceError removeError = m_deviceManager->removeConfiguredDevice(deviceId); - if (removeError == DeviceManager::DeviceErrorNoError) { + Device::DeviceError removeError = m_deviceManager->removeConfiguredDevice(deviceId); + if (removeError == Device::DeviceErrorNoError) { m_logger->removeDeviceLogs(deviceId); } @@ -434,12 +434,12 @@ DeviceManager::DeviceError NymeaCore::removeConfiguredDevice(const DeviceId &dev /*! Calls the metheod DeviceManager::executeAction(\a action). * \sa DeviceManager::executeAction(), */ -DeviceManager::DeviceError NymeaCore::executeAction(const Action &action) +Device::DeviceError NymeaCore::executeAction(const Action &action) { - DeviceManager::DeviceError ret = m_deviceManager->executeAction(action); - if (ret == DeviceManager::DeviceErrorNoError) { + Device::DeviceError ret = m_deviceManager->executeAction(action); + if (ret == Device::DeviceErrorNoError) { m_logger->logAction(action); - } else if (ret == DeviceManager::DeviceErrorAsync) { + } else if (ret == Device::DeviceErrorAsync) { m_pendingActions.insert(action.id(), action); } else { m_logger->logAction(action, Logging::LoggingLevelAlert, ret); @@ -534,25 +534,25 @@ void NymeaCore::executeRuleActions(const QList ruleActions) foreach (const Action &action, actions) { qCDebug(dcRuleEngine) << "Executing action" << action.actionTypeId() << action.params(); - DeviceManager::DeviceError status = executeAction(action); + Device::DeviceError status = executeAction(action); switch(status) { - case DeviceManager::DeviceErrorNoError: + case Device::DeviceErrorNoError: break; - case DeviceManager::DeviceErrorSetupFailed: + case Device::DeviceErrorSetupFailed: qCWarning(dcRuleEngine) << "Error executing action. Device setup failed."; break; - case DeviceManager::DeviceErrorAsync: + case Device::DeviceErrorAsync: qCDebug(dcRuleEngine) << "Executing asynchronous action."; break; - case DeviceManager::DeviceErrorInvalidParameter: + case Device::DeviceErrorInvalidParameter: qCWarning(dcRuleEngine) << "Error executing action. Invalid action parameter."; break; default: qCWarning(dcRuleEngine) << "Error executing action:" << status; } - // if (status != DeviceManager::DeviceErrorAsync) - // m_logger->logAction(action, status == DeviceManager::DeviceErrorNoError ? Logging::LoggingLevelInfo : Logging::LoggingLevelAlert, status); + // if (status != Device::DeviceErrorAsync) + // m_logger->logAction(action, status == Device::DeviceErrorNoError ? Logging::LoggingLevelInfo : Logging::LoggingLevelAlert, status); } } @@ -790,11 +790,11 @@ RestServer *NymeaCore::restServer() const return m_serverManager->restServer(); } -void NymeaCore::actionExecutionFinished(const ActionId &id, DeviceManager::DeviceError status) +void NymeaCore::actionExecutionFinished(const ActionId &id, Device::DeviceError status) { emit actionExecuted(id, status); Action action = m_pendingActions.take(id); - m_logger->logAction(action, status == DeviceManager::DeviceErrorNoError ? Logging::LoggingLevelInfo : Logging::LoggingLevelAlert, status); + m_logger->logAction(action, status == Device::DeviceErrorNoError ? Logging::LoggingLevelInfo : Logging::LoggingLevelAlert, status); } void NymeaCore::onDeviceDisappeared(const DeviceId &deviceId) @@ -838,15 +838,15 @@ void NymeaCore::onDeviceDisappeared(const DeviceId &deviceId) // remove the child devices foreach (Device *d, childDevices) { - DeviceManager::DeviceError removeError = m_deviceManager->removeConfiguredDevice(d->id()); - if (removeError == DeviceManager::DeviceErrorNoError) { + Device::DeviceError removeError = m_deviceManager->removeConfiguredDevice(d->id()); + if (removeError == Device::DeviceErrorNoError) { m_logger->removeDeviceLogs(d->id()); } } // delete the device - DeviceManager::DeviceError removeError = m_deviceManager->removeConfiguredDevice(deviceId); - if (removeError == DeviceManager::DeviceErrorNoError) { + Device::DeviceError removeError = m_deviceManager->removeConfiguredDevice(deviceId); + if (removeError == Device::DeviceErrorNoError) { m_logger->removeDeviceLogs(deviceId); } } diff --git a/libnymea-core/nymeacore.h b/libnymea-core/nymeacore.h index f12fcc7d..f05db29f 100644 --- a/libnymea-core/nymeacore.h +++ b/libnymea-core/nymeacore.h @@ -22,15 +22,16 @@ #ifndef NYMEACORE_H #define NYMEACORE_H -#include "rule.h" #include "types/event.h" #include "types/deviceclass.h" -#include "plugin/deviceplugin.h" -#include "plugin/devicedescriptor.h" +#include "devices/deviceplugin.h" +#include "devices/devicedescriptor.h" +#include "devices/devicemanagerimplementation.h" + +#include "ruleengine/rule.h" +#include "ruleengine/ruleengine.h" #include "logging/logengine.h" -#include "devicemanager.h" -#include "ruleengine.h" #include "servermanager.h" #include "cloud/cloudmanager.h" @@ -67,10 +68,10 @@ public: void destroy(); // Device handling - QPair >removeConfiguredDevice(const DeviceId &deviceId, const QHash &removePolicyList); - DeviceManager::DeviceError removeConfiguredDevice(const DeviceId &deviceId, const RuleEngine::RemovePolicy &removePolicy); + QPair >removeConfiguredDevice(const DeviceId &deviceId, const QHash &removePolicyList); + Device::DeviceError removeConfiguredDevice(const DeviceId &deviceId, const RuleEngine::RemovePolicy &removePolicy); - DeviceManager::DeviceError executeAction(const Action &action); + Device::DeviceError executeAction(const Action &action); void executeRuleActions(const QList ruleActions); @@ -104,12 +105,12 @@ signals: void deviceAdded(Device *device); void deviceChanged(Device *device); void deviceSettingChanged(const DeviceId deviceId, const ParamTypeId &settingParamTypeId, const QVariant &value); - void actionExecuted(const ActionId &id, DeviceManager::DeviceError status); + void actionExecuted(const ActionId &id, Device::DeviceError status); void devicesDiscovered(const DeviceClassId &deviceClassId, const QList deviceDescriptors); - void deviceSetupFinished(Device *device, DeviceManager::DeviceError status); - void deviceReconfigurationFinished(Device *device, DeviceManager::DeviceError status); - void pairingFinished(const PairingTransactionId &pairingTransactionId, DeviceManager::DeviceError status, const DeviceId &deviceId); + void deviceSetupFinished(Device *device, Device::DeviceError status); + void deviceReconfigurationFinished(Device *device, Device::DeviceError status); + void pairingFinished(const PairingTransactionId &pairingTransactionId, Device::DeviceError status, const DeviceId &deviceId); void ruleRemoved(const RuleId &ruleId); void ruleAdded(const Rule &rule); @@ -124,7 +125,7 @@ private: NymeaConfiguration *m_configuration; ServerManager *m_serverManager; - DeviceManager *m_deviceManager; + DeviceManagerImplementation *m_deviceManager; RuleEngine *m_ruleEngine; LogEngine *m_logger; TimeManager *m_timeManager; @@ -143,7 +144,7 @@ private: private slots: void gotEvent(const Event &event); void onDateTimeChanged(const QDateTime &dateTime); - void actionExecutionFinished(const ActionId &id, DeviceManager::DeviceError status); + void actionExecutionFinished(const ActionId &id, Device::DeviceError status); void onDeviceDisappeared(const DeviceId &deviceId); void deviceManagerLoaded(); diff --git a/libnymea-core/rule.cpp b/libnymea-core/ruleengine/rule.cpp similarity index 100% rename from libnymea-core/rule.cpp rename to libnymea-core/ruleengine/rule.cpp diff --git a/libnymea-core/rule.h b/libnymea-core/ruleengine/rule.h similarity index 98% rename from libnymea-core/rule.h rename to libnymea-core/ruleengine/rule.h index 6a688e6e..c1828383 100644 --- a/libnymea-core/rule.h +++ b/libnymea-core/ruleengine/rule.h @@ -25,7 +25,7 @@ #include "types/state.h" #include "types/ruleaction.h" #include "types/eventdescriptor.h" -#include "stateevaluator.h" +#include "devices/stateevaluator.h" #include "time/timedescriptor.h" #include diff --git a/libnymea-core/ruleengine.cpp b/libnymea-core/ruleengine/ruleengine.cpp similarity index 99% rename from libnymea-core/ruleengine.cpp rename to libnymea-core/ruleengine/ruleengine.cpp index 7efb028a..76f4e0b2 100644 --- a/libnymea-core/ruleengine.cpp +++ b/libnymea-core/ruleengine/ruleengine.cpp @@ -110,8 +110,8 @@ #include "types/eventdescriptor.h" #include "types/paramdescriptor.h" #include "nymeasettings.h" -#include "devicemanager.h" -#include "plugin/device.h" +#include "devices/devicemanager.h" +#include "devices/device.h" #include #include diff --git a/libnymea-core/ruleengine.h b/libnymea-core/ruleengine/ruleengine.h similarity index 99% rename from libnymea-core/ruleengine.h rename to libnymea-core/ruleengine/ruleengine.h index 21c20fdd..7917044c 100644 --- a/libnymea-core/ruleengine.h +++ b/libnymea-core/ruleengine/ruleengine.h @@ -25,7 +25,7 @@ #include "rule.h" #include "types/event.h" #include "types/deviceclass.h" -#include "stateevaluator.h" +#include "devices/stateevaluator.h" #include #include diff --git a/libnymea-core/servers/rest/deviceclassesresource.cpp b/libnymea-core/servers/rest/deviceclassesresource.cpp index 586edfab..2c110f04 100644 --- a/libnymea-core/servers/rest/deviceclassesresource.cpp +++ b/libnymea-core/servers/rest/deviceclassesresource.cpp @@ -74,12 +74,12 @@ HttpReply *DeviceClassesResource::proccessRequest(const HttpRequest &request, co DeviceClassId deviceClassId = DeviceClassId(urlTokens.at(3)); if (deviceClassId.isNull()) { qCWarning(dcRest) << "Could not parse DeviceClassId:" << urlTokens.at(3); - return createDeviceErrorReply(HttpReply::BadRequest, DeviceManager::DeviceErrorDeviceClassNotFound); + return createDeviceErrorReply(HttpReply::BadRequest, Device::DeviceErrorDeviceClassNotFound); } m_deviceClass = NymeaCore::instance()->deviceManager()->findDeviceClass(deviceClassId); if (!m_deviceClass.isValid()) { qCWarning(dcRest) << "DeviceClassId" << deviceClassId.toString() << "not found"; - return createDeviceErrorReply(HttpReply::NotFound, DeviceManager::DeviceErrorDeviceClassNotFound); + return createDeviceErrorReply(HttpReply::NotFound, Device::DeviceErrorDeviceClassNotFound); } } @@ -108,7 +108,7 @@ HttpReply *DeviceClassesResource::proccessGetRequest(const HttpRequest &request, vendorId = VendorId(request.urlQuery().queryItemValue("vendorId")); if (vendorId.isNull()) { qCWarning(dcRest) << "Could not parse VendorId:" << request.urlQuery().queryItemValue("vendorId"); - return createDeviceErrorReply(HttpReply::BadRequest, DeviceManager::DeviceErrorVendorNotFound); + return createDeviceErrorReply(HttpReply::BadRequest, Device::DeviceErrorVendorNotFound); } } } @@ -128,7 +128,7 @@ HttpReply *DeviceClassesResource::proccessGetRequest(const HttpRequest &request, ActionTypeId actionTypeId = ActionTypeId(urlTokens.at(5)); if (actionTypeId.isNull()) { qCWarning(dcRest) << "Could not parse ActionTypeId:" << urlTokens.at(5); - return createDeviceErrorReply(HttpReply::BadRequest, DeviceManager::DeviceErrorActionTypeNotFound); + return createDeviceErrorReply(HttpReply::BadRequest, Device::DeviceErrorActionTypeNotFound); } return getActionType(actionTypeId); } @@ -142,7 +142,7 @@ HttpReply *DeviceClassesResource::proccessGetRequest(const HttpRequest &request, StateTypeId stateTypeId = StateTypeId(urlTokens.at(5)); if (stateTypeId.isNull()) { qCWarning(dcRest) << "Could not parse StateTypeId:" << urlTokens.at(5); - return createDeviceErrorReply(HttpReply::BadRequest, DeviceManager::DeviceErrorStateTypeNotFound); + return createDeviceErrorReply(HttpReply::BadRequest, Device::DeviceErrorStateTypeNotFound); } return getStateType(stateTypeId); } @@ -156,7 +156,7 @@ HttpReply *DeviceClassesResource::proccessGetRequest(const HttpRequest &request, EventTypeId eventTypeId = EventTypeId(urlTokens.at(5)); if (eventTypeId.isNull()) { qCWarning(dcRest) << "Could not parse EventTypeId:" << urlTokens.at(5); - return createDeviceErrorReply(HttpReply::BadRequest, DeviceManager::DeviceErrorEventTypeNotFound); + return createDeviceErrorReply(HttpReply::BadRequest, Device::DeviceErrorEventTypeNotFound); } return getEventType(eventTypeId); } @@ -209,7 +209,7 @@ HttpReply *DeviceClassesResource::getActionType(const ActionTypeId &actionTypeId return reply; } } - return createDeviceErrorReply(HttpReply::NotFound, DeviceManager::DeviceErrorActionTypeNotFound); + return createDeviceErrorReply(HttpReply::NotFound, Device::DeviceErrorActionTypeNotFound); } HttpReply *DeviceClassesResource::getStateTypes() @@ -233,7 +233,7 @@ HttpReply *DeviceClassesResource::getStateType(const StateTypeId &stateTypeId) return reply; } } - return createDeviceErrorReply(HttpReply::NotFound, DeviceManager::DeviceErrorStateTypeNotFound); + return createDeviceErrorReply(HttpReply::NotFound, Device::DeviceErrorStateTypeNotFound); } HttpReply *DeviceClassesResource::getEventTypes() @@ -257,7 +257,7 @@ HttpReply *DeviceClassesResource::getEventType(const EventTypeId &eventTypeId) return reply; } } - return createDeviceErrorReply(HttpReply::NotFound, DeviceManager::DeviceErrorEventTypeNotFound); + return createDeviceErrorReply(HttpReply::NotFound, Device::DeviceErrorEventTypeNotFound); } HttpReply *DeviceClassesResource::getDiscoverdDevices(const ParamList &discoveryParams) @@ -265,15 +265,15 @@ HttpReply *DeviceClassesResource::getDiscoverdDevices(const ParamList &discovery qCDebug(dcRest) << "Discover devices for DeviceClass" << m_deviceClass.id(); qCDebug(dcRest) << discoveryParams; - DeviceManager::DeviceError status = NymeaCore::instance()->deviceManager()->discoverDevices(m_deviceClass.id(), discoveryParams); + Device::DeviceError status = NymeaCore::instance()->deviceManager()->discoverDevices(m_deviceClass.id(), discoveryParams); - if (status == DeviceManager::DeviceErrorAsync) { + if (status == Device::DeviceErrorAsync) { HttpReply *reply = createAsyncReply(); m_discoverRequests.insert(m_deviceClass.id(), reply); return reply; } - if (status != DeviceManager::DeviceErrorNoError) + if (status != Device::DeviceErrorNoError) return createDeviceErrorReply(HttpReply::InternalServerError, status); return createSuccessReply(); diff --git a/libnymea-core/servers/rest/deviceclassesresource.h b/libnymea-core/servers/rest/deviceclassesresource.h index aba8fb86..0ae4f8a3 100644 --- a/libnymea-core/servers/rest/deviceclassesresource.h +++ b/libnymea-core/servers/rest/deviceclassesresource.h @@ -23,6 +23,7 @@ #include #include +#include #include "jsonrpc/jsontypes.h" #include "restresource.h" @@ -33,7 +34,7 @@ namespace nymeaserver { class HttpRequest; -class DeviceClassesResource : public RestResource +class DeviceClassesResource: public RestResource { Q_OBJECT public: @@ -69,7 +70,6 @@ private: private slots: void devicesDiscovered(const DeviceClassId &deviceClassId, const QList deviceDescriptors); - }; } diff --git a/libnymea-core/servers/rest/devicesresource.cpp b/libnymea-core/servers/rest/devicesresource.cpp index 069db826..bf54585d 100644 --- a/libnymea-core/servers/rest/devicesresource.cpp +++ b/libnymea-core/servers/rest/devicesresource.cpp @@ -41,7 +41,6 @@ #include "servers/httprequest.h" #include "jsonrpc/jsontypes.h" #include "nymeacore.h" -#include "translator.h" #include @@ -80,12 +79,12 @@ HttpReply *DevicesResource::proccessRequest(const HttpRequest &request, const QS DeviceId deviceId = DeviceId(urlTokens.at(3)); if (deviceId.isNull()) { qCWarning(dcRest) << "Could not parse DeviceId:" << urlTokens.at(3); - return createDeviceErrorReply(HttpReply::BadRequest, DeviceManager::DeviceErrorDeviceNotFound); + return createDeviceErrorReply(HttpReply::BadRequest, Device::DeviceErrorDeviceNotFound); } m_device = NymeaCore::instance()->deviceManager()->findConfiguredDevice(deviceId); if (!m_device) { qCWarning(dcRest) << "Could find any device with DeviceId:" << urlTokens.at(3); - return createDeviceErrorReply(HttpReply::NotFound, DeviceManager::DeviceErrorDeviceNotFound); + return createDeviceErrorReply(HttpReply::NotFound, Device::DeviceErrorDeviceNotFound); } } @@ -135,12 +134,12 @@ HttpReply *DevicesResource::proccessGetRequest(const HttpRequest &request, const StateTypeId stateTypeId = StateTypeId(urlTokens.at(5)); if (stateTypeId.isNull()) { qCWarning(dcRest) << "Could not parse StateTypeId:" << urlTokens.at(5); - return createDeviceErrorReply(HttpReply::BadRequest, DeviceManager::DeviceErrorStateTypeNotFound); + return createDeviceErrorReply(HttpReply::BadRequest, Device::DeviceErrorStateTypeNotFound); } if (!m_device->hasState(stateTypeId)){ qCWarning(dcRest) << "This device has no StateTypeId:" << urlTokens.at(5); - return createDeviceErrorReply(HttpReply::NotFound, DeviceManager::DeviceErrorStateTypeNotFound); + return createDeviceErrorReply(HttpReply::NotFound, Device::DeviceErrorStateTypeNotFound); } return getDeviceStateValue(m_device, stateTypeId); } @@ -210,7 +209,7 @@ HttpReply *DevicesResource::proccessPostRequest(const HttpRequest &request, cons ActionTypeId actionTypeId = ActionTypeId(urlTokens.at(5)); if (actionTypeId.isNull()) { qCWarning(dcRest) << "Could not parse ActionTypeId:" << urlTokens.at(5); - return createDeviceErrorReply(HttpReply::BadRequest, DeviceManager::DeviceErrorActionTypeNotFound); + return createDeviceErrorReply(HttpReply::BadRequest, Device::DeviceErrorActionTypeNotFound); } bool found = false; DeviceClass deviceClass = NymeaCore::instance()->deviceManager()->findDeviceClass(m_device->deviceClassId()); @@ -222,7 +221,7 @@ HttpReply *DevicesResource::proccessPostRequest(const HttpRequest &request, cons } if (!found) { qCWarning(dcRest) << "Could not find ActionTypeId:" << actionTypeId.toString(); - return createDeviceErrorReply(HttpReply::NotFound, DeviceManager::DeviceErrorActionTypeNotFound); + return createDeviceErrorReply(HttpReply::NotFound, Device::DeviceErrorActionTypeNotFound); } return executeAction(m_device, actionTypeId, request.payload()); @@ -284,7 +283,7 @@ HttpReply *DevicesResource::removeDevice(Device *device, const QVariantMap ¶ // global removePolicy has priority if (params.contains("removePolicy")) { RuleEngine::RemovePolicy removePolicy = params.value("removePolicy").toString() == "RemovePolicyCascade" ? RuleEngine::RemovePolicyCascade : RuleEngine::RemovePolicyUpdate; - DeviceManager::DeviceError result = NymeaCore::instance()->removeConfiguredDevice(device->id(), removePolicy); + Device::DeviceError result = NymeaCore::instance()->removeConfiguredDevice(device->id(), removePolicy); return createDeviceErrorReply(HttpReply::Ok, result); } @@ -295,7 +294,7 @@ HttpReply *DevicesResource::removeDevice(Device *device, const QVariantMap ¶ removePolicyList.insert(ruleId, policy); } - QPair > status = NymeaCore::instance()->removeConfiguredDevice(device->id(), removePolicyList); + QPair > status = NymeaCore::instance()->removeConfiguredDevice(device->id(), removePolicyList); // if there are offending rules if (!status.second.isEmpty()) { @@ -314,7 +313,7 @@ HttpReply *DevicesResource::removeDevice(Device *device, const QVariantMap ¶ return reply; } - if (status.first == DeviceManager::DeviceErrorNoError) + if (status.first == Device::DeviceErrorNoError) return createDeviceErrorReply(HttpReply::Ok, status.first); return createDeviceErrorReply(HttpReply::BadRequest, status.first); @@ -338,14 +337,14 @@ HttpReply *DevicesResource::executeAction(Device *device, const ActionTypeId &ac Action action(actionTypeId, device->id()); action.setParams(actionParams); - DeviceManager::DeviceError status = NymeaCore::instance()->executeAction(action); - if (status == DeviceManager::DeviceErrorAsync) { + Device::DeviceError status = NymeaCore::instance()->executeAction(action); + if (status == Device::DeviceErrorAsync) { HttpReply *reply = createAsyncReply(); m_asyncActionExecutions.insert(action.id(), reply); return reply; } - if (status != DeviceManager::DeviceErrorNoError) + if (status != Device::DeviceErrorNoError) return createDeviceErrorReply(HttpReply::InternalServerError, status); return createDeviceErrorReply(HttpReply::Ok, status); @@ -361,14 +360,14 @@ HttpReply *DevicesResource::addConfiguredDevice(const QByteArray &payload) const DeviceClassId deviceClassId(params.value("deviceClassId").toString()); if (deviceClassId.isNull()) - return createDeviceErrorReply(HttpReply::BadRequest, DeviceManager::DeviceErrorDeviceClassNotFound); + return createDeviceErrorReply(HttpReply::BadRequest, Device::DeviceErrorDeviceClassNotFound); QString deviceName = params.value("name").toString(); DeviceId newDeviceId = DeviceId::createDeviceId(); ParamList deviceParams = JsonTypes::unpackParams(params.value("deviceParams").toList()); DeviceDescriptorId deviceDescriptorId(params.value("deviceDescriptorId").toString()); - DeviceManager::DeviceError status; + Device::DeviceError status; if (deviceDescriptorId.isNull()) { qCDebug(dcRest) << "Adding device" << deviceName << "with" << deviceParams; status = NymeaCore::instance()->deviceManager()->addConfiguredDevice(deviceClassId, deviceName, deviceParams, newDeviceId); @@ -376,14 +375,14 @@ HttpReply *DevicesResource::addConfiguredDevice(const QByteArray &payload) const qCDebug(dcRest) << "Adding discovered device" << deviceName << "with DeviceDescriptorId" << deviceDescriptorId.toString(); status = NymeaCore::instance()->deviceManager()->addConfiguredDevice(deviceClassId, deviceName, deviceDescriptorId, deviceParams, newDeviceId); } - if (status == DeviceManager::DeviceErrorAsync) { + if (status == Device::DeviceErrorAsync) { HttpReply *reply = createAsyncReply(); qCDebug(dcRest) << "Device setup async reply"; m_asyncDeviceAdditions.insert(newDeviceId, reply); return reply; } - if (status != DeviceManager::DeviceErrorNoError) + if (status != Device::DeviceErrorNoError) return createDeviceErrorReply(HttpReply::InternalServerError, status); QVariant result = JsonTypes::packDevice(NymeaCore::instance()->deviceManager()->findConfiguredDevice(newDeviceId)); @@ -401,9 +400,9 @@ HttpReply *DevicesResource::editDevice(const QByteArray &payload) const QVariantMap params = verification.second.toMap(); QString name = params.value("name").toString(); - DeviceManager::DeviceError status = NymeaCore::instance()->deviceManager()->editDevice(m_device->id(), name); + Device::DeviceError status = NymeaCore::instance()->deviceManager()->editDevice(m_device->id(), name); - if (status != DeviceManager::DeviceErrorNoError) + if (status != Device::DeviceErrorNoError) return createDeviceErrorReply(HttpReply::BadRequest, status); return createDeviceErrorReply(HttpReply::Ok, status); @@ -422,14 +421,14 @@ HttpReply *DevicesResource::pairDevice(const QByteArray &payload) const if (deviceClassId.isNull()) { qCWarning(dcRest) << "Could not find deviceClassId" << params.value("deviceClassId").toString(); - return createDeviceErrorReply(HttpReply::BadRequest, DeviceManager::DeviceErrorDeviceClassNotFound); + return createDeviceErrorReply(HttpReply::BadRequest, Device::DeviceErrorDeviceClassNotFound); } QString deviceName = params.value("name").toString(); qCDebug(dcRest) << "Pair device" << deviceName << "with deviceClassId" << deviceClassId.toString(); - DeviceManager::DeviceError status; + Device::DeviceError status; PairingTransactionId pairingTransactionId = PairingTransactionId::createPairingTransactionId(); if (params.contains("deviceDescriptorId")) { DeviceDescriptorId deviceDescriptorId(params.value("deviceDescriptorId").toString()); @@ -439,11 +438,11 @@ HttpReply *DevicesResource::pairDevice(const QByteArray &payload) const status = NymeaCore::instance()->deviceManager()->pairDevice(pairingTransactionId, deviceClassId, deviceName, deviceParams); } - if (status != DeviceManager::DeviceErrorNoError) + if (status != Device::DeviceErrorNoError) return createDeviceErrorReply(HttpReply::BadRequest, status); QVariantMap returns; - returns.insert("displayMessage", NymeaCore::instance()->deviceManager()->translator()->translate(deviceClass.pluginId(), deviceClass.pairingInfo(), NymeaCore::instance()->configuration()->locale())); + returns.insert("displayMessage", NymeaCore::instance()->deviceManager()->translate(deviceClass.pluginId(), deviceClass.pairingInfo(), NymeaCore::instance()->configuration()->locale())); returns.insert("pairingTransactionId", pairingTransactionId.toString()); returns.insert("setupMethod", JsonTypes::setupMethod().at(deviceClass.setupMethod())); HttpReply *reply = createSuccessReply(); @@ -462,19 +461,19 @@ HttpReply *DevicesResource::confirmPairDevice(const QByteArray &payload) const PairingTransactionId pairingTransactionId = PairingTransactionId(params.value("pairingTransactionId").toString()); QString secret = params.value("secret").toString(); - DeviceManager::DeviceError status = NymeaCore::instance()->deviceManager()->confirmPairing(pairingTransactionId, secret); + Device::DeviceError status = NymeaCore::instance()->deviceManager()->confirmPairing(pairingTransactionId, secret); - if (status == DeviceManager::DeviceErrorAsync) { + if (status == Device::DeviceErrorAsync) { HttpReply *reply = createAsyncReply(); qCDebug(dcRest) << "Confirm pairing async reply"; m_asyncPairingRequests.insert(pairingTransactionId, reply); return reply; } - if (status != DeviceManager::DeviceErrorNoError) + if (status != Device::DeviceErrorNoError) return createDeviceErrorReply(HttpReply::InternalServerError, status); - return createDeviceErrorReply(HttpReply::Ok, DeviceManager::DeviceErrorNoError); + return createDeviceErrorReply(HttpReply::Ok, Device::DeviceErrorNoError); } HttpReply *DevicesResource::reconfigureDevice(Device *device, const QByteArray &payload) const @@ -487,7 +486,7 @@ HttpReply *DevicesResource::reconfigureDevice(Device *device, const QByteArray & QVariantMap params = verification.second.toMap(); ParamList deviceParams = JsonTypes::unpackParams(params.value("deviceParams").toList()); - DeviceManager::DeviceError status; + Device::DeviceError status; DeviceDescriptorId deviceDescriptorId(params.value("deviceDescriptorId").toString()); if (deviceDescriptorId.isNull()) { qCDebug(dcRest) << "Reconfigure device with params:" << deviceParams; @@ -497,20 +496,20 @@ HttpReply *DevicesResource::reconfigureDevice(Device *device, const QByteArray & status = NymeaCore::instance()->deviceManager()->reconfigureDevice(device->id(), deviceDescriptorId); } - if (status == DeviceManager::DeviceErrorAsync) { + if (status == Device::DeviceErrorAsync) { HttpReply *reply = createAsyncReply(); qCDebug(dcRest) << "Device reconfiguration async reply"; m_asyncReconfigureDevice.insert(device, reply); return reply; } - if (status != DeviceManager::DeviceErrorNoError) + if (status != Device::DeviceErrorNoError) return createDeviceErrorReply(HttpReply::InternalServerError, status); - return createDeviceErrorReply(HttpReply::Ok, DeviceManager::DeviceErrorNoError); + return createDeviceErrorReply(HttpReply::Ok, Device::DeviceErrorNoError); } -void DevicesResource::actionExecuted(const ActionId &actionId, DeviceManager::DeviceError status) +void DevicesResource::actionExecuted(const ActionId &actionId, Device::DeviceError status) { if (!m_asyncActionExecutions.contains(actionId)) return; // Not the action we are waiting for. @@ -525,7 +524,7 @@ void DevicesResource::actionExecuted(const ActionId &actionId, DeviceManager::De HttpReply *reply = m_asyncActionExecutions.take(actionId); reply->setHeader(HttpReply::ContentTypeHeader, "application/json; charset=\"utf-8\";"); - if (status == DeviceManager::DeviceErrorNoError) { + if (status == Device::DeviceErrorNoError) { qCDebug(dcRest) << "Action execution finished successfully"; reply->setHttpStatusCode(HttpReply::Ok); reply->setPayload(QJsonDocument::fromVariant(response).toJson()); @@ -540,7 +539,7 @@ void DevicesResource::actionExecuted(const ActionId &actionId, DeviceManager::De reply->finished(); } -void DevicesResource::deviceSetupFinished(Device *device, DeviceManager::DeviceError status) +void DevicesResource::deviceSetupFinished(Device *device, Device::DeviceError status) { if (!m_asyncDeviceAdditions.contains(device->id())) return; // Not the device we are waiting for. @@ -555,7 +554,7 @@ void DevicesResource::deviceSetupFinished(Device *device, DeviceManager::DeviceE HttpReply *reply = m_asyncDeviceAdditions.take(device->id()); reply->setHeader(HttpReply::ContentTypeHeader, "application/json; charset=\"utf-8\";"); - if (status == DeviceManager::DeviceErrorNoError) { + if (status == Device::DeviceErrorNoError) { qCDebug(dcRest) << "Device setup finished successfully"; reply->setHttpStatusCode(HttpReply::Ok); reply->setPayload(QJsonDocument::fromVariant(response).toJson()); @@ -571,7 +570,7 @@ void DevicesResource::deviceSetupFinished(Device *device, DeviceManager::DeviceE reply->finished(); } -void DevicesResource::deviceReconfigurationFinished(Device *device, DeviceManager::DeviceError status) +void DevicesResource::deviceReconfigurationFinished(Device *device, Device::DeviceError status) { if (!m_asyncReconfigureDevice.contains(device)) return; // Not the device we are waiting for. @@ -586,7 +585,7 @@ void DevicesResource::deviceReconfigurationFinished(Device *device, DeviceManage HttpReply *reply = m_asyncReconfigureDevice.take(device); reply->setHeader(HttpReply::ContentTypeHeader, "application/json; charset=\"utf-8\";"); - if (status == DeviceManager::DeviceErrorNoError) { + if (status == Device::DeviceErrorNoError) { qCDebug(dcRest) << "Device reconfiguration finished successfully"; reply->setHttpStatusCode(HttpReply::Ok); reply->setPayload(QJsonDocument::fromVariant(response).toJson()); @@ -599,7 +598,7 @@ void DevicesResource::deviceReconfigurationFinished(Device *device, DeviceManage reply->finished(); } -void DevicesResource::pairingFinished(const PairingTransactionId &pairingTransactionId, DeviceManager::DeviceError status, const DeviceId &deviceId) +void DevicesResource::pairingFinished(const PairingTransactionId &pairingTransactionId, Device::DeviceError status, const DeviceId &deviceId) { if (!m_asyncPairingRequests.contains(pairingTransactionId)) return; // Not the device pairing we are waiting for. @@ -613,7 +612,7 @@ void DevicesResource::pairingFinished(const PairingTransactionId &pairingTransac } HttpReply *reply = m_asyncPairingRequests.take(pairingTransactionId); - if (status != DeviceManager::DeviceErrorNoError) { + if (status != Device::DeviceErrorNoError) { qCDebug(dcRest) << "Pairing device finished with error."; reply->setHeader(HttpReply::ContentTypeHeader, "application/json; charset=\"utf-8\";"); reply->setHttpStatusCode(HttpReply::InternalServerError); diff --git a/libnymea-core/servers/rest/devicesresource.h b/libnymea-core/servers/rest/devicesresource.h index 6f35bb4d..aeee5850 100644 --- a/libnymea-core/servers/rest/devicesresource.h +++ b/libnymea-core/servers/rest/devicesresource.h @@ -23,6 +23,7 @@ #include #include +#include #include "jsonrpc/jsontypes.h" #include "restresource.h" @@ -36,7 +37,7 @@ class DevicesResource: public RestResource { Q_OBJECT public: - explicit DevicesResource(QObject *parent = 0); + explicit DevicesResource(QObject *parent = nullptr); QString name() const override; @@ -77,10 +78,10 @@ private: HttpReply *reconfigureDevice(Device *device, const QByteArray &payload) const; private slots: - void actionExecuted(const ActionId &actionId, DeviceManager::DeviceError status); - void deviceSetupFinished(Device *device, DeviceManager::DeviceError status); - void deviceReconfigurationFinished(Device *device, DeviceManager::DeviceError status); - void pairingFinished(const PairingTransactionId &pairingTransactionId, DeviceManager::DeviceError status, const DeviceId &deviceId); + void actionExecuted(const ActionId &actionId, Device::DeviceError status); + void deviceSetupFinished(Device *device, Device::DeviceError status); + void deviceReconfigurationFinished(Device *device, Device::DeviceError status); + void pairingFinished(const PairingTransactionId &pairingTransactionId, Device::DeviceError status, const DeviceId &deviceId); }; } diff --git a/libnymea-core/servers/rest/pluginsresource.cpp b/libnymea-core/servers/rest/pluginsresource.cpp index 66b16257..e99b2973 100644 --- a/libnymea-core/servers/rest/pluginsresource.cpp +++ b/libnymea-core/servers/rest/pluginsresource.cpp @@ -74,7 +74,7 @@ HttpReply *PluginsResource::proccessRequest(const HttpRequest &request, const QS m_pluginId = PluginId(urlTokens.at(3)); if (m_pluginId.isNull()) { qCWarning(dcRest) << "Could not parse PluginId:" << urlTokens.at(3); - return createDeviceErrorReply(HttpReply::BadRequest, DeviceManager::DeviceErrorPluginNotFound); + return createDeviceErrorReply(HttpReply::BadRequest, Device::DeviceErrorPluginNotFound); } } @@ -154,7 +154,7 @@ HttpReply *PluginsResource::getPlugin(const PluginId &pluginId) const return reply; } } - return createDeviceErrorReply(HttpReply::NotFound, DeviceManager::DeviceErrorPluginNotFound); + return createDeviceErrorReply(HttpReply::NotFound, Device::DeviceErrorPluginNotFound); } HttpReply *PluginsResource::getPluginConfiguration(const PluginId &pluginId) const @@ -164,7 +164,7 @@ HttpReply *PluginsResource::getPluginConfiguration(const PluginId &pluginId) con DevicePlugin *plugin = 0; plugin = findPlugin(pluginId); if (!plugin) - return createDeviceErrorReply(HttpReply::NotFound, DeviceManager::DeviceErrorPluginNotFound); + return createDeviceErrorReply(HttpReply::NotFound, Device::DeviceErrorPluginNotFound); QVariantList configurationParamsList; foreach (const Param ¶m, plugin->configuration()) { @@ -182,7 +182,7 @@ HttpReply *PluginsResource::setPluginConfiguration(const PluginId &pluginId, con DevicePlugin *plugin = 0; plugin = findPlugin(pluginId); if (!plugin) - return createDeviceErrorReply(HttpReply::NotFound, DeviceManager::DeviceErrorPluginNotFound); + return createDeviceErrorReply(HttpReply::NotFound, Device::DeviceErrorPluginNotFound); qCDebug(dcRest) << "Set configuration of plugin with id" << pluginId.toString(); @@ -193,9 +193,9 @@ HttpReply *PluginsResource::setPluginConfiguration(const PluginId &pluginId, con QVariantList configuration = verification.second.toList(); ParamList pluginParams = JsonTypes::unpackParams(configuration); qCDebug(dcRest) << pluginParams; - DeviceManager::DeviceError result = NymeaCore::instance()->deviceManager()->setPluginConfig(pluginId, pluginParams); + Device::DeviceError result = NymeaCore::instance()->deviceManager()->setPluginConfig(pluginId, pluginParams); - if (result != DeviceManager::DeviceErrorNoError) + if (result != Device::DeviceErrorNoError) return createDeviceErrorReply(HttpReply::BadRequest, result); return createDeviceErrorReply(HttpReply::Ok, result); diff --git a/libnymea-core/servers/rest/restresource.cpp b/libnymea-core/servers/rest/restresource.cpp index ddecae98..08cf1c24 100644 --- a/libnymea-core/servers/rest/restresource.cpp +++ b/libnymea-core/servers/rest/restresource.cpp @@ -60,7 +60,7 @@ #include "restresource.h" #include "servers/httprequest.h" #include "loggingcategories.h" -#include "devicemanager.h" +#include "devices/devicemanager.h" #include #include @@ -107,7 +107,7 @@ HttpReply *RestResource::createErrorReply(const HttpReply::HttpStatusCode &statu } /*! Returns the pointer to a new created error \l{HttpReply} initialized with the given \a statusCode, \l{HttpReply::TypeSync} and the \a deviceError. */ -HttpReply *RestResource::createDeviceErrorReply(const HttpReply::HttpStatusCode &statusCode, const DeviceManager::DeviceError &deviceError) +HttpReply *RestResource::createDeviceErrorReply(const HttpReply::HttpStatusCode &statusCode, const Device::DeviceError &deviceError) { HttpReply *reply = new HttpReply(statusCode, HttpReply::TypeSync); QVariantMap response; diff --git a/libnymea-core/servers/rest/restresource.h b/libnymea-core/servers/rest/restresource.h index 8a7a2450..474568ea 100644 --- a/libnymea-core/servers/rest/restresource.h +++ b/libnymea-core/servers/rest/restresource.h @@ -46,7 +46,7 @@ public: static HttpReply *createSuccessReply(); static HttpReply *createCorsSuccessReply(); static HttpReply *createErrorReply(const HttpReply::HttpStatusCode &statusCode); - static HttpReply *createDeviceErrorReply(const HttpReply::HttpStatusCode &statusCode, const DeviceManager::DeviceError &deviceError); + static HttpReply *createDeviceErrorReply(const HttpReply::HttpStatusCode &statusCode, const Device::DeviceError &deviceError); static HttpReply *createRuleErrorReply(const HttpReply::HttpStatusCode &statusCode, const RuleEngine::RuleError &ruleError); static HttpReply *createLoggingErrorReply(const HttpReply::HttpStatusCode &statusCode, const Logging::LoggingError &loggingError); static HttpReply *createAsyncReply(); diff --git a/libnymea-core/servers/rest/vendorsresource.cpp b/libnymea-core/servers/rest/vendorsresource.cpp index 2194be13..a908dd04 100644 --- a/libnymea-core/servers/rest/vendorsresource.cpp +++ b/libnymea-core/servers/rest/vendorsresource.cpp @@ -72,7 +72,7 @@ HttpReply *VendorsResource::proccessRequest(const HttpRequest &request, const QS m_vendorId = VendorId(urlTokens.at(3)); if (m_vendorId.isNull()) { qCWarning(dcRest) << "Could not parse VendorId:" << urlTokens.at(3); - return createDeviceErrorReply(HttpReply::BadRequest, DeviceManager::DeviceErrorVendorNotFound); + return createDeviceErrorReply(HttpReply::BadRequest, Device::DeviceErrorVendorNotFound); } } @@ -129,7 +129,7 @@ HttpReply *VendorsResource::getVendor(const VendorId &vendorId) const return reply; } } - return createDeviceErrorReply(HttpReply::NotFound, DeviceManager::DeviceErrorVendorNotFound); + return createDeviceErrorReply(HttpReply::NotFound, Device::DeviceErrorVendorNotFound); } } diff --git a/libnymea-core/tagging/tagsstorage.cpp b/libnymea-core/tagging/tagsstorage.cpp index 72ecdd4a..6400990b 100644 --- a/libnymea-core/tagging/tagsstorage.cpp +++ b/libnymea-core/tagging/tagsstorage.cpp @@ -19,8 +19,8 @@ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #include "tagsstorage.h" -#include "devicemanager.h" -#include "ruleengine.h" +#include "devices/devicemanager.h" +#include "ruleengine/ruleengine.h" #include "nymeasettings.h" namespace nymeaserver { diff --git a/libnymea-core/pushbuttondbusservice.cpp b/libnymea-core/usermanager/pushbuttondbusservice.cpp similarity index 100% rename from libnymea-core/pushbuttondbusservice.cpp rename to libnymea-core/usermanager/pushbuttondbusservice.cpp diff --git a/libnymea-core/pushbuttondbusservice.h b/libnymea-core/usermanager/pushbuttondbusservice.h similarity index 100% rename from libnymea-core/pushbuttondbusservice.h rename to libnymea-core/usermanager/pushbuttondbusservice.h diff --git a/libnymea-core/tokeninfo.cpp b/libnymea-core/usermanager/tokeninfo.cpp similarity index 100% rename from libnymea-core/tokeninfo.cpp rename to libnymea-core/usermanager/tokeninfo.cpp diff --git a/libnymea-core/tokeninfo.h b/libnymea-core/usermanager/tokeninfo.h similarity index 100% rename from libnymea-core/tokeninfo.h rename to libnymea-core/usermanager/tokeninfo.h diff --git a/libnymea-core/usermanager.cpp b/libnymea-core/usermanager/usermanager.cpp similarity index 100% rename from libnymea-core/usermanager.cpp rename to libnymea-core/usermanager/usermanager.cpp diff --git a/libnymea-core/usermanager.h b/libnymea-core/usermanager/usermanager.h similarity index 100% rename from libnymea-core/usermanager.h rename to libnymea-core/usermanager/usermanager.h diff --git a/libnymea/devicemanager.h b/libnymea/devicemanager.h deleted file mode 100644 index feec853e..00000000 --- a/libnymea/devicemanager.h +++ /dev/null @@ -1,211 +0,0 @@ -/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * - * * - * Copyright (C) 2015-2018 Simon Stürz * - * Copyright (C) 2014 Michael Zanetti * - * * - * This file is part of nymea. * - * * - * This library is free software; you can redistribute it and/or * - * modify it under the terms of the GNU Lesser General Public * - * License as published by the Free Software Foundation; either * - * version 2.1 of the License, or (at your option) any later version. * - * * - * This library is distributed in the hope that it will be useful, * - * but WITHOUT ANY WARRANTY; without even the implied warranty of * - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * - * Lesser General Public License for more details. * - * * - * You should have received a copy of the GNU Lesser General Public * - * License along with this library; If not, see * - * . * - * * - * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ - -#ifndef DEVICEMANAGER_H -#define DEVICEMANAGER_H - -#include "libnymea.h" - -#include "plugin/device.h" -#include "plugin/devicedescriptor.h" - -#include "types/deviceclass.h" -#include "types/interface.h" -#include "types/event.h" -#include "types/action.h" -#include "types/vendor.h" - -#include -#include -#include -#include -#include - -#include "hardwaremanager.h" - -class Device; -class DevicePlugin; -class DevicePairingInfo; -class HardwareManager; -class Translator; - -class LIBNYMEA_EXPORT DeviceManager : public QObject -{ - Q_OBJECT - - friend class DevicePlugin; - -public: - enum DeviceError { - DeviceErrorNoError, - DeviceErrorPluginNotFound, - DeviceErrorVendorNotFound, - DeviceErrorDeviceNotFound, - DeviceErrorDeviceClassNotFound, - DeviceErrorActionTypeNotFound, - DeviceErrorStateTypeNotFound, - DeviceErrorEventTypeNotFound, - DeviceErrorDeviceDescriptorNotFound, - DeviceErrorMissingParameter, - DeviceErrorInvalidParameter, - DeviceErrorSetupFailed, - DeviceErrorDuplicateUuid, - DeviceErrorCreationMethodNotSupported, - DeviceErrorSetupMethodNotSupported, - DeviceErrorHardwareNotAvailable, - DeviceErrorHardwareFailure, - DeviceErrorAuthentificationFailure, - DeviceErrorAsync, - DeviceErrorDeviceInUse, - DeviceErrorDeviceInRule, - DeviceErrorDeviceIsChild, - DeviceErrorPairingTransactionIdNotFound, - DeviceErrorParameterNotWritable - }; - Q_ENUM(DeviceError) - - enum DeviceSetupStatus { - DeviceSetupStatusSuccess, - DeviceSetupStatusFailure, - DeviceSetupStatusAsync - }; - Q_ENUM(DeviceSetupStatus) - - explicit DeviceManager(HardwareManager *hardwareManager, const QLocale &locale, QObject *parent = nullptr); - ~DeviceManager(); - - static QStringList pluginSearchDirs(); - static QList pluginsMetadata(); - void registerStaticPlugin(DevicePlugin* plugin, const QJsonObject &metaData); - - HardwareManager *hardwareManager() const; - - QList plugins() const; - DevicePlugin* plugin(const PluginId &id) const; - DeviceError setPluginConfig(const PluginId &pluginId, const ParamList &pluginConfig); - - QList supportedVendors() const; - Interfaces supportedInterfaces() const; - Interface findInterface(const QString &name); - QList supportedDevices(const VendorId &vendorId = VendorId()) const; - - DeviceError discoverDevices(const DeviceClassId &deviceClassId, const ParamList ¶ms); - - QList configuredDevices() const; - DeviceError addConfiguredDevice(const DeviceClassId &deviceClassId, const QString &name, const ParamList ¶ms, const DeviceId id = DeviceId::createDeviceId()); - DeviceError addConfiguredDevice(const DeviceClassId &deviceClassId, const QString &name, const DeviceDescriptorId &deviceDescriptorId, const ParamList ¶ms = ParamList(), const DeviceId &deviceId = DeviceId::createDeviceId()); - - DeviceError reconfigureDevice(const DeviceId &deviceId, const ParamList ¶ms, bool fromDiscoveryOrAuto = false); - DeviceError reconfigureDevice(const DeviceId &deviceId, const DeviceDescriptorId &deviceDescriptorId); - - DeviceError editDevice(const DeviceId &deviceId, const QString &name); - DeviceError setDeviceSettings(const DeviceId &deviceId, const ParamList &settings); - - DeviceError pairDevice(const PairingTransactionId &pairingTransactionId, const DeviceClassId &deviceClassId, const QString &name, const ParamList ¶ms); - DeviceError pairDevice(const PairingTransactionId &pairingTransactionId, const DeviceClassId &deviceClassId, const QString &name, const DeviceDescriptorId &deviceDescriptorId); - DeviceError confirmPairing(const PairingTransactionId &pairingTransactionId, const QString &secret = QString()); - - DeviceError removeConfiguredDevice(const DeviceId &deviceId); - - Device* findConfiguredDevice(const DeviceId &id) const; - QList findConfiguredDevices(const DeviceClassId &deviceClassId) const; - QList findConfiguredDevices(const QString &interface) const; - QList findChildDevices(const DeviceId &id) const; - DeviceClass findDeviceClass(const DeviceClassId &deviceClassId) const; - - DeviceError verifyParams(const QList paramTypes, ParamList ¶ms, bool requireAll = true); - DeviceError verifyParam(const QList paramTypes, const Param ¶m); - DeviceError verifyParam(const ParamType ¶mType, const Param ¶m); - - Translator* translator() const; -signals: - void loaded(); - void pluginConfigChanged(const PluginId &id, const ParamList &config); - void eventTriggered(const Event &event); - void deviceStateChanged(Device *device, const StateTypeId &stateTypeId, const QVariant &value); - void deviceRemoved(const DeviceId &deviceId); - void deviceDisappeared(const DeviceId &deviceId); - void deviceAdded(Device *device); - void deviceChanged(Device *device); - void deviceSettingChanged(const DeviceId deviceId, const ParamTypeId &settingParamTypeId, const QVariant &value); - void devicesDiscovered(const DeviceClassId &deviceClassId, const QList &devices); - void deviceSetupFinished(Device *device, DeviceError status); - void deviceReconfigurationFinished(Device *device, DeviceError status); - void pairingFinished(const PairingTransactionId &pairingTransactionId, DeviceError status, const DeviceId &deviceId = DeviceId()); - void actionExecutionFinished(const ActionId &actionId, DeviceManager::DeviceError status); - -public slots: - DeviceError executeAction(const Action &action); - void timeTick(); - -private slots: - void loadPlugins(); - void loadPlugin(DevicePlugin *pluginIface); - void loadConfiguredDevices(); - void storeConfiguredDevices(); - void startMonitoringAutoDevices(); - void slotDevicesDiscovered(const DeviceClassId &deviceClassId, const QList deviceDescriptors); - void slotDeviceSetupFinished(Device *device, DeviceManager::DeviceSetupStatus status); - void slotPairingFinished(const PairingTransactionId &pairingTransactionId, DeviceManager::DeviceSetupStatus status); - void onAutoDevicesAppeared(const DeviceClassId &deviceClassId, const QList &deviceDescriptors); - void onAutoDeviceDisappeared(const DeviceId &deviceId); - void onLoaded(); - void cleanupDeviceStateCache(); - - // Only connect this to Devices. It will query the sender() - void slotDeviceStateValueChanged(const StateTypeId &stateTypeId, const QVariant &value); - void slotDeviceSettingChanged(const ParamTypeId ¶mTypeId, const QVariant &value); - -private: - bool verifyPluginMetadata(const QJsonObject &data); - DeviceError addConfiguredDeviceInternal(const DeviceClassId &deviceClassId, const QString &name, const ParamList ¶ms, const DeviceId id = DeviceId::createDeviceId()); - DeviceSetupStatus setupDevice(Device *device); - void postSetupDevice(Device *device); - void storeDeviceStates(Device *device); - void loadDeviceStates(Device *device); - -private: - HardwareManager *m_hardwareManager; - - QLocale m_locale; - Translator *m_translator = nullptr; - QHash m_supportedVendors; - QHash m_supportedInterfaces; - QHash > m_vendorDeviceMap; - QHash m_supportedDevices; - QHash m_configuredDevices; - QHash m_discoveredDevices; - - QHash m_devicePlugins; - - QHash m_pairingsJustAdd; - QHash m_pairingsDiscovery; - - QList m_asyncDeviceReconfiguration; - QList m_discoveringPlugins; -}; - -Q_DECLARE_METATYPE(DeviceManager::DeviceError) -Q_DECLARE_METATYPE(DeviceManager::DeviceSetupStatus) - -#endif // DEVICEMANAGER_H diff --git a/libnymea/plugin/device.cpp b/libnymea/devices/device.cpp similarity index 72% rename from libnymea/plugin/device.cpp rename to libnymea/devices/device.cpp index 76b8107a..1de3160e 100644 --- a/libnymea/plugin/device.cpp +++ b/libnymea/devices/device.cpp @@ -34,32 +34,99 @@ \sa DeviceClass, DeviceDescriptor */ +/*! \enum Device::DeviceError + + This enum type specifies the errors that can happen when working with \l{Device}{Devices}. + + \value DeviceErrorNoError + No Error. Everything went fine. + \value DeviceErrorPluginNotFound + Couldn't find the Plugin for the given id. + \value DeviceErrorVendorNotFound + Couldn't find the Vendor for the given id. + \value DeviceErrorDeviceNotFound + Couldn't find a \l{Device} for the given id. + \value DeviceErrorDeviceClassNotFound + Couldn't find a \l{DeviceClass} for the given id. + \value DeviceErrorActionTypeNotFound + Couldn't find the \l{ActionType} for the given id. + \value DeviceErrorStateTypeNotFound + Couldn't find the \l{StateType} for the given id. + \value DeviceErrorEventTypeNotFound + Couldn't find the \l{EventType} for the given id. + \value DeviceErrorDeviceDescriptorNotFound + Couldn't find the \l{DeviceDescriptor} for the given id. + \value DeviceErrorMissingParameter + Parameters do not comply to the template. + \value DeviceErrorInvalidParameter + One of the given parameter is not valid. + \value DeviceErrorSetupFailed + Error setting up the \l{Device}. It will not be functional. + \value DeviceErrorDuplicateUuid + Error setting up the \l{Device}. The given DeviceId already exists. + \value DeviceErrorCreationMethodNotSupported + Error setting up the \l{Device}. This \l{DeviceClass}{CreateMethod} is not supported for this \l{Device}. + \value DeviceErrorSetupMethodNotSupported + Error setting up the \l{Device}. This \l{DeviceClass}{SetupMethod} is not supported for this \l{Device}. + \value DeviceErrorHardwareNotAvailable + The Hardware of the \l{Device} is not available. + \value DeviceErrorHardwareFailure + The Hardware of the \l{Device} has an error. + \value DeviceErrorAsync + The response of the \l{Device} will be asynchronously. + \value DeviceErrorDeviceInUse + The \l{Device} is currently bussy. + \value DeviceErrorPairingTransactionIdNotFound + Couldn't find the PairingTransactionId for the given id. + \value DeviceErrorAuthentificationFailure + The device could not authentificate with something. + \value DeviceErrorDeviceIsChild + The device is a child device and can not be deleted directly. + \value DeviceErrorDeviceInRule + The device is in a rule and can not be deleted withou \l{nymeaserver::RuleEngine::RemovePolicy}. + \value DeviceErrorParameterNotWritable + One of the given device params is not writable. +*/ + +/*! \enum Device::DeviceSetupStatus + + This enum type specifies the setup status of a \l{Device}. + + \value DeviceSetupStatusSuccess + No Error. Everything went fine. + \value DeviceSetupStatusFailure + Something went wrong during the setup. + \value DeviceSetupStatusAsync + The status of the \l{Device} setup will be emitted asynchronous. +*/ + /*! \fn void Device::stateValueChanged(const StateTypeId &stateTypeId, const QVariant &value) This signal is emitted when the \l{State} with the given \a stateTypeId changed. The \a value parameter describes the new value of the State. */ #include "device.h" +#include "deviceplugin.h" #include "types/event.h" #include "loggingcategories.h" #include /*! Construct an Device with the given \a pluginId, \a id, \a deviceClassId and \a parent. */ -Device::Device(const PluginId &pluginId, const DeviceId &id, const DeviceClassId &deviceClassId, QObject *parent): +Device::Device(DevicePlugin *plugin, const DeviceClass &deviceClass, const DeviceId &id, QObject *parent): QObject(parent), - m_id(id), - m_deviceClassId(deviceClassId), - m_pluginId(pluginId) + m_deviceClass(deviceClass), + m_plugin(plugin), + m_id(id) { } /*! Construct an Device with the given \a pluginId, \a deviceClassId and \a parent. A new DeviceId will be created for this Device. */ -Device::Device(const PluginId &pluginId, const DeviceClassId &deviceClassId, QObject *parent): +Device::Device(DevicePlugin *plugin, const DeviceClass &deviceClass, QObject *parent): QObject(parent), - m_id(DeviceId::createDeviceId()), - m_deviceClassId(deviceClassId), - m_pluginId(pluginId) + m_deviceClass(deviceClass), + m_plugin(plugin), + m_id(DeviceId::createDeviceId()) { } @@ -78,13 +145,13 @@ DeviceId Device::id() const /*! Returns the deviceClassId of the associated \l{DeviceClass}. */ DeviceClassId Device::deviceClassId() const { - return m_deviceClassId; + return m_deviceClass.id(); } /*! Returns the id of the \l{DevicePlugin} this Device is managed by. */ PluginId Device::pluginId() const { - return m_pluginId; + return m_plugin->pluginId(); } /*! Returns the name of this Device. This is visible to the user. */ @@ -314,6 +381,25 @@ Device *Devices::findById(const DeviceId &id) return nullptr; } +/*! Find a certain device by its \a params. All parameters must + match or the device will not be found. Be prepared for nullptrs. +*/ +Device *Devices::findByParams(const ParamList ¶ms) const +{ + foreach (Device *device, *this) { + bool matching = true; + foreach (const Param ¶m, params) { + if (device->paramValue(param.paramTypeId()) != param.value()) { + matching = false; + } + } + if (matching) { + return device; + } + } + return nullptr; +} + QDebug operator<<(QDebug dbg, Device *device) { dbg.nospace() << "Device(" << device->name(); diff --git a/libnymea/plugin/device.h b/libnymea/devices/device.h similarity index 71% rename from libnymea/plugin/device.h rename to libnymea/devices/device.h index 6410916b..9f91d3a8 100644 --- a/libnymea/plugin/device.h +++ b/libnymea/devices/device.h @@ -35,17 +35,58 @@ #include #include +class DevicePlugin; + class LIBNYMEA_EXPORT Device: public QObject { Q_OBJECT friend class DeviceManager; + friend class DeviceManagerImplementation; public: + enum DeviceError { + DeviceErrorNoError, + DeviceErrorPluginNotFound, + DeviceErrorVendorNotFound, + DeviceErrorDeviceNotFound, + DeviceErrorDeviceClassNotFound, + DeviceErrorActionTypeNotFound, + DeviceErrorStateTypeNotFound, + DeviceErrorEventTypeNotFound, + DeviceErrorDeviceDescriptorNotFound, + DeviceErrorMissingParameter, + DeviceErrorInvalidParameter, + DeviceErrorSetupFailed, + DeviceErrorDuplicateUuid, + DeviceErrorCreationMethodNotSupported, + DeviceErrorSetupMethodNotSupported, + DeviceErrorHardwareNotAvailable, + DeviceErrorHardwareFailure, + DeviceErrorAuthentificationFailure, + DeviceErrorAsync, + DeviceErrorDeviceInUse, + DeviceErrorDeviceInRule, + DeviceErrorDeviceIsChild, + DeviceErrorPairingTransactionIdNotFound, + DeviceErrorParameterNotWritable + }; + Q_ENUM(DeviceError) + + enum DeviceSetupStatus { + DeviceSetupStatusSuccess, + DeviceSetupStatusFailure, + DeviceSetupStatusAsync + }; + Q_ENUM(DeviceSetupStatus) + DeviceId id() const; DeviceClassId deviceClassId() const; PluginId pluginId() const; + DeviceClass deviceClass() const; + DevicePlugin* plugin(); + QString name() const; void setName(const QString &name); @@ -84,17 +125,18 @@ signals: void nameChanged(); private: - Device(const PluginId &pluginId, const DeviceId &id, const DeviceClassId &deviceClassId, QObject *parent = nullptr); - Device(const PluginId &pluginId, const DeviceClassId &deviceClassId, QObject *parent = nullptr); + Device(DevicePlugin *plugin, const DeviceClass &deviceClass, const DeviceId &id, QObject *parent = nullptr); + Device(DevicePlugin *plugin, const DeviceClass &deviceClass, QObject *parent = nullptr); void setupCompleted(); void setSetupComplete(const bool &complete); private: + DeviceClass m_deviceClass; + DevicePlugin* m_plugin = nullptr; + DeviceId m_id; DeviceId m_parentId; - DeviceClassId m_deviceClassId; - PluginId m_pluginId; QString m_name; ParamList m_params; ParamList m_settings; @@ -111,8 +153,12 @@ public: Devices() = default; Devices(const QList &other); Device* findById(const DeviceId &id); + Device* findByParams(const ParamList ¶ms) const; Devices filterByParam(const ParamTypeId ¶mTypeId, const QVariant &value = QVariant()); Devices filterByDeviceClassId(const DeviceClassId &deviceClassId); }; +Q_DECLARE_METATYPE(Device::DeviceError) +Q_DECLARE_METATYPE(Device::DeviceSetupStatus) + #endif diff --git a/libnymea/plugin/devicedescriptor.cpp b/libnymea/devices/devicedescriptor.cpp similarity index 100% rename from libnymea/plugin/devicedescriptor.cpp rename to libnymea/devices/devicedescriptor.cpp diff --git a/libnymea/plugin/devicedescriptor.h b/libnymea/devices/devicedescriptor.h similarity index 100% rename from libnymea/plugin/devicedescriptor.h rename to libnymea/devices/devicedescriptor.h diff --git a/libnymea/devices/devicemanager.cpp b/libnymea/devices/devicemanager.cpp new file mode 100644 index 00000000..a2bb77e4 --- /dev/null +++ b/libnymea/devices/devicemanager.cpp @@ -0,0 +1,41 @@ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * + * * + * Copyright (C) 2019 Michael Zanetti * + * * + * This file is part of nymea. * + * * + * This library is free software; you can redistribute it and/or * + * modify it under the terms of the GNU Lesser General Public * + * License as published by the Free Software Foundation; either * + * version 2.1 of the License, or (at your option) any later version. * + * * + * This library is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * + * Lesser General Public License for more details. * + * * + * You should have received a copy of the GNU Lesser General Public * + * License along with this library; If not, see * + * . * + * * + * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +#include "devicemanager.h" + +/*! + \class DeviceManager + \brief The main entry point when interacting with \l{Device}{Devices} + + \ingroup devices + \inmodule libnymea + + The DeviceManager hold s all information about supported and configured Devices in the system. + + It is also responsible for loading Plugins and managing common hardware resources between + \l{DevicePlugin}{device plugins}. +*/ + +DeviceManager::DeviceManager(QObject *parent) : QObject(parent) +{ + +} diff --git a/libnymea/devices/devicemanager.h b/libnymea/devices/devicemanager.h new file mode 100644 index 00000000..14c3d793 --- /dev/null +++ b/libnymea/devices/devicemanager.h @@ -0,0 +1,91 @@ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * + * * + * Copyright (C) 2019 Michael Zanetti * + * * + * This file is part of nymea. * + * * + * This library is free software; you can redistribute it and/or * + * modify it under the terms of the GNU Lesser General Public * + * License as published by the Free Software Foundation; either * + * version 2.1 of the License, or (at your option) any later version. * + * * + * This library is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * + * Lesser General Public License for more details. * + * * + * You should have received a copy of the GNU Lesser General Public * + * License along with this library; If not, see * + * . * + * * + * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +#ifndef DEVICEMANAGER_H +#define DEVICEMANAGER_H + +#include + +#include "device.h" +#include "deviceplugin.h" +#include "types/interface.h" +#include "types/vendor.h" + +class DeviceManager : public QObject +{ + Q_OBJECT +public: + explicit DeviceManager(QObject *parent = nullptr); + virtual ~DeviceManager() = default; + + virtual DevicePlugins plugins() const = 0; + virtual Device::DeviceError setPluginConfig(const PluginId &pluginId, const ParamList &pluginConfig) = 0; + + virtual Vendors supportedVendors() const = 0; + virtual Interfaces supportedInterfaces() const = 0; + virtual DeviceClasses supportedDevices(const VendorId &vendorId = VendorId()) const = 0; + + virtual DeviceClass findDeviceClass(const DeviceClassId &deviceClassId) const = 0; + + virtual Devices configuredDevices() const = 0; + virtual Device* findConfiguredDevice(const DeviceId &id) const = 0; + virtual Devices findConfiguredDevices(const DeviceClassId &deviceClassId) const = 0; + virtual Devices findConfiguredDevices(const QString &interface) const = 0; + virtual Devices findChildDevices(const DeviceId &id) const = 0; + + virtual Device::DeviceError discoverDevices(const DeviceClassId &deviceClassId, const ParamList ¶ms) = 0; + + virtual Device::DeviceError addConfiguredDevice(const DeviceClassId &deviceClassId, const QString &name, const ParamList ¶ms, const DeviceId id = DeviceId::createDeviceId()) = 0; + virtual Device::DeviceError addConfiguredDevice(const DeviceClassId &deviceClassId, const QString &name, const DeviceDescriptorId &deviceDescriptorId, const ParamList ¶ms = ParamList(), const DeviceId &deviceId = DeviceId::createDeviceId()) = 0; + + virtual Device::DeviceError reconfigureDevice(const DeviceId &deviceId, const ParamList ¶ms, bool fromDiscoveryOrAuto = false) = 0; + virtual Device::DeviceError reconfigureDevice(const DeviceId &deviceId, const DeviceDescriptorId &deviceDescriptorId) = 0; + + virtual Device::DeviceError editDevice(const DeviceId &deviceId, const QString &name) = 0; + virtual Device::DeviceError setDeviceSettings(const DeviceId &deviceId, const ParamList &settings) = 0; + + virtual Device::DeviceError pairDevice(const PairingTransactionId &pairingTransactionId, const DeviceClassId &deviceClassId, const QString &name, const ParamList ¶ms) = 0; + virtual Device::DeviceError pairDevice(const PairingTransactionId &pairingTransactionId, const DeviceClassId &deviceClassId, const QString &name, const DeviceDescriptorId &deviceDescriptorId) = 0; + virtual Device::DeviceError confirmPairing(const PairingTransactionId &pairingTransactionId, const QString &secret = QString()) = 0; + + virtual Device::DeviceError removeConfiguredDevice(const DeviceId &deviceId) = 0; + + virtual QString translate(const PluginId &pluginId, const QString &string, const QLocale &locale) = 0; + +signals: + void pluginConfigChanged(const PluginId &id, const ParamList &config); + void eventTriggered(const Event &event); + void deviceStateChanged(Device *device, const StateTypeId &stateTypeId, const QVariant &value); + void deviceRemoved(const DeviceId &deviceId); + void deviceDisappeared(const DeviceId &deviceId); + void deviceAdded(Device *device); + void deviceChanged(Device *device); + void deviceSettingChanged(const DeviceId deviceId, const ParamTypeId &settingParamTypeId, const QVariant &value); + void devicesDiscovered(const DeviceClassId &deviceClassId, const QList &devices); + void deviceSetupFinished(Device *device, Device::DeviceError status); + void deviceReconfigurationFinished(Device *device, Device::DeviceError status); + void pairingFinished(const PairingTransactionId &pairingTransactionId, Device::DeviceError status, const DeviceId &deviceId = DeviceId()); + void actionExecutionFinished(const ActionId &actionId, Device::DeviceError status); + +}; + +#endif // DEVICEMANAGER_H diff --git a/libnymea/plugin/devicepairinginfo.cpp b/libnymea/devices/devicepairinginfo.cpp similarity index 100% rename from libnymea/plugin/devicepairinginfo.cpp rename to libnymea/devices/devicepairinginfo.cpp diff --git a/libnymea/plugin/devicepairinginfo.h b/libnymea/devices/devicepairinginfo.h similarity index 100% rename from libnymea/plugin/devicepairinginfo.h rename to libnymea/devices/devicepairinginfo.h diff --git a/libnymea/devices/deviceplugin.cpp b/libnymea/devices/deviceplugin.cpp new file mode 100644 index 00000000..46fc71e9 --- /dev/null +++ b/libnymea/devices/deviceplugin.cpp @@ -0,0 +1,380 @@ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * + * * + * Copyright (C) 2015-2018 Simon Stürz * + * Copyright (C) 2014 Michael Zanetti * + * * + * This file is part of nymea. * + * * + * This library is free software; you can redistribute it and/or * + * modify it under the terms of the GNU Lesser General Public * + * License as published by the Free Software Foundation; either * + * version 2.1 of the License, or (at your option) any later version. * + * * + * This library is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * + * Lesser General Public License for more details. * + * * + * You should have received a copy of the GNU Lesser General Public * + * License along with this library; If not, see * + * . * + * * + * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +/*! + \class DevicePlugin + \brief This is the base class interface for device plugins. + + \ingroup devices + \inmodule libnymea + +*/ + + +/*! \fn void DevicePlugin::devicesDiscovered(const DeviceClassId &deviceClassId, const QList &devices); + Emit this signal when the discovery of a \a deviceClassId of this DevicePlugin is finished. The \a devices parameter describes the + list of \l{DeviceDescriptor}{DeviceDescriptors} of all discovered \l{Device}{Devices}. + Note: During a discovery a plugin should always return the full result set. So even if a device is already known to the system and + a later discovery finds the device again, it should be included in the result set but the DeviceDescriptor's deviceId should be set + to the device ID. + \sa discoverDevices() +*/ + +/*! \fn void DevicePlugin::pairingFinished(const PairingTransactionId &pairingTransactionId, Device::DeviceSetupStatus status); + This signal is emitted when the pairing of a \a pairingTransactionId is finished. + The \a status of the will be described as \l{Device::DeviceError}{DeviceError}. + \sa confirmPairing() +*/ + +/*! \fn void DevicePlugin::deviceSetupFinished(Device *device, Device::DeviceSetupStatus status); + This signal is emitted when the setup of a \a device in this DevicePlugin is finished. The \a status parameter describes the + \l{Device::DeviceError}{DeviceError} that occurred. +*/ + +/*! \fn void DevicePlugin::configValueChanged(const ParamTypeId ¶mTypeId, const QVariant &value); + This signal is emitted when the \l{Param} with a certain \a paramTypeId of a \l{Device} configuration changed the \a value. +*/ + +/*! \fn void DevicePlugin::actionExecutionFinished(const ActionId &id, Device::DeviceError status) + This signal is to be emitted when you previously have returned \l{DeviceManager}{DeviceErrorAsync} + in a call of executeAction(). The \a id refers to the executed \l{Action}. The \a status of the \l{Action} + execution will be described as \l{Device::DeviceError}{DeviceError}. +*/ + +/*! \fn void DevicePlugin::autoDevicesAppeared(const DeviceClassId &deviceClassId, const QList &deviceDescriptors) + This signal is emitted when a new \l{Device} of certain \a deviceClassId appeared. The description of the \l{Device}{Devices} + will be in \a deviceDescriptors. This signal can only emitted from devices with the \l{DeviceClass}{CreateMethodAuto}. +*/ + +/*! \fn void DevicePlugin::autoDeviceDisappeared(const DeviceId &id) + Emit this signal when a device with the given \a id and which was created by \l{DevicePlugin::autoDevicesAppeared} has been removed from the system. + Be careful with this, as this will completely remove the device from the system and with it all the associated rules. Only + emit this if you are sure that a device will never come back. This signal should not be emitted for child auto devices + when the parent who created them is removed. The system will automatically remove all child devices in such a case. +*/ + +/*! \fn void DevicePlugin::emitEvent(const Event &event) + To produce a new event in the system, create a new \l{Event} and emit it with \a event. + Usually events are emitted in response to incoming data or other other events happening. Find a configured + \l{Device} from the \l{DeviceManager} and get its \l{EventType}{EventTypes}, then + create a \l{Event} complying to that \l{EventType} and emit it here. +*/ + +/*! \fn void DevicePlugin::init() + This will be called after constructing the DevicePlugin. Override this to do any + initialisation work you need to do. +*/ + +#include "deviceplugin.h" +#include "devicemanager.h" +#include "deviceutils.h" +#include "loggingcategories.h" + +#include "nymeasettings.h" + +#include "hardware/radio433/radio433.h" +#include "network/upnp/upnpdiscovery.h" + +#include +#include +#include +#include +#include +#include +#include + +/*! DevicePlugin constructor. DevicePlugins will be instantiated by the DeviceManager, its \a parent. */ +DevicePlugin::DevicePlugin(QObject *parent): + QObject(parent) +{ +} + +/*! Virtual destructor... */ +DevicePlugin::~DevicePlugin() +{ + +} + +/*! Returns the name of this DevicePlugin. */ +QString DevicePlugin::pluginName() const +{ + return m_metaData.pluginName(); +} + +/*! Returns the displayName of this DevicePlugin, to be shown to the user, translated. */ +QString DevicePlugin::pluginDisplayName() const +{ + return m_metaData.pluginDisplayName(); +} + +/*! Returns the id of this DevicePlugin. + * When implementing a plugin, generate a new uuid and return it here. Always return the + * same uuid and don't change it or configurations can't be matched any more. */ +PluginId DevicePlugin::pluginId() const +{ + return m_metaData.pluginId(); +} + +/*! Returns the list of \l{Vendor}{Vendors} supported by this DevicePlugin. */ +Vendors DevicePlugin::supportedVendors() const +{ + return m_metaData.vendors(); +} + +/*! Return a list of \l{DeviceClass}{DeviceClasses} describing all the devices supported by this plugin. + If a DeviceClass has an invalid parameter it will be ignored. +*/ +DeviceClasses DevicePlugin::supportedDevices() const +{ + return m_metaData.deviceClasses(); +} + +/*! Override this if your plugin supports Device with DeviceClass::CreationMethodAuto. + This will be called at startup, after the configured devices have been loaded. + This is the earliest time you should start emitting autoDevicesAppeared(). If you + are monitoring some hardware/service for devices to appear, start monitoring now. + If you are building the devices based on a static list, you may emit + autoDevicesAppeard() in here. +*/ +void DevicePlugin::startMonitoringAutoDevices() +{ + +} + +/*! Reimplement this if you support a DeviceClass with createMethod \l{DeviceManager}{CreateMethodDiscovery}. + This will be called to discover Devices for the given \a deviceClassId with the given \a params. This will always + be an async operation. Return \l{DeviceManager}{DeviceErrorAsync} or \l{DeviceManager}{DeviceErrorNoError} + if the discovery has been started successfully. Return an appropriate error otherwise. + Once devices are discovered, emit devicesDiscovered(). +*/ +Device::DeviceError DevicePlugin::discoverDevices(const DeviceClassId &deviceClassId, const ParamList ¶ms) +{ + Q_UNUSED(deviceClassId) + Q_UNUSED(params) + return Device::DeviceErrorCreationMethodNotSupported; +} + +/*! This will be called when a new device is created. The plugin has the chance to do some setup. + Return \l{DeviceManager}{DeviceSetupStatusFailure} if something bad happened during the setup in which case the \a device + will be disabled. Return \l{DeviceManager}{DeviceSetupStatusSuccess} if everything went well. If you can't tell yet and + need more time to set up the \a device (note: you should never block in this method) you can + return \l{DeviceManager}{DeviceSetupStatusAsync}. In that case the \l{DeviceManager} will wait for you to emit + \l{DevicePlugin}{deviceSetupFinished} to report the status. +*/ +Device::DeviceSetupStatus DevicePlugin::setupDevice(Device *device) +{ + Q_UNUSED(device) + return Device::DeviceSetupStatusSuccess; +} + +/*! This will be called when a new \a device was added successfully and the device setup is finished.*/ +void DevicePlugin::postSetupDevice(Device *device) +{ + Q_UNUSED(device) +} + +/*! This will be called when a \a device removed. The plugin has the chance to do some teardown. + The device is still valid during this call, but already removed from the system. + The device will be deleted as soon as this method returns. +*/ +void DevicePlugin::deviceRemoved(Device *device) +{ + Q_UNUSED(device) +} + +/*! This method will be called for \l{Device}{Devices} with the \l{DeviceClass::SetupMethodDisplayPin} right after the paring request + with the given \a pairingTransactionId for the given \a deviceDescriptor. +*/ +Device::DeviceError DevicePlugin::displayPin(const PairingTransactionId &pairingTransactionId, const DeviceDescriptor &deviceDescriptor) +{ + Q_UNUSED(pairingTransactionId) + Q_UNUSED(deviceDescriptor) + + qCWarning(dcDeviceManager) << "Plugin does not implement the display pin setup method."; + + return Device::DeviceErrorNoError; +} + +/*! Confirms the pairing of a \a deviceClassId with the given \a pairingTransactionId and \a params. + Returns \l{Device::DeviceError}{DeviceError} to inform about the result. The optional paramerter + \a secret contains for example the pin for \l{Device}{Devices} with the setup method \l{DeviceClass::SetupMethodDisplayPin}. +*/ +Device::DeviceSetupStatus DevicePlugin::confirmPairing(const PairingTransactionId &pairingTransactionId, const DeviceClassId &deviceClassId, const ParamList ¶ms, const QString &secret = QString()) +{ + Q_UNUSED(pairingTransactionId) + Q_UNUSED(deviceClassId) + Q_UNUSED(params) + Q_UNUSED(secret) + + qCWarning(dcDeviceManager) << "Plugin does not implement pairing."; + return Device::DeviceSetupStatusFailure; +} + +/*! This will be called to actually execute actions on the hardware. The \{Device} and + the \{Action} are contained in the \a device and \a action parameters. + Return the appropriate \l{Device::DeviceError}{DeviceError}. + + It is possible to execute actions asynchronously. You never should do anything blocking for + a long time (e.g. wait on a network reply from the internet) but instead return + Device::DeviceErrorAsync and continue processing in an async manner. Once + you have the reply ready, emit actionExecutionFinished() with the appropriate parameters. + + \sa actionExecutionFinished() +*/ +Device::DeviceError DevicePlugin::executeAction(Device *device, const Action &action) +{ + Q_UNUSED(device) + Q_UNUSED(action) + return Device::DeviceErrorNoError; +} + +/*! Returns the configuration description of this DevicePlugin as a list of \l{ParamType}{ParamTypes}. */ +ParamTypes DevicePlugin::configurationDescription() const +{ + return m_metaData.pluginSettings(); +} + +/*! This will be called when the DeviceManager initializes the plugin and set up the things behind the scenes. + When implementing a new plugin, use \l{DevicePlugin::init()} instead in order to do initialisation work. + The \l{DevicePlugin::init()} method will be called once the plugin configuration has been loaded. */ +void DevicePlugin::initPlugin(const PluginMetadata &metadata, DeviceManager *deviceManager, HardwareManager *hardwareManager) +{ + m_metaData = metadata; + m_deviceManager = deviceManager; + m_hardwareManager = hardwareManager; + +} + +/*! Returns a map containing the plugin configuration. + When implementing a new plugin, override this and fill in the empty configuration if your plugin requires any. +*/ +ParamList DevicePlugin::configuration() const +{ + return m_config; +} + +/*! Use this to retrieve the values for your parameters. Values might not be set + at the time when your plugin is loaded, but will be set soon after. Listen to + configurationValueChanged() to know when something changes. + When implementing a new plugin, specify in configurationDescription() what you want to see here. + Returns the config value of a \l{Param} with the given \a paramTypeId of this DevicePlugin. +*/ +QVariant DevicePlugin::configValue(const ParamTypeId ¶mTypeId) const +{ + return m_config.paramValue(paramTypeId); +} + +/*! Will be called by the DeviceManager to set a plugin's \a configuration. */ +Device::DeviceError DevicePlugin::setConfiguration(const ParamList &configuration) +{ + foreach (const Param ¶m, configuration) { + qCDebug(dcDeviceManager()) << "* Set plugin configuration" << param; + Device::DeviceError result = setConfigValue(param.paramTypeId(), param.value()); + if (result != Device::DeviceErrorNoError) + return result; + + } + return Device::DeviceErrorNoError; +} + +/*! Can be called in the DevicePlugin to set a plugin's \l{Param} with the given \a paramTypeId and \a value. */ +Device::DeviceError DevicePlugin::setConfigValue(const ParamTypeId ¶mTypeId, const QVariant &value) +{ + bool found = false; + foreach (const ParamType ¶mType, configurationDescription()) { + if (paramType.id() == paramTypeId) { + found = true; + Device::DeviceError result = DeviceUtils::verifyParam(paramType, Param(paramTypeId, value)); + if (result != Device::DeviceErrorNoError) + return result; + + break; + } + } + + if (!found) { + qCWarning(dcDeviceManager()) << QString("Could not find plugin parameter with the id %1.").arg(paramTypeId.toString()); + return Device::DeviceErrorInvalidParameter; + } + + if (m_config.hasParam(paramTypeId)) { + if (!m_config.setParamValue(paramTypeId, value)) { + qCWarning(dcDeviceManager()) << "Could not set param value" << value << "for param with id" << paramTypeId.toString(); + return Device::DeviceErrorInvalidParameter; + } + } else { + m_config.append(Param(paramTypeId, value)); + } + + emit configValueChanged(paramTypeId, value); + return Device::DeviceErrorNoError; +} + +bool DevicePlugin::isBuiltIn() const +{ + return m_metaData.isBuiltIn(); +} + +/*! Returns a list of all configured devices belonging to this plugin. */ +Devices DevicePlugin::myDevices() const +{ + QList ret; + foreach (Device *device, m_deviceManager->configuredDevices()) { + if (device->pluginId() == pluginId()) { + ret.append(device); + } + } + return ret; +} + + +/*! Returns the pointer to the main \l{HardwareManager} of this server. */ +HardwareManager *DevicePlugin::hardwareManager() const +{ + return m_hardwareManager; +} + +void DevicePlugin::setMetaData(const PluginMetadata &metaData) +{ + m_metaData = metaData; +} + +DevicePlugins::DevicePlugins() +{ + +} + +DevicePlugins::DevicePlugins(const QList &other): QList(other) +{ + +} + +DevicePlugin *DevicePlugins::findById(const PluginId &id) const +{ + foreach (DevicePlugin *plugin, *this) { + if (plugin->pluginId() == id) { + return plugin; + } + } + return nullptr; +} diff --git a/libnymea/plugin/deviceplugin.h b/libnymea/devices/deviceplugin.h similarity index 65% rename from libnymea/plugin/deviceplugin.h rename to libnymea/devices/deviceplugin.h index 587568ea..037a5018 100644 --- a/libnymea/plugin/deviceplugin.h +++ b/libnymea/devices/deviceplugin.h @@ -24,21 +24,23 @@ #ifndef DEVICEPLUGIN_H #define DEVICEPLUGIN_H -#include "devicemanager.h" - #include "libnymea.h" #include "typeutils.h" +#include "device.h" +#include "devicedescriptor.h" +#include "pluginmetadata.h" + #include "types/deviceclass.h" #include "types/event.h" #include "types/action.h" #include "types/vendor.h" #include "types/param.h" +#include "types/interface.h" + +#include "hardwaremanager.h" #include -#include -#include -#include #include #include @@ -50,6 +52,7 @@ class LIBNYMEA_EXPORT DevicePlugin: public QObject Q_OBJECT friend class DeviceManager; + friend class DeviceManagerImplementation; public: DevicePlugin(QObject *parent = nullptr); @@ -60,50 +63,47 @@ public: PluginId pluginId() const; QString pluginName() const; QString pluginDisplayName() const; - QList supportedVendors() const; - QList supportedDevices() const; + Vendors supportedVendors() const; + DeviceClasses supportedDevices() const; virtual void startMonitoringAutoDevices(); - virtual DeviceManager::DeviceError discoverDevices(const DeviceClassId &deviceClassId, const ParamList ¶ms); + virtual Device::DeviceError discoverDevices(const DeviceClassId &deviceClassId, const ParamList ¶ms); - virtual DeviceManager::DeviceSetupStatus setupDevice(Device *device); + virtual Device::DeviceSetupStatus setupDevice(Device *device); virtual void postSetupDevice(Device *device); virtual void deviceRemoved(Device *device); - virtual DeviceManager::DeviceError displayPin(const PairingTransactionId &pairingTransactionId, const DeviceDescriptor &deviceDescriptor); - virtual DeviceManager::DeviceSetupStatus confirmPairing(const PairingTransactionId &pairingTransactionId, const DeviceClassId &deviceClassId, const ParamList ¶ms, const QString &secret); + virtual Device::DeviceError displayPin(const PairingTransactionId &pairingTransactionId, const DeviceDescriptor &deviceDescriptor); + virtual Device::DeviceSetupStatus confirmPairing(const PairingTransactionId &pairingTransactionId, const DeviceClassId &deviceClassId, const ParamList ¶ms, const QString &secret); - virtual DeviceManager::DeviceError executeAction(Device *device, const Action &action); + virtual Device::DeviceError executeAction(Device *device, const Action &action); // Configuration ParamTypes configurationDescription() const; - DeviceManager::DeviceError setConfiguration(const ParamList &configuration); + Device::DeviceError setConfiguration(const ParamList &configuration); ParamList configuration() const; QVariant configValue(const ParamTypeId ¶mTypeId) const; - DeviceManager::DeviceError setConfigValue(const ParamTypeId ¶mTypeId, const QVariant &value); + Device::DeviceError setConfigValue(const ParamTypeId ¶mTypeId, const QVariant &value); bool isBuiltIn() const; signals: void emitEvent(const Event &event); void devicesDiscovered(const DeviceClassId &deviceClassId, const QList &deviceDescriptors); - void deviceSetupFinished(Device *device, DeviceManager::DeviceSetupStatus status); - void pairingFinished(const PairingTransactionId &pairingTransactionId, DeviceManager::DeviceSetupStatus status); - void actionExecutionFinished(const ActionId &id, DeviceManager::DeviceError status); + void deviceSetupFinished(Device *device, Device::DeviceSetupStatus status); + void pairingFinished(const PairingTransactionId &pairingTransactionId, Device::DeviceSetupStatus status); + void actionExecutionFinished(const ActionId &id, Device::DeviceError status); void configValueChanged(const ParamTypeId ¶mTypeId, const QVariant &value); void autoDevicesAppeared(const DeviceClassId &deviceClassId, const QList &deviceDescriptors); void autoDeviceDisappeared(const DeviceId &deviceId); protected: - DeviceManager *deviceManager() const; Devices myDevices() const; HardwareManager *hardwareManager() const; - Device* findDeviceByParams(const ParamList ¶ms) const; private: - void setMetaData(const QJsonObject &metaData); - void loadMetaData(); - void initPlugin(DeviceManager *deviceManager); + void setMetaData(const PluginMetadata &metaData); + void initPlugin(const PluginMetadata &metadata, DeviceManager *deviceManager, HardwareManager *hardwareManager); QPair > parseParamTypes(const QJsonArray &array) const; @@ -114,25 +114,22 @@ private: QPair loadAndVerifyUnit(const QString &unitString) const; QPair loadAndVerifyInputType(const QString &inputType) const; - // FIXME: This is expensive because it will open all the files. - // Once DeviceManager is in libnymea-core this should probably be there too. - // I didn't want to add even more dependencies on the devicemanager into here, so reading the list here for now. - static Interfaces allInterfaces(); - static Interface loadInterface(const QString &name); - static Interface mergeInterfaces(const Interface &iface1, const Interface &iface2); - static QStringList generateInterfaceParentList(const QString &interface); - DeviceManager *m_deviceManager = nullptr; + HardwareManager *m_hardwareManager = nullptr; - QList m_configurationDescription; + PluginMetadata m_metaData; ParamList m_config; - - QJsonObject m_metaData; - - mutable QList m_supportedDevices; - }; Q_DECLARE_INTERFACE(DevicePlugin, "io.nymea.DevicePlugin") + +class LIBNYMEA_EXPORT DevicePlugins: public QList +{ +public: + DevicePlugins(); + DevicePlugins(const QList &other); + DevicePlugin* findById(const PluginId &id) const; +}; + #endif // DEVICEPLUGIN_H diff --git a/libnymea/devices/deviceutils.cpp b/libnymea/devices/deviceutils.cpp new file mode 100644 index 00000000..70f6b22d --- /dev/null +++ b/libnymea/devices/deviceutils.cpp @@ -0,0 +1,307 @@ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * + * * + * Copyright (C) 2019 Michael Zanetti * + * * + * This file is part of nymea. * + * * + * This library is free software; you can redistribute it and/or * + * modify it under the terms of the GNU Lesser General Public * + * License as published by the Free Software Foundation; either * + * version 2.1 of the License, or (at your option) any later version. * + * * + * This library is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * + * Lesser General Public License for more details. * + * * + * You should have received a copy of the GNU Lesser General Public * + * License along with this library; If not, see * + * . * + * * + * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +#include "deviceutils.h" +#include "loggingcategories.h" + +#include +#include +#include + +DeviceUtils::DeviceUtils() +{ + +} + +/*! Verify if the given \a params matches the given \a paramTypes. Ith \a requireAll + * is true, all \l{ParamList}{Params} has to be valid. Returns \l{Device::DeviceError} to inform about the result.*/ +Device::DeviceError DeviceUtils::verifyParams(const QList paramTypes, ParamList ¶ms, bool requireAll) +{ + foreach (const Param ¶m, params) { + Device::DeviceError result = verifyParam(paramTypes, param); + if (result != Device::DeviceErrorNoError) { + return result; + } + } + if (!requireAll) { + return Device::DeviceErrorNoError; + } + foreach (const ParamType ¶mType, paramTypes) { + bool found = false; + foreach (const Param ¶m, params) { + if (paramType.id() == param.paramTypeId()) { + found = true; + } + } + + // This paramType has a default value... lets fill in that one. + if (!paramType.defaultValue().isNull() && !found) { + found = true; + params.append(Param(paramType.id(), paramType.defaultValue())); + } + + if (!found) { + qCWarning(dcDevice) << "Missing parameter:" << paramType.name(); + return Device::DeviceErrorMissingParameter; + } + } + return Device::DeviceErrorNoError; +} + +/*! Verify if the given \a param matches one of the given \a paramTypes. Returns \l{Device::DeviceError} to inform about the result.*/ +Device::DeviceError DeviceUtils::verifyParam(const QList paramTypes, const Param ¶m) +{ + foreach (const ParamType ¶mType, paramTypes) { + if (paramType.id() == param.paramTypeId()) { + return verifyParam(paramType, param); + } + } + + qCWarning(dcDevice) << "Invalid parameter" << param.paramTypeId().toString() << "in parameter list"; + return Device::DeviceErrorInvalidParameter; +} + +/*! Verify if the given \a param matches the given \a paramType. Returns \l{Device::DeviceError} to inform about the result.*/ +Device::DeviceError DeviceUtils::verifyParam(const ParamType ¶mType, const Param ¶m) +{ + if (paramType.id() != param.paramTypeId()) { + qCWarning(dcDevice) << "Parameter id" << param.paramTypeId().toString() << "does not match with ParamType id" << paramType.id().toString(); + return Device::DeviceErrorInvalidParameter; + } + + if (!param.value().canConvert(static_cast(paramType.type()))) { + qCWarning(dcDevice) << "Wrong parameter type for param" << param.paramTypeId().toString() << " Got:" << param.value() << " Expected:" << QVariant::typeToName(static_cast(paramType.type())); + return Device::DeviceErrorInvalidParameter; + } + + if (!param.value().convert(static_cast(paramType.type()))) { + qCWarning(dcDevice) << "Could not convert value of param" << param.paramTypeId().toString() << " to:" << QVariant::typeToName(static_cast(paramType.type())) << " Got:" << param.value(); + return Device::DeviceErrorInvalidParameter; + } + + if (paramType.type() == QVariant::Int) { + if (paramType.maxValue().isValid() && param.value().toInt() > paramType.maxValue().toInt()) { + qCWarning(dcDevice) << "Value out of range for param" << param.paramTypeId().toString() << " Got:" << param.value() << " Max:" << paramType.maxValue(); + return Device::DeviceErrorInvalidParameter; + } + + if (paramType.minValue().isValid() && param.value().toInt() < paramType.minValue().toInt()) { + qCWarning(dcDevice) << "Value out of range for param" << param.paramTypeId().toString() << " Got:" << param.value() << " Min:" << paramType.minValue(); + return Device::DeviceErrorInvalidParameter; + } + } else if (paramType.type() == QVariant::UInt) { + if (paramType.maxValue().isValid() && param.value().toUInt() > paramType.maxValue().toUInt()) { + qCWarning(dcDevice) << "Value out of range for param" << param.paramTypeId().toString() << " Got:" << param.value() << " Max:" << paramType.maxValue(); + return Device::DeviceErrorInvalidParameter; + } + + if (paramType.minValue().isValid() && param.value().toUInt() < paramType.minValue().toUInt()) { + qCWarning(dcDevice) << "Value out of range for param" << param.paramTypeId().toString() << " Got:" << param.value() << " Min:" << paramType.minValue(); + return Device::DeviceErrorInvalidParameter; + } + } else if (paramType.type() == QVariant::Double) { + if (paramType.maxValue().isValid() && param.value().toDouble() > paramType.maxValue().toDouble()) { + qCWarning(dcDevice) << "Value out of range for param" << param.paramTypeId().toString() << " Got:" << param.value() << " Max:" << paramType.maxValue(); + return Device::DeviceErrorInvalidParameter; + } + + if (paramType.minValue().isValid() && param.value().toDouble() < paramType.minValue().toDouble()) { + qCWarning(dcDevice) << "Value out of range for param" << param.paramTypeId().toString() << " Got:" << param.value() << " Min:" << paramType.minValue(); + return Device::DeviceErrorInvalidParameter; + } + } else { + if (paramType.maxValue().isValid() && param.value() > paramType.maxValue()) { + qCWarning(dcDevice) << "Value out of range for param" << param.paramTypeId().toString() << " Got:" << param.value() << " Max:" << paramType.maxValue(); + return Device::DeviceErrorInvalidParameter; + } + + if (paramType.minValue().isValid() && param.value() < paramType.minValue()) { + qCWarning(dcDevice) << "Value out of range for param" << param.paramTypeId().toString() << " Got:" << param.value() << " Min:" << paramType.minValue(); + return Device::DeviceErrorInvalidParameter; + } + } + + if (!paramType.allowedValues().isEmpty() && !paramType.allowedValues().contains(param.value())) { + QStringList allowedValues; + foreach (const QVariant &value, paramType.allowedValues()) { + allowedValues.append(value.toString()); + } + + qCWarning(dcDevice) << "Value not in allowed values for param" << param.paramTypeId().toString() << " Got:" << param.value() << " Allowed:" << allowedValues.join(","); + return Device::DeviceErrorInvalidParameter; + } + + return Device::DeviceErrorNoError; +} + +Interfaces DeviceUtils::allInterfaces() +{ + Interfaces ret; + QDir dir(":/interfaces/"); + foreach (const QFileInfo &ifaceFile, dir.entryInfoList()) { + ret.append(loadInterface(ifaceFile.baseName())); + } + return ret; +} + +Interface DeviceUtils::loadInterface(const QString &name) +{ + Interface iface; + QFile f(QString(":/interfaces/%1.json").arg(name)); + if (!f.open(QFile::ReadOnly)) { + qCWarning(dcDeviceManager()) << "Failed to load interface" << name; + return iface; + } + QJsonParseError error; + QJsonDocument jsonDoc = QJsonDocument::fromJson(f.readAll(), &error); + if (error.error != QJsonParseError::NoError) { + qCWarning(dcDeviceManager) << "Cannot load interface definition for interface" << name << ":" << error.errorString(); + return iface; + } + QVariantMap content = jsonDoc.toVariant().toMap(); + if (content.contains("extends")) { + if (!content.value("extends").toString().isEmpty()) { + iface = loadInterface(content.value("extends").toString()); + } else if (content.value("extends").toList().count() > 0) { + foreach (const QVariant &extendedIface, content.value("extends").toList()) { + Interface tmp = loadInterface(extendedIface.toString()); + iface = mergeInterfaces(iface, tmp); + } + } + } + + StateTypes stateTypes; + ActionTypes actionTypes; + EventTypes eventTypes; + foreach (const QVariant &stateVariant, content.value("states").toList()) { + StateType stateType(StateTypeId::fromUuid(QUuid())); + stateType.setName(stateVariant.toMap().value("name").toString()); + stateType.setType(QVariant::nameToType(stateVariant.toMap().value("type").toByteArray())); + stateType.setPossibleValues(stateVariant.toMap().value("allowedValues").toList()); + stateType.setMinValue(stateVariant.toMap().value("minValue")); + stateType.setMaxValue(stateVariant.toMap().value("maxValue")); + stateTypes.append(stateType); + + EventType stateChangeEventType(EventTypeId::fromUuid(QUuid())); + stateChangeEventType.setName(stateType.name()); + ParamType stateChangeEventParamType; + stateChangeEventParamType.setName(stateType.name()); + stateChangeEventParamType.setType(stateType.type()); + stateChangeEventParamType.setAllowedValues(stateType.possibleValues()); + stateChangeEventParamType.setMinValue(stateType.minValue()); + stateChangeEventParamType.setMaxValue(stateType.maxValue()); + stateChangeEventType.setParamTypes(ParamTypes() << stateChangeEventParamType); + eventTypes.append(stateChangeEventType); + + if (stateVariant.toMap().value("writable", false).toBool()) { + ActionType stateChangeActionType(ActionTypeId::fromUuid(QUuid())); + stateChangeActionType.setName(stateType.name()); + stateChangeActionType.setParamTypes(ParamTypes() << stateChangeEventParamType); + actionTypes.append(stateChangeActionType); + } + } + + foreach (const QVariant &actionVariant, content.value("actions").toList()) { + ActionType actionType(ActionTypeId::fromUuid(QUuid())); + actionType.setName(actionVariant.toMap().value("name").toString()); + ParamTypes paramTypes; + foreach (const QVariant &actionParamVariant, actionVariant.toMap().value("params").toList()) { + ParamType paramType; + paramType.setName(actionParamVariant.toMap().value("name").toString()); + paramType.setType(QVariant::nameToType(actionParamVariant.toMap().value("type").toByteArray())); + paramType.setAllowedValues(actionParamVariant.toMap().value("allowedValues").toList()); + paramType.setMinValue(actionParamVariant.toMap().value("min")); + paramTypes.append(paramType); + } + actionType.setParamTypes(paramTypes); + actionTypes.append(actionType); + } + + foreach (const QVariant &eventVariant, content.value("events").toList()) { + EventType eventType(EventTypeId::fromUuid(QUuid())); + eventType.setName(eventVariant.toMap().value("name").toString()); + ParamTypes paramTypes; + foreach (const QVariant &eventParamVariant, eventVariant.toMap().value("params").toList()) { + ParamType paramType; + paramType.setName(eventParamVariant.toMap().value("name").toString()); + paramType.setType(QVariant::nameToType(eventParamVariant.toMap().value("type").toByteArray())); + paramType.setAllowedValues(eventParamVariant.toMap().value("allowedValues").toList()); + paramType.setMinValue(eventParamVariant.toMap().value("minValue")); + paramType.setMaxValue(eventParamVariant.toMap().value("maxValue")); + paramTypes.append(paramType); + } + eventType.setParamTypes(paramTypes); + eventTypes.append(eventType); + } + + return Interface(name, iface.actionTypes() << actionTypes, iface.eventTypes() << eventTypes, iface.stateTypes() << stateTypes); +} + +Interface DeviceUtils::mergeInterfaces(const Interface &iface1, const Interface &iface2) +{ + EventTypes eventTypes = iface1.eventTypes(); + foreach (const EventType &et, iface2.eventTypes()) { + if (eventTypes.findByName(et.name()).name().isEmpty()) { + eventTypes.append(et); + } + } + StateTypes stateTypes = iface1.stateTypes(); + foreach (const StateType &st, iface2.stateTypes()) { + if (stateTypes.findByName(st.name()).name().isEmpty()) { + stateTypes.append(st); + } + } + ActionTypes actionTypes = iface1.actionTypes(); + foreach (const ActionType &at, iface2.actionTypes()) { + if (actionTypes.findByName(at.name()).name().isEmpty()) { + actionTypes.append(at); + } + } + return Interface(QString(), actionTypes, eventTypes, stateTypes); +} + +QStringList DeviceUtils::generateInterfaceParentList(const QString &interface) +{ + QFile f(QString(":/interfaces/%1.json").arg(interface)); + if (!f.open(QFile::ReadOnly)) { + qCWarning(dcDeviceManager()) << "Failed to load interface" << interface; + return QStringList(); + } + QJsonParseError error; + QJsonDocument jsonDoc = QJsonDocument::fromJson(f.readAll(), &error); + if (error.error != QJsonParseError::NoError) { + qCWarning(dcDeviceManager) << "Cannot load interface definition for interface" << interface << ":" << error.errorString(); + return QStringList(); + } + QStringList ret = {interface}; + QVariantMap content = jsonDoc.toVariant().toMap(); + if (content.contains("extends")) { + if (!content.value("extends").toString().isEmpty()) { + ret << generateInterfaceParentList(content.value("extends").toString()); + } else if (content.value("extends").toList().count() > 0) { + foreach (const QVariant &extendedIface, content.value("extends").toList()) { + ret << generateInterfaceParentList(extendedIface.toString()); + } + } + } + return ret; +} diff --git a/libnymea/devices/deviceutils.h b/libnymea/devices/deviceutils.h new file mode 100644 index 00000000..6416d255 --- /dev/null +++ b/libnymea/devices/deviceutils.h @@ -0,0 +1,48 @@ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * + * * + * Copyright (C) 2019 Michael Zanetti * + * * + * This file is part of nymea. * + * * + * This library is free software; you can redistribute it and/or * + * modify it under the terms of the GNU Lesser General Public * + * License as published by the Free Software Foundation; either * + * version 2.1 of the License, or (at your option) any later version. * + * * + * This library is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * + * Lesser General Public License for more details. * + * * + * You should have received a copy of the GNU Lesser General Public * + * License along with this library; If not, see * + * . * + * * + * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +#ifndef DEVICEUTILS_H +#define DEVICEUTILS_H + +#include "device.h" +#include "pluginmetadata.h" + +#include "types/paramtype.h" +#include "types/interface.h" + +class DeviceUtils +{ +public: + DeviceUtils(); + + static Device::DeviceError verifyParams(const QList paramTypes, ParamList ¶ms, bool requireAll = true); + static Device::DeviceError verifyParam(const QList paramTypes, const Param ¶m); + static Device::DeviceError verifyParam(const ParamType ¶mType, const Param ¶m); + + static Interfaces allInterfaces(); + static Interface loadInterface(const QString &name); + static Interface mergeInterfaces(const Interface &iface1, const Interface &iface2); + static QStringList generateInterfaceParentList(const QString &interface); + +}; + +#endif // DEVICEUTILS_H diff --git a/libnymea/plugin/nymea-generateplugininfo b/libnymea/devices/nymea-generateplugininfo similarity index 100% rename from libnymea/plugin/nymea-generateplugininfo rename to libnymea/devices/nymea-generateplugininfo diff --git a/libnymea/plugin/plugin.pri b/libnymea/devices/plugin.pri similarity index 100% rename from libnymea/plugin/plugin.pri rename to libnymea/devices/plugin.pri diff --git a/libnymea/devices/pluginmetadata.cpp b/libnymea/devices/pluginmetadata.cpp new file mode 100644 index 00000000..2e9041e4 --- /dev/null +++ b/libnymea/devices/pluginmetadata.cpp @@ -0,0 +1,687 @@ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * + * * + * Copyright (C) 2019 Michael Zanetti * + * * + * This file is part of nymea. * + * * + * This library is free software; you can redistribute it and/or * + * modify it under the terms of the GNU Lesser General Public * + * License as published by the Free Software Foundation; either * + * version 2.1 of the License, or (at your option) any later version. * + * * + * This library is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * + * Lesser General Public License for more details. * + * * + * You should have received a copy of the GNU Lesser General Public * + * License along with this library; If not, see * + * . * + * * + * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +#include "pluginmetadata.h" +#include "deviceutils.h" + +#include "loggingcategories.h" + +#include "types/interface.h" + +#include +#include +#include +#include + +PluginMetadata::PluginMetadata() +{ + +} + +PluginMetadata::PluginMetadata(const QJsonObject &jsonObject, bool isBuiltIn): m_isBuiltIn(isBuiltIn) +{ + parse(jsonObject); +} + +bool PluginMetadata::isValid() const +{ + return m_isValid; +} + +PluginId PluginMetadata::pluginId() const +{ + return m_pluginId; +} + +QString PluginMetadata::pluginName() const +{ + return m_pluginName; +} + +QString PluginMetadata::pluginDisplayName() const +{ + return m_pluginDisplayName; +} + +bool PluginMetadata::isBuiltIn() const +{ + return m_isBuiltIn; +} + +ParamTypes PluginMetadata::pluginSettings() const +{ + return m_pluginSettings; +} + +Vendors PluginMetadata::vendors() const +{ + return m_vendors; +} + +DeviceClasses PluginMetadata::deviceClasses() const +{ + return m_deviceClasses; +} + +void PluginMetadata::parse(const QJsonObject &jsonObject) +{ + // General plugin info + QStringList pluginMandatoryJsonProperties = QStringList() << "id" << "name" << "displayName" << "vendors"; + QStringList pluginJsonProperties = QStringList() << "id" << "name" << "displayName" << "vendors" << "paramTypes" << "builtIn"; + QPair verificationResult = verifyFields(pluginJsonProperties, pluginMandatoryJsonProperties, jsonObject); + if (!verificationResult.first.isEmpty()) { + qCWarning(dcDevice()) << pluginName() << "Skipping plugin because of missing fields:" << verificationResult.first.join(", ") << endl << jsonObject; + return; + } + if (!verificationResult.second.isEmpty()) { + qCWarning(dcDevice()) << pluginName() << "Skipping plugin because of unknown fields:" << verificationResult.second.join(", ") << endl << jsonObject; + return; + } + + m_pluginId = jsonObject.value("id").toString(); + m_pluginName = jsonObject.value("name").toString(); + m_pluginDisplayName = jsonObject.value("displayName").toString(); + + // Mandatory fields available... All the rest will be skipped if not valid, but it won't invalidate the entire meta data + m_isValid = true; + + // parse plugin configuration params + if (jsonObject.contains("paramTypes")) { + QPair > paramVerification = parseParamTypes(jsonObject.value("paramTypes").toArray()); + if (paramVerification.first) { + m_pluginSettings = paramVerification.second; + } + } + + // Load vendors + foreach (const QJsonValue &vendorJson, jsonObject.value("vendors").toArray()) { + bool broken = false; + QJsonObject vendorObject = vendorJson.toObject(); + + QStringList vendorMandatoryJsonProperties = QStringList() << "id" << "name" << "displayName" << "deviceClasses"; + QStringList vendorJsonProperties = QStringList() << "id" << "name" << "displayName" << "deviceClasses"; + + QPair verificationResult = verifyFields(vendorJsonProperties, vendorMandatoryJsonProperties, vendorObject); + + // Check mandatory fields + if (!verificationResult.first.isEmpty()) { + qCWarning(dcDevice()) << pluginName() << "Skipping vendor because of missing fields:" << verificationResult.first.join(", ") << endl << vendorObject; + broken = true; + break; + } + + // Check if there are any unknown fields + if (!verificationResult.second.isEmpty()) { + qCWarning(dcDevice()) << pluginName() << "Skipping vendor because of unknown fields:" << verificationResult.second.join(", ") << endl << vendorObject; + broken = true; + break; + } + + VendorId vendorId = VendorId(vendorObject.value("id").toString()); + Vendor vendor(vendorId, vendorObject.value("name").toString()); + vendor.setDisplayName(vendorObject.value("displayName").toString()); + m_vendors.append(vendor); + + // Load deviceclasses of this vendor + foreach (const QJsonValue &deviceClassJson, vendorJson.toObject().value("deviceClasses").toArray()) { + QJsonObject deviceClassObject = deviceClassJson.toObject(); + /*! Returns a list of all valid JSON properties a DeviceClass JSON definition can have. */ + QStringList deviceClassProperties = QStringList() << "id" << "name" << "displayName" << "createMethods" << "setupMethod" + << "interfaces" << "pairingInfo" << "discoveryParamTypes" << "discoveryParamTypes" + << "paramTypes" << "settingsTypes" << "stateTypes" << "actionTypes" << "eventTypes"; + QStringList mandatoryDeviceClassProperties = QStringList() << "id" << "name" << "displayName"; + + QPair verificationResult = verifyFields(deviceClassProperties, mandatoryDeviceClassProperties, deviceClassObject); + + // Check mandatory fields + if (!verificationResult.first.isEmpty()) { + qCWarning(dcDevice()) << pluginName() << "Skipping device class because of missing fields:" << verificationResult.first.join(", ") << endl << deviceClassObject; + broken = true; + break; + } + + // Check if there are any unknown fields + if (!verificationResult.second.isEmpty()) { + qCWarning(dcDevice()) << pluginName() << "Skipping device class because of unknown fields:" << verificationResult.second.join(", ") << endl << deviceClassObject; + broken = true; + break; + } + + DeviceClass deviceClass(pluginId(), vendorId, deviceClassObject.value("id").toString()); + deviceClass.setName(deviceClassObject.value("name").toString()); + deviceClass.setDisplayName(deviceClassObject.value("displayName").toString()); + + // Read create methods + DeviceClass::CreateMethods createMethods; + if (!deviceClassObject.contains("createMethods")) { + // Default if not specified + createMethods |= DeviceClass::CreateMethodUser; + } else { + foreach (const QJsonValue &createMethodValue, deviceClassObject.value("createMethods").toArray()) { + if (createMethodValue.toString().toLower() == "discovery") { + createMethods |= DeviceClass::CreateMethodDiscovery; + } else if (createMethodValue.toString().toLower() == "auto") { + createMethods |= DeviceClass::CreateMethodAuto; + } else if (createMethodValue.toString().toLower() == "user") { + createMethods |= DeviceClass::CreateMethodUser; + } else { + qCWarning(dcDevice()) << "Unknown createMehtod" << createMethodValue.toString() << "in deviceClass " + << deviceClass.name() << ". Falling back to CreateMethodUser."; + createMethods |= DeviceClass::CreateMethodUser; + } + } + } + deviceClass.setCreateMethods(createMethods); + + // Read params + QPair > paramTypesVerification = parseParamTypes(deviceClassObject.value("paramTypes").toArray()); + if (!paramTypesVerification.first) { + broken = true; + break; + } else { + deviceClass.setParamTypes(paramTypesVerification.second); + } + + // Read settings + QPair > settingsTypesVerification = parseParamTypes(deviceClassObject.value("settingsTypes").toArray()); + if (!settingsTypesVerification.first) { + broken = true; + break; + } else { + deviceClass.setSettingsTypes(settingsTypesVerification.second); + } + + // Read discover params + QPair > discoveryParamVerification = parseParamTypes(deviceClassObject.value("discoveryParamTypes").toArray()); + if (!discoveryParamVerification.first) { + broken = true; + break; + } else { + deviceClass.setDiscoveryParamTypes(discoveryParamVerification.second); + } + + // Read setup method + DeviceClass::SetupMethod setupMethod = DeviceClass::SetupMethodJustAdd; + if (deviceClassObject.contains("setupMethod")) { + QString setupMethodString = deviceClassObject.value("setupMethod").toString(); + if (setupMethodString.toLower() == "pushbutton") { + setupMethod = DeviceClass::SetupMethodPushButton; + } else if (setupMethodString.toLower() == "displaypin") { + setupMethod = DeviceClass::SetupMethodDisplayPin; + } else if (setupMethodString.toLower() == "enterpin") { + setupMethod = DeviceClass::SetupMethodEnterPin; + } else if (setupMethodString.toLower() == "justadd") { + setupMethod = DeviceClass::SetupMethodJustAdd; + } else { + qCWarning(dcDevice()) << "Unknown setupMehtod" << setupMethod << "in deviceClass" + << deviceClass.name() << ". Falling back to SetupMethodJustAdd."; + setupMethod = DeviceClass::SetupMethodJustAdd; + } + } + deviceClass.setSetupMethod(setupMethod); + + // Read pairing info + deviceClass.setPairingInfo(deviceClassObject.value("pairingInfo").toString()); + + QList actionTypes; + QList stateTypes; + QList eventTypes; + + // Read StateTypes + int index = 0; + foreach (const QJsonValue &stateTypesJson, deviceClassObject.value("stateTypes").toArray()) { + QJsonObject st = stateTypesJson.toObject(); + bool writableState = false; + + QPair verificationResult = verifyFields(StateType::typeProperties(), StateType::mandatoryTypeProperties(), st); + + // Check mandatory fields + if (!verificationResult.first.isEmpty()) { + qCWarning(dcDevice()) << "Skipping device class" << deviceClass.name() << "because of missing" << verificationResult.first.join(", ") << "in stateType" << st; + broken = true; + break; + } + + // Check if there are any unknown fields + if (!verificationResult.second.isEmpty()) { + qCWarning(dcDevice()) << "Skipping device class" << deviceClass.name() << "because of unknown properties" << verificationResult.second.join(", ") << "in stateType" << st; + broken = true; + break; + } + + // If this is a writable stateType, there must be also the displayNameAction property + if (st.contains("writable") && st.value("writable").toBool()) { + writableState = true; + if (!st.contains("displayNameAction")) { + qCWarning(dcDevice()) << "Skipping device class" << deviceClass.name() << ". The state is writable, but does not define the displayNameAction property" << st; + broken = true; + break; + } + } + + QVariant::Type t = QVariant::nameToType(st.value("type").toString().toLatin1().data()); + if (t == QVariant::Invalid) { + qCWarning(dcDevice()) << "Invalid StateType type:" << st.value("type").toString(); + broken = true; + break; + } + + StateType stateType(st.value("id").toString()); + stateType.setName(st.value("name").toString()); + stateType.setDisplayName(st.value("displayName").toString()); + stateType.setIndex(index++); + stateType.setType(t); + QPair unitVerification = loadAndVerifyUnit(st.value("unit").toString()); + if (!unitVerification.first) { + broken = true; + break; + } else { + stateType.setUnit(unitVerification.second); + } + + stateType.setDefaultValue(st.value("defaultValue").toVariant()); + if (st.contains("minValue")) + stateType.setMinValue(st.value("minValue").toVariant()); + + if (st.contains("maxValue")) + stateType.setMaxValue(st.value("maxValue").toVariant()); + + if (st.contains("possibleValues")) { + QVariantList possibleValues; + foreach (const QJsonValue &possibleValueJson, st.value("possibleValues").toArray()) { + possibleValues.append(possibleValueJson.toVariant()); + } + stateType.setPossibleValues(possibleValues); + + if (!stateType.possibleValues().contains(stateType.defaultValue())) { + qCWarning(dcDevice()) << QString("\"%1\" plugin:").arg(pluginName()).toLatin1().data() << QString("The given default value \"%1\" is not in the possible values of the stateType \"%2\".") + .arg(stateType.defaultValue().toString()).arg(stateType.name()).toLatin1().data(); + broken = true; + break; + } + } + + if (st.contains("cached")) { + stateType.setCached(st.value("cached").toBool()); + } + stateTypes.append(stateType); + + // Events for state changed + EventType eventType(EventTypeId(stateType.id().toString())); + eventType.setName(st.value("name").toString()); + eventType.setDisplayName(st.value("displayNameEvent").toString()); + ParamType paramType(ParamTypeId(stateType.id().toString()), st.value("name").toString(), stateType.type()); + paramType.setDisplayName(st.value("displayName").toString()); + paramType.setAllowedValues(stateType.possibleValues()); + paramType.setDefaultValue(stateType.defaultValue()); + paramType.setMinValue(stateType.minValue()); + paramType.setMaxValue(stateType.maxValue()); + paramType.setUnit(stateType.unit()); + eventType.setParamTypes(QList() << paramType); + eventType.setIndex(stateType.index()); + eventTypes.append(eventType); + + // ActionTypes for writeable StateTypes + if (writableState) { + ActionType actionType(ActionTypeId(stateType.id().toString())); + actionType.setName(stateType.name()); + actionType.setDisplayName(st.value("displayNameAction").toString()); + actionType.setIndex(stateType.index()); + actionType.setParamTypes(QList() << paramType); + actionTypes.append(actionType); + } + } + deviceClass.setStateTypes(stateTypes); + + // ActionTypes + index = 0; + foreach (const QJsonValue &actionTypesJson, deviceClassObject.value("actionTypes").toArray()) { + QJsonObject at = actionTypesJson.toObject(); + QPair verificationResult = verifyFields(ActionType::typeProperties(), ActionType::mandatoryTypeProperties(), at); + + // Check mandatory fields + if (!verificationResult.first.isEmpty()) { + qCWarning(dcDevice()) << pluginName() << "Skipping device class" << deviceClass.name() << "because of missing" << verificationResult.first.join(", ") << "in action type:" << endl << at; + broken = true; + break; + } + + // Check if there are any unknown fields + if (!verificationResult.second.isEmpty()) { + qCWarning(dcDevice()) << pluginName() << "Skipping device class" << deviceClass.name() << "because of unknown fields:" << verificationResult.second.join(", ") << "in action type:" << endl << at; + broken = true; + break; + } + + ActionType actionType(at.value("id").toString()); + actionType.setName(at.value("name").toString()); + actionType.setDisplayName(at.value("displayName").toString()); + actionType.setIndex(index++); + + QPair > paramVerification = parseParamTypes(at.value("paramTypes").toArray()); + if (!paramVerification.first) { + broken = true; + break; + } else { + actionType.setParamTypes(paramVerification.second); + } + + actionTypes.append(actionType); + } + deviceClass.setActionTypes(actionTypes); + + // EventTypes + index = 0; + foreach (const QJsonValue &eventTypesJson, deviceClassObject.value("eventTypes").toArray()) { + QJsonObject et = eventTypesJson.toObject(); + + QPair verificationResult = verifyFields(EventType::typeProperties(), EventType::mandatoryTypeProperties(), et); + + // Check mandatory fields + if (!verificationResult.first.isEmpty()) { + qCWarning(dcDevice()) << pluginName() << "Skipping device class" << deviceClass.name() << "because of missing" << verificationResult.first.join(", ") << "in event type:" << endl << et; + broken = true; + break; + } + + // Check if there are any unknown fields + if (!verificationResult.second.isEmpty()) { + qCWarning(dcDevice()) << pluginName() << "Skipping device class" << deviceClass.name() << "because of unknown fields:" << verificationResult.second.join(", ") << "in event type:" << endl << et; + broken = true; + break; + } + + EventType eventType(et.value("id").toString()); + eventType.setName(et.value("name").toString()); + eventType.setDisplayName(et.value("displayName").toString()); + eventType.setIndex(index++); + + QPair > paramVerification = parseParamTypes(et.value("paramTypes").toArray()); + if (!paramVerification.first) { + broken = true; + break; + } else { + eventType.setParamTypes(paramVerification.second); + } + eventTypes.append(eventType); + } + deviceClass.setEventTypes(eventTypes); + + // Read interfaces + QStringList interfaces; + foreach (const QJsonValue &value, deviceClassObject.value("interfaces").toArray()) { + Interface iface = DeviceUtils::loadInterface(value.toString()); + + StateTypes stateTypes(deviceClass.stateTypes()); + ActionTypes actionTypes(deviceClass.actionTypes()); + EventTypes eventTypes(deviceClass.eventTypes()); + + bool valid = true; + foreach (const StateType &ifaceStateType, iface.stateTypes()) { + StateType stateType = stateTypes.findByName(ifaceStateType.name()); + if (stateType.id().isNull()) { + qCWarning(dcDevice()) << "DeviceClass" << deviceClass.name() << "claims to implement interface" << value.toString() << "but doesn't implement state" << ifaceStateType.name(); + valid = false; + continue; + } + if (ifaceStateType.type() != stateType.type()) { + qCWarning(dcDevice()) << "DeviceClass" << deviceClass.name() << "claims to implement interface" << value.toString() << "but state" << stateType.name() << "has not matching type" << stateType.type() << "!=" << ifaceStateType.type(); + valid = false; + continue; + } + if (ifaceStateType.minValue().isValid() && !ifaceStateType.minValue().isNull()) { + if (ifaceStateType.minValue().toString() == "any") { + if (stateType.minValue().isNull()) { + qCWarning(dcDevice()) << "DeviceClass" << deviceClass.name() << "claims to implement interface" << value.toString() << "but state" << stateType.name() << "has no minimum value defined."; + valid = false; + continue; + } + } else if (ifaceStateType.minValue() != stateType.minValue()) { + qCWarning(dcDevice()) << "DeviceClass" << deviceClass.name() << "claims to implement interface" << value.toString() << "but state" << stateType.name() << "has not matching minimum value:" << ifaceStateType.minValue() << "!=" << stateType.minValue(); + valid = false; + continue; + } + } + if (ifaceStateType.maxValue().isValid() && !ifaceStateType.maxValue().isNull()) { + if (ifaceStateType.maxValue().toString() == "any") { + if (stateType.maxValue().isNull()) { + qCWarning(dcDevice()) << "DeviceClass" << deviceClass.name() << "claims to implement interface" << value.toString() << "but state" << stateType.name() << "has no maximum value defined."; + valid = false; + continue; + } + } else if (ifaceStateType.maxValue() != stateType.maxValue()) { + qCWarning(dcDevice()) << "DeviceClass" << deviceClass.name() << "claims to implement interface" << value.toString() << "but state" << stateType.name() << "has not matching maximum value:" << ifaceStateType.maxValue() << "!=" << stateType.minValue(); + valid = false; + continue; + } + } + if (!ifaceStateType.possibleValues().isEmpty() && ifaceStateType.possibleValues() != stateType.possibleValues()) { + qCWarning(dcDevice()) << "DeviceClass" << deviceClass.name() << "claims to implement interface" << value.toString() << "but state" << stateType.name() << "has not matching allowed values" << ifaceStateType.possibleValues() << "!=" << stateType.possibleValues(); + valid = false; + continue; + } + } + + foreach (const ActionType &ifaceActionType, iface.actionTypes()) { + ActionType actionType = actionTypes.findByName(ifaceActionType.name()); + if (actionType.id().isNull()) { + qCWarning(dcDevice) << "DeviceClass" << deviceClass.name() << "claims to implement interface" << value.toString() << "but doesn't implement action" << ifaceActionType.name(); + valid = false; + } + foreach (const ParamType &ifaceActionParamType, ifaceActionType.paramTypes()) { + ParamType paramType = actionType.paramTypes().findByName(ifaceActionParamType.name()); + if (!paramType.isValid()) { + qCWarning(dcDevice) << "DeviceClass" << deviceClass.name() << "claims to implement interface" << value.toString() << "but doesn't implement action param" << ifaceActionType.name() << ":" << ifaceActionParamType.name(); + valid = false; + } else { + if (paramType.type() != ifaceActionParamType.type()) { + qCWarning(dcDevice()) << "DeviceClass" << deviceClass.name() << "claims to implement interface" << value.toString() << "but param" << paramType.name() << "is of wrong type:" << QVariant::typeToName(paramType.type()) << "expected:" << QVariant::typeToName(ifaceActionParamType.type()); + valid = false; + } + } + } + } + + foreach (const EventType &ifaceEventType, iface.eventTypes()) { + EventType eventType = eventTypes.findByName(ifaceEventType.name()); + if (!eventType.isValid()) { + qCWarning(dcDevice) << "DeviceClass" << deviceClass.name() << "claims to implement interface" << value.toString() << "but doesn't implement event" << ifaceEventType.name(); + valid = false; + } + foreach (const ParamType &ifaceEventParamType, ifaceEventType.paramTypes()) { + ParamType paramType = eventType.paramTypes().findByName(ifaceEventParamType.name()); + if (!paramType.isValid()) { + qCWarning(dcDevice) << "DeviceClass" << deviceClass.name() << "claims to implement interface" << value.toString() << "but doesn't implement event param" << ifaceEventType.name() << ":" << ifaceEventParamType.name(); + valid = false; + } else { + if (paramType.type() != ifaceEventParamType.type()) { + qCWarning(dcDevice()) << "DeviceClass" << deviceClass.name() << "claims to implement interface" << value.toString() << "but param" << paramType.name() << "is of wrong type:" << QVariant::typeToName(paramType.type()) << "expected:" << QVariant::typeToName(ifaceEventParamType.type()); + valid = false; + } + } + } + } + + if (valid) { + interfaces.append(DeviceUtils::generateInterfaceParentList(value.toString())); + } + } + interfaces.removeDuplicates(); + deviceClass.setInterfaces(interfaces); + + if (!broken) { + m_deviceClasses.append(deviceClass); + } else { + qCWarning(dcDevice()) << "Skipping device class" << deviceClass.name(); + } + } + } +} + +QPair PluginMetadata::loadAndVerifyUnit(const QString &unitString) +{ + if (unitString.isEmpty()) + return QPair(true, Types::UnitNone); + + QMetaObject metaObject = Types::staticMetaObject; + int enumIndex = metaObject.indexOfEnumerator(QString("Unit").toLatin1().data()); + QMetaEnum metaEnum = metaObject.enumerator(enumIndex); + + int enumValue = -1; + for (int i = 0; i < metaEnum.keyCount(); i++) { + if (QString(metaEnum.valueToKey(metaEnum.value(i))) == QString("Unit" + unitString)) { + enumValue = metaEnum.value(i); + break; + } + } + + // inform the plugin developer about the error in the plugin json file + if (enumValue == -1) { + qCWarning(dcDeviceManager()) << QString("\"%1\" plugin:").arg(pluginName()).toLatin1().data() << QString("Invalid unit type \"%1\" in json file.").arg(unitString).toLatin1().data(); + return QPair(false, Types::UnitNone); + } + + return QPair(true, (Types::Unit)enumValue); +} + +QPair PluginMetadata::verifyFields(const QStringList &possibleFields, const QStringList &mandatoryFields, const QJsonObject &value) +{ + QStringList missingFields; + QStringList unknownFields; + + // Check if we have an unknown field + foreach (const QString &property, value.keys()) { + if (!possibleFields.contains(property)) { + unknownFields << property; + } + } + + // Check if a mandatory field is missing + foreach (const QString &field, mandatoryFields) { + if (!value.contains(field)) { + missingFields << field; + } + } + + return QPair(missingFields, unknownFields); +} + +QPair PluginMetadata::parseParamTypes(const QJsonArray &array) +{ + int index = 0; + QList paramTypes; + foreach (const QJsonValue ¶mTypesJson, array) { + QJsonObject pt = paramTypesJson.toObject(); + + QPair verificationResult = verifyFields(ParamType::typeProperties(), ParamType::mandatoryTypeProperties(), pt); + + // Check mandatory fields + if (!verificationResult.first.isEmpty()) { + qCWarning(dcDevice()) << pluginName() << "Error parsing ParamType: missing fields:" << verificationResult.first.join(", ") << endl << pt; + return QPair >(false, QList()); + } + + // Check if there are any unknown fields + if (!verificationResult.second.isEmpty()) { + qCWarning(dcDevice()) << pluginName() << "Error parsing ParamType: unknown fields:" << verificationResult.second.join(", ") << endl << pt; + return QPair >(false, QList()); + } + + // Check type + QVariant::Type t = QVariant::nameToType(pt.value("type").toString().toLatin1().data()); + if (t == QVariant::Invalid) { + qCWarning(dcDevice()) << pluginName() << QString("Invalid type %1 for param %2 in json file.") + .arg(pt.value("type").toString()) + .arg(pt.value("name").toString()).toLatin1().data(); + return QPair >(false, QList()); + } + + ParamType paramType(ParamTypeId(pt.value("id").toString()), pt.value("name").toString(), t, pt.value("defaultValue").toVariant()); + paramType.setDisplayName(pt.value("displayName").toString()); + + + // Set allowed values + QVariantList allowedValues; + foreach (const QJsonValue &allowedTypesJson, pt.value("allowedValues").toArray()) { + allowedValues.append(allowedTypesJson.toVariant()); + } + + // Set the input type if there is any + if (pt.contains("inputType")) { + QPair inputTypeVerification = loadAndVerifyInputType(pt.value("inputType").toString()); + if (!inputTypeVerification.first) { + qCWarning(dcDevice()) << pluginName() << QString("Invalid inputType for paramType") << pt; + return QPair >(false, QList()); + } else { + paramType.setInputType(inputTypeVerification.second); + } + } + + // set the unit if there is any + if (pt.contains("unit")) { + QPair unitVerification = loadAndVerifyUnit(pt.value("unit").toString()); + if (!unitVerification.first) { + qCWarning(dcDevice()) << pluginName() << QString("Invalid unit type for paramType") << pt; + return QPair >(false, QList()); + } else { + paramType.setUnit(unitVerification.second); + } + } + + // set readOnly if given (default false) + if (pt.contains("readOnly")) + paramType.setReadOnly(pt.value("readOnly").toBool()); + + paramType.setAllowedValues(allowedValues); + paramType.setLimits(pt.value("minValue").toVariant(), pt.value("maxValue").toVariant()); + paramType.setIndex(index++); + paramTypes.append(paramType); + } + + return QPair >(true, paramTypes); +} + +QPair PluginMetadata::loadAndVerifyInputType(const QString &inputType) +{ + if (inputType.isEmpty()) + return QPair(true, Types::InputTypeNone); + + QMetaObject metaObject = Types::staticMetaObject; + int enumIndex = metaObject.indexOfEnumerator(QString("InputType").toLatin1().data()); + QMetaEnum metaEnum = metaObject.enumerator(enumIndex); + + int enumValue = -1; + for (int i = 0; i < metaEnum.keyCount(); i++) { + if (QString(metaEnum.valueToKey(metaEnum.value(i))) == QString("InputType" + inputType)) { + enumValue = metaEnum.value(i); + break; + } + } + + // inform the plugin developer about the error in the plugin json file + if (enumValue == -1) { + qCWarning(dcDeviceManager()) << QString("\"%1\" plugin:").arg(pluginName()).toLatin1().data() << QString("Invalid inputType \"%1\" in json file.").arg(inputType).toLatin1().data(); + return QPair(false, Types::InputTypeNone); + } + + return QPair(true, (Types::InputType)enumValue); +} diff --git a/libnymea/devices/pluginmetadata.h b/libnymea/devices/pluginmetadata.h new file mode 100644 index 00000000..b5a1a54c --- /dev/null +++ b/libnymea/devices/pluginmetadata.h @@ -0,0 +1,66 @@ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * + * * + * Copyright (C) 2019 Michael Zanetti * + * * + * This file is part of nymea. * + * * + * This library is free software; you can redistribute it and/or * + * modify it under the terms of the GNU Lesser General Public * + * License as published by the Free Software Foundation; either * + * version 2.1 of the License, or (at your option) any later version. * + * * + * This library is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * + * Lesser General Public License for more details. * + * * + * You should have received a copy of the GNU Lesser General Public * + * License along with this library; If not, see * + * . * + * * + * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +#ifndef PLUGINMETADATA_H +#define PLUGINMETADATA_H + +#include "types/paramtype.h" +#include "types/deviceclass.h" + +class PluginMetadata +{ +public: + PluginMetadata(); + PluginMetadata(const QJsonObject &jsonObject, bool isBuiltIn = false); + + bool isValid() const; + + PluginId pluginId() const; + QString pluginName() const; + QString pluginDisplayName() const; + bool isBuiltIn() const; + + ParamTypes pluginSettings() const; + + Vendors vendors() const; + DeviceClasses deviceClasses() const; + + +private: + void parse(const QJsonObject &jsonObject); + QPair parseParamTypes(const QJsonArray &array); + QPair verifyFields(const QStringList &possibleFields, const QStringList &mandatoryFields, const QJsonObject &value); + QPair loadAndVerifyUnit(const QString &unitString); + QPair loadAndVerifyInputType(const QString &inputType); + +private: + bool m_isValid = false; + bool m_isBuiltIn = false; + PluginId m_pluginId; + QString m_pluginName; + QString m_pluginDisplayName; + ParamTypes m_pluginSettings; + Vendors m_vendors; + DeviceClasses m_deviceClasses; +}; + +#endif // PLUGINMETADATA_H diff --git a/libnymea/libnymea.pro b/libnymea/libnymea.pro index 50cf0d78..e090a616 100644 --- a/libnymea/libnymea.pro +++ b/libnymea/libnymea.pro @@ -8,17 +8,20 @@ DEFINES += LIBNYMEA_LIBRARY QMAKE_LFLAGS += -fPIC -HEADERS += devicemanager.h \ +HEADERS += \ + devices/devicemanager.h \ + devices/deviceutils.h \ + devices/pluginmetadata.h \ libnymea.h \ platform/package.h \ platform/repository.h \ typeutils.h \ loggingcategories.h \ nymeasettings.h \ - plugin/device.h \ - plugin/deviceplugin.h \ - plugin/devicedescriptor.h \ - plugin/devicepairinginfo.h \ + devices/device.h \ + devices/deviceplugin.h \ + devices/devicedescriptor.h \ + devices/devicepairinginfo.h \ hardware/gpio.h \ hardware/gpiomonitor.h \ hardware/pwm.h \ @@ -66,20 +69,22 @@ HEADERS += devicemanager.h \ nymeadbusservice.h \ network/mqtt/mqttprovider.h \ network/mqtt/mqttchannel.h \ - translator.h \ platform/platformsystemcontroller.h \ platform/platformupdatecontroller.h \ platform/platformzeroconfcontroller.h \ -SOURCES += devicemanager.cpp \ +SOURCES += \ + devices/devicemanager.cpp \ + devices/deviceutils.cpp \ + devices/pluginmetadata.cpp \ loggingcategories.cpp \ nymeasettings.cpp \ platform/package.cpp \ platform/repository.cpp \ - plugin/device.cpp \ - plugin/deviceplugin.cpp \ - plugin/devicedescriptor.cpp \ - plugin/devicepairinginfo.cpp \ + devices/device.cpp \ + devices/deviceplugin.cpp \ + devices/devicedescriptor.cpp \ + devices/devicepairinginfo.cpp \ hardware/gpio.cpp \ hardware/gpiomonitor.cpp \ hardware/pwm.cpp \ @@ -127,7 +132,6 @@ SOURCES += devicemanager.cpp \ nymeadbusservice.cpp \ network/mqtt/mqttprovider.cpp \ network/mqtt/mqttchannel.cpp \ - translator.cpp \ platform/platformsystemcontroller.cpp \ platform/platformupdatecontroller.cpp \ platform/platformzeroconfcontroller.cpp \ @@ -139,12 +143,12 @@ RESOURCES += \ ## Install instructions # install plugininfo python script for libnymea-dev -generateplugininfo.files = plugin/nymea-generateplugininfo +generateplugininfo.files = devices/nymea-generateplugininfo generateplugininfo.path = $$[QT_INSTALL_PREFIX]/bin INSTALLS += generateplugininfo # install plugin.pri for external plugins -pluginpri.files = plugin/plugin.pri +pluginpri.files = devices/plugin.pri pluginpri.path = $$[QT_INSTALL_PREFIX]/include/nymea/ INSTALLS += pluginpri diff --git a/libnymea/loggingcategories.cpp b/libnymea/loggingcategories.cpp index 4496ef6c..e699bb34 100644 --- a/libnymea/loggingcategories.cpp +++ b/libnymea/loggingcategories.cpp @@ -23,6 +23,7 @@ #include "loggingcategories.h" Q_LOGGING_CATEGORY(dcApplication, "Application") +Q_LOGGING_CATEGORY(dcDevice, "Device") Q_LOGGING_CATEGORY(dcDeviceManager, "DeviceManager") Q_LOGGING_CATEGORY(dcSystem, "System") Q_LOGGING_CATEGORY(dcPlatform, "Platform") diff --git a/libnymea/loggingcategories.h b/libnymea/loggingcategories.h index 12d303f5..a79a66ba 100644 --- a/libnymea/loggingcategories.h +++ b/libnymea/loggingcategories.h @@ -28,6 +28,7 @@ // Core / libnymea Q_DECLARE_LOGGING_CATEGORY(dcApplication) +Q_DECLARE_LOGGING_CATEGORY(dcDevice) Q_DECLARE_LOGGING_CATEGORY(dcDeviceManager) Q_DECLARE_LOGGING_CATEGORY(dcSystem) Q_DECLARE_LOGGING_CATEGORY(dcPlatform) diff --git a/libnymea/network/upnp/upnpdiscovery.h b/libnymea/network/upnp/upnpdiscovery.h index eff50f10..78fad0c3 100644 --- a/libnymea/network/upnp/upnpdiscovery.h +++ b/libnymea/network/upnp/upnpdiscovery.h @@ -32,7 +32,6 @@ #include #include "libnymea.h" -#include "devicemanager.h" #include "hardwareresource.h" #include "upnpdiscoveryreply.h" #include "upnpdevicedescriptor.h" diff --git a/libnymea/plugin/deviceplugin.cpp b/libnymea/plugin/deviceplugin.cpp deleted file mode 100644 index 58f675c4..00000000 --- a/libnymea/plugin/deviceplugin.cpp +++ /dev/null @@ -1,1145 +0,0 @@ -/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * - * * - * Copyright (C) 2015-2018 Simon Stürz * - * Copyright (C) 2014 Michael Zanetti * - * * - * This file is part of nymea. * - * * - * This library is free software; you can redistribute it and/or * - * modify it under the terms of the GNU Lesser General Public * - * License as published by the Free Software Foundation; either * - * version 2.1 of the License, or (at your option) any later version. * - * * - * This library is distributed in the hope that it will be useful, * - * but WITHOUT ANY WARRANTY; without even the implied warranty of * - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * - * Lesser General Public License for more details. * - * * - * You should have received a copy of the GNU Lesser General Public * - * License along with this library; If not, see * - * . * - * * - * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ - -/*! - \class DevicePlugin - \brief This is the base class interface for device plugins. - - \ingroup devices - \inmodule libnymea - -*/ - - -/*! \fn void DevicePlugin::devicesDiscovered(const DeviceClassId &deviceClassId, const QList &devices); - Emit this signal when the discovery of a \a deviceClassId of this DevicePlugin is finished. The \a devices parameter describes the - list of \l{DeviceDescriptor}{DeviceDescriptors} of all discovered \l{Device}{Devices}. - Note: During a discovery a plugin should always return the full result set. So even if a device is already known to the system and - a later discovery finds the device again, it should be included in the result set but the DeviceDescriptor's deviceId should be set - to the device ID. - \sa discoverDevices() -*/ - -/*! \fn void DevicePlugin::pairingFinished(const PairingTransactionId &pairingTransactionId, DeviceManager::DeviceSetupStatus status); - This signal is emitted when the pairing of a \a pairingTransactionId is finished. - The \a status of the will be described as \l{DeviceManager::DeviceError}{DeviceError}. - \sa confirmPairing() -*/ - -/*! \fn void DevicePlugin::deviceSetupFinished(Device *device, DeviceManager::DeviceSetupStatus status); - This signal is emitted when the setup of a \a device in this DevicePlugin is finished. The \a status parameter describes the - \l{DeviceManager::DeviceError}{DeviceError} that occurred. -*/ - -/*! \fn void DevicePlugin::configValueChanged(const ParamTypeId ¶mTypeId, const QVariant &value); - This signal is emitted when the \l{Param} with a certain \a paramTypeId of a \l{Device} configuration changed the \a value. -*/ - -/*! \fn void DevicePlugin::actionExecutionFinished(const ActionId &id, DeviceManager::DeviceError status) - This signal is to be emitted when you previously have returned \l{DeviceManager}{DeviceErrorAsync} - in a call of executeAction(). The \a id refers to the executed \l{Action}. The \a status of the \l{Action} - execution will be described as \l{DeviceManager::DeviceError}{DeviceError}. -*/ - -/*! \fn void DevicePlugin::autoDevicesAppeared(const DeviceClassId &deviceClassId, const QList &deviceDescriptors) - This signal is emitted when a new \l{Device} of certain \a deviceClassId appeared. The description of the \l{Device}{Devices} - will be in \a deviceDescriptors. This signal can only emitted from devices with the \l{DeviceClass}{CreateMethodAuto}. -*/ - -/*! \fn void DevicePlugin::autoDeviceDisappeared(const DeviceId &id) - Emit this signal when a device with the given \a id and which was created by \l{DevicePlugin::autoDevicesAppeared} has been removed from the system. - Be careful with this, as this will completely remove the device from the system and with it all the associated rules. Only - emit this if you are sure that a device will never come back. This signal should not be emitted for child auto devices - when the parent who created them is removed. The system will automatically remove all child devices in such a case. -*/ - -/*! \fn void DevicePlugin::emitEvent(const Event &event) - To produce a new event in the system, create a new \l{Event} and emit it with \a event. - Usually events are emitted in response to incoming data or other other events happening. Find a configured - \l{Device} from the \l{DeviceManager} and get its \l{EventType}{EventTypes}, then - create a \l{Event} complying to that \l{EventType} and emit it here. -*/ - -/*! \fn void DevicePlugin::init() - This will be called after constructing the DevicePlugin. Override this to do any - initialisation work you need to do. -*/ - -#include "deviceplugin.h" -#include "loggingcategories.h" - -#include "devicemanager.h" -#include "nymeasettings.h" - -#include "hardware/radio433/radio433.h" -#include "network/upnp/upnpdiscovery.h" - -#include -#include -#include -#include -#include -#include -#include - -/*! DevicePlugin constructor. DevicePlugins will be instantiated by the DeviceManager, its \a parent. */ -DevicePlugin::DevicePlugin(QObject *parent): - QObject(parent) -{ -} - -/*! Virtual destructor... */ -DevicePlugin::~DevicePlugin() -{ - -} - -/*! Returns the name of this DevicePlugin. */ -QString DevicePlugin::pluginName() const -{ - return m_metaData.value("name").toString(); -} - -/*! Returns the displayName of this DevicePlugin, to be shown to the user, translated. */ -QString DevicePlugin::pluginDisplayName() const -{ - return m_metaData.value("displayName").toString(); -} - -/*! Returns the id of this DevicePlugin. - * When implementing a plugin, generate a new uuid and return it here. Always return the - * same uuid and don't change it or configurations can't be matched any more. */ -PluginId DevicePlugin::pluginId() const -{ - return PluginId(m_metaData.value("id").toString()); -} - -/*! Returns the list of \l{Vendor}{Vendors} supported by this DevicePlugin. */ -QList DevicePlugin::supportedVendors() const -{ - QList vendors; - foreach (const QJsonValue &vendorJson, m_metaData.value("vendors").toArray()) { - Vendor vendor(vendorJson.toObject().value("id").toString(), vendorJson.toObject().value("name").toString()); - vendor.setDisplayName(vendorJson.toObject().value("displayName").toString()); - vendors.append(vendor); - } - return vendors; -} - -/*! Return a list of \l{DeviceClass}{DeviceClasses} describing all the devices supported by this plugin. - If a DeviceClass has an invalid parameter it will be ignored. -*/ -QList DevicePlugin::supportedDevices() const -{ - return m_supportedDevices; -} - -/*! Override this if your plugin supports Device with DeviceClass::CreationMethodAuto. - This will be called at startup, after the configured devices have been loaded. - This is the earliest time you should start emitting autoDevicesAppeared(). If you - are monitoring some hardware/service for devices to appear, start monitoring now. - If you are building the devices based on a static list, you may emit - autoDevicesAppeard() in here. -*/ -void DevicePlugin::startMonitoringAutoDevices() -{ - -} - -/*! Reimplement this if you support a DeviceClass with createMethod \l{DeviceManager}{CreateMethodDiscovery}. - This will be called to discover Devices for the given \a deviceClassId with the given \a params. This will always - be an async operation. Return \l{DeviceManager}{DeviceErrorAsync} or \l{DeviceManager}{DeviceErrorNoError} - if the discovery has been started successfully. Return an appropriate error otherwise. - Once devices are discovered, emit devicesDiscovered(). -*/ -DeviceManager::DeviceError DevicePlugin::discoverDevices(const DeviceClassId &deviceClassId, const ParamList ¶ms) -{ - Q_UNUSED(deviceClassId) - Q_UNUSED(params) - return DeviceManager::DeviceErrorCreationMethodNotSupported; -} - -/*! This will be called when a new device is created. The plugin has the chance to do some setup. - Return \l{DeviceManager}{DeviceSetupStatusFailure} if something bad happened during the setup in which case the \a device - will be disabled. Return \l{DeviceManager}{DeviceSetupStatusSuccess} if everything went well. If you can't tell yet and - need more time to set up the \a device (note: you should never block in this method) you can - return \l{DeviceManager}{DeviceSetupStatusAsync}. In that case the \l{DeviceManager} will wait for you to emit - \l{DevicePlugin}{deviceSetupFinished} to report the status. -*/ -DeviceManager::DeviceSetupStatus DevicePlugin::setupDevice(Device *device) -{ - Q_UNUSED(device) - return DeviceManager::DeviceSetupStatusSuccess; -} - -/*! This will be called when a new \a device was added successfully and the device setup is finished.*/ -void DevicePlugin::postSetupDevice(Device *device) -{ - Q_UNUSED(device) -} - -/*! This will be called when a \a device removed. The plugin has the chance to do some teardown. - The device is still valid during this call, but already removed from the system. - The device will be deleted as soon as this method returns. -*/ -void DevicePlugin::deviceRemoved(Device *device) -{ - Q_UNUSED(device) -} - -/*! This method will be called for \l{Device}{Devices} with the \l{DeviceClass::SetupMethodDisplayPin} right after the paring request - with the given \a pairingTransactionId for the given \a deviceDescriptor. -*/ -DeviceManager::DeviceError DevicePlugin::displayPin(const PairingTransactionId &pairingTransactionId, const DeviceDescriptor &deviceDescriptor) -{ - Q_UNUSED(pairingTransactionId) - Q_UNUSED(deviceDescriptor) - - qCWarning(dcDeviceManager) << "Plugin does not implement the display pin setup method."; - - return DeviceManager::DeviceErrorNoError; -} - -/*! Confirms the pairing of a \a deviceClassId with the given \a pairingTransactionId and \a params. - Returns \l{DeviceManager::DeviceError}{DeviceError} to inform about the result. The optional paramerter - \a secret contains for example the pin for \l{Device}{Devices} with the setup method \l{DeviceClass::SetupMethodDisplayPin}. -*/ -DeviceManager::DeviceSetupStatus DevicePlugin::confirmPairing(const PairingTransactionId &pairingTransactionId, const DeviceClassId &deviceClassId, const ParamList ¶ms, const QString &secret = QString()) -{ - Q_UNUSED(pairingTransactionId) - Q_UNUSED(deviceClassId) - Q_UNUSED(params) - Q_UNUSED(secret) - - qCWarning(dcDeviceManager) << "Plugin does not implement pairing."; - return DeviceManager::DeviceSetupStatusFailure; -} - -/*! This will be called to actually execute actions on the hardware. The \{Device} and - the \{Action} are contained in the \a device and \a action parameters. - Return the appropriate \l{DeviceManager::DeviceError}{DeviceError}. - - It is possible to execute actions asynchronously. You never should do anything blocking for - a long time (e.g. wait on a network reply from the internet) but instead return - DeviceManager::DeviceErrorAsync and continue processing in an async manner. Once - you have the reply ready, emit actionExecutionFinished() with the appropriate parameters. - - \sa actionExecutionFinished() -*/ -DeviceManager::DeviceError DevicePlugin::executeAction(Device *device, const Action &action) -{ - Q_UNUSED(device) - Q_UNUSED(action) - return DeviceManager::DeviceErrorNoError; -} - -/*! Returns the configuration description of this DevicePlugin as a list of \l{ParamType}{ParamTypes}. */ -ParamTypes DevicePlugin::configurationDescription() const -{ - return m_configurationDescription; -} - -/*! This will be called when the DeviceManager initializes the plugin and set up the things behind the scenes. - When implementing a new plugin, use \l{DevicePlugin::init()} instead in order to do initialisation work. - The \l{DevicePlugin::init()} method will be called once the plugin configuration has been loaded. */ -void DevicePlugin::initPlugin(DeviceManager *deviceManager) -{ - m_deviceManager = deviceManager; - loadMetaData(); -} - -QPair > DevicePlugin::parseParamTypes(const QJsonArray &array) const -{ - int index = 0; - QList paramTypes; - foreach (const QJsonValue ¶mTypesJson, array) { - QJsonObject pt = paramTypesJson.toObject(); - - QPair verificationResult = verifyFields(ParamType::typeProperties(), ParamType::mandatoryTypeProperties(), pt); - - // Check mandatory fields - if (!verificationResult.first.isEmpty()) { - qCWarning(dcDeviceManager()) << pluginName() << "Error parsing ParamType: missing fields:" << verificationResult.first.join(", ") << endl << pt; - return QPair >(false, QList()); - } - - // Check if there are any unknown fields - if (!verificationResult.second.isEmpty()) { - qCWarning(dcDeviceManager()) << pluginName() << "Error parsing ParamType: unknown fields:" << verificationResult.second.join(", ") << endl << pt; - return QPair >(false, QList()); - } - - // Check type - QVariant::Type t = QVariant::nameToType(pt.value("type").toString().toLatin1().data()); - if (t == QVariant::Invalid) { - qCWarning(dcDeviceManager()) << pluginName() << QString("Invalid type %1 for param %2 in json file.") - .arg(pt.value("type").toString()) - .arg(pt.value("name").toString()).toLatin1().data(); - return QPair >(false, QList()); - } - - ParamType paramType(ParamTypeId(pt.value("id").toString()), pt.value("name").toString(), t, pt.value("defaultValue").toVariant()); - paramType.setDisplayName(pt.value("displayName").toString()); - - - // Set allowed values - QVariantList allowedValues; - foreach (const QJsonValue &allowedTypesJson, pt.value("allowedValues").toArray()) { - allowedValues.append(allowedTypesJson.toVariant()); - } - - // Set the input type if there is any - if (pt.contains("inputType")) { - QPair inputTypeVerification = loadAndVerifyInputType(pt.value("inputType").toString()); - if (!inputTypeVerification.first) { - qCWarning(dcDeviceManager()) << pluginName() << QString("Invalid inputType for paramType") << pt; - return QPair >(false, QList()); - } else { - paramType.setInputType(inputTypeVerification.second); - } - } - - // set the unit if there is any - if (pt.contains("unit")) { - QPair unitVerification = loadAndVerifyUnit(pt.value("unit").toString()); - if (!unitVerification.first) { - qCWarning(dcDeviceManager()) << pluginName() << QString("Invalid unit type for paramType") << pt; - return QPair >(false, QList()); - } else { - paramType.setUnit(unitVerification.second); - } - } - - // set readOnly if given (default false) - if (pt.contains("readOnly")) - paramType.setReadOnly(pt.value("readOnly").toBool()); - - paramType.setAllowedValues(allowedValues); - paramType.setLimits(pt.value("minValue").toVariant(), pt.value("maxValue").toVariant()); - paramType.setIndex(index++); - paramTypes.append(paramType); - } - - return QPair >(true, paramTypes); -} - -QPair DevicePlugin::verifyFields(const QStringList &possibleFields, const QStringList &mandatoryFields, const QJsonObject &value) const -{ - QStringList missingFields; - QStringList unknownFields; - - // Check if we have an unknown field - foreach (const QString &property, value.keys()) { - if (!possibleFields.contains(property)) { - unknownFields << property; - } - } - - // Check if a mandatory field is missing - foreach (const QString &field, mandatoryFields) { - if (!value.contains(field)) { - missingFields << field; - } - } - - return QPair(missingFields, unknownFields); -} - -/*! Returns a map containing the plugin configuration. - When implementing a new plugin, override this and fill in the empty configuration if your plugin requires any. -*/ -ParamList DevicePlugin::configuration() const -{ - return m_config; -} - -/*! Use this to retrieve the values for your parameters. Values might not be set - at the time when your plugin is loaded, but will be set soon after. Listen to - configurationValueChanged() to know when something changes. - When implementing a new plugin, specify in configurationDescription() what you want to see here. - Returns the config value of a \l{Param} with the given \a paramTypeId of this DevicePlugin. -*/ -QVariant DevicePlugin::configValue(const ParamTypeId ¶mTypeId) const -{ - return m_config.paramValue(paramTypeId); -} - -/*! Will be called by the DeviceManager to set a plugin's \a configuration. */ -DeviceManager::DeviceError DevicePlugin::setConfiguration(const ParamList &configuration) -{ - foreach (const Param ¶m, configuration) { - qCDebug(dcDeviceManager()) << "* Set plugin configuration" << param; - DeviceManager::DeviceError result = setConfigValue(param.paramTypeId(), param.value()); - if (result != DeviceManager::DeviceErrorNoError) - return result; - - } - return DeviceManager::DeviceErrorNoError; -} - -/*! Can be called in the DevicePlugin to set a plugin's \l{Param} with the given \a paramTypeId and \a value. */ -DeviceManager::DeviceError DevicePlugin::setConfigValue(const ParamTypeId ¶mTypeId, const QVariant &value) -{ - bool found = false; - foreach (const ParamType ¶mType, configurationDescription()) { - if (paramType.id() == paramTypeId) { - found = true; - DeviceManager::DeviceError result = deviceManager()->verifyParam(paramType, Param(paramTypeId, value)); - if (result != DeviceManager::DeviceErrorNoError) - return result; - - break; - } - } - - if (!found) { - qCWarning(dcDeviceManager()) << QString("Could not find plugin parameter with the id %1.").arg(paramTypeId.toString()); - return DeviceManager::DeviceErrorInvalidParameter; - } - - if (m_config.hasParam(paramTypeId)) { - if (!m_config.setParamValue(paramTypeId, value)) { - qCWarning(dcDeviceManager()) << "Could not set param value" << value << "for param with id" << paramTypeId.toString(); - return DeviceManager::DeviceErrorInvalidParameter; - } - } else { - m_config.append(Param(paramTypeId, value)); - } - - emit configValueChanged(paramTypeId, value); - return DeviceManager::DeviceErrorNoError; -} - -bool DevicePlugin::isBuiltIn() const -{ - return m_metaData.value("builtIn").toBool(); -} - -/*! Returns a pointer to the \l{DeviceManager}. - When implementing a plugin, use this to find the \l{Device}{Devices} you need. -*/ -DeviceManager *DevicePlugin::deviceManager() const -{ - return m_deviceManager; -} - -/*! Returns a list of all configured devices belonging to this plugin. */ -Devices DevicePlugin::myDevices() const -{ - QList myDeviceClassIds; - foreach (const DeviceClass &deviceClass, m_supportedDevices) { - myDeviceClassIds.append(deviceClass.id()); - } - - QList ret; - foreach (Device *device, deviceManager()->configuredDevices()) { - if (myDeviceClassIds.contains(device->deviceClassId())) { - ret.append(device); - } - } - return ret; -} - -/*! Returns the pointer to the main \l{HardwareManager} of this server. */ -HardwareManager *DevicePlugin::hardwareManager() const -{ - return m_deviceManager->hardwareManager(); -} - -/*! Find a certain device from myDevices() by its \a params. All parameters must - match or the device will not be found. Be prepared for nullptrs. -*/ -Device *DevicePlugin::findDeviceByParams(const ParamList ¶ms) const -{ - foreach (Device *device, myDevices()) { - bool matching = true; - foreach (const Param ¶m, params) { - if (device->paramValue(param.paramTypeId()) != param.value()) { - matching = false; - } - } - if (matching) { - return device; - } - } - return nullptr; -} - -void DevicePlugin::setMetaData(const QJsonObject &metaData) -{ - m_metaData = metaData; -} - -void DevicePlugin::loadMetaData() -{ - - m_configurationDescription.clear(); - m_supportedDevices.clear(); - - // parse plugin configuration params - if (m_metaData.contains("paramTypes")) { - QPair > paramVerification = parseParamTypes(m_metaData.value("paramTypes").toArray()); - if (paramVerification.first) - m_configurationDescription << paramVerification.second; - - } - - // Note: The DevicePlugin has no type class, so we define the json properties here - QStringList pluginMandatoryJsonProperties = QStringList() << "id" << "name" << "displayName" << "vendors"; - QStringList pluginJsonProperties = QStringList() << "id" << "name" << "displayName" << "vendors" << "paramTypes" << "builtIn"; - - QPair verificationResult = verifyFields(pluginJsonProperties, pluginMandatoryJsonProperties, m_metaData); - - // Check mandatory fields - if (!verificationResult.first.isEmpty()) { - qCWarning(dcDeviceManager()) << pluginName() << "Skipping plugin because of missing fields:" << verificationResult.first.join(", ") << endl << m_metaData; - return; - } - - // Check if there are any unknown fields - if (!verificationResult.second.isEmpty()) { - qCWarning(dcDeviceManager()) << pluginName() << "Skipping plugin because of unknown fields:" << verificationResult.second.join(", ") << endl << m_metaData; - return; - } - - // Load vendors - foreach (const QJsonValue &vendorJson, m_metaData.value("vendors").toArray()) { - bool broken = false; - QJsonObject vendorObject = vendorJson.toObject(); - - // Note: The Vendor has no type class, so we define the json properties here - QStringList vendorMandatoryJsonProperties = QStringList() << "id" << "name" << "displayName" << "deviceClasses"; - QStringList vendorJsonProperties = QStringList() << "id" << "name" << "displayName" << "deviceClasses"; - - QPair verificationResult = verifyFields(vendorJsonProperties, vendorMandatoryJsonProperties, vendorObject); - - // Check mandatory fields - if (!verificationResult.first.isEmpty()) { - qCWarning(dcDeviceManager()) << pluginName() << "Skipping vendor because of missing fields:" << verificationResult.first.join(", ") << endl << vendorObject; - broken = true; - break; - } - - // Check if there are any unknown fields - if (!verificationResult.second.isEmpty()) { - qCWarning(dcDeviceManager()) << pluginName() << "Skipping vendor because of unknown fields:" << verificationResult.second.join(", ") << endl << vendorObject; - broken = true; - break; - } - - VendorId vendorId = vendorObject.value("id").toString(); - - // Load deviceclasses of this vendor - foreach (const QJsonValue &deviceClassJson, vendorJson.toObject().value("deviceClasses").toArray()) { - QJsonObject deviceClassObject = deviceClassJson.toObject(); - QPair verificationResult = verifyFields(DeviceClass::typeProperties(), DeviceClass::mandatoryTypeProperties(), deviceClassObject); - - // Check mandatory fields - if (!verificationResult.first.isEmpty()) { - qCWarning(dcDeviceManager()) << pluginName() << "Skipping device class because of missing fields:" << verificationResult.first.join(", ") << endl << deviceClassObject; - broken = true; - break; - } - - // Check if there are any unknown fields - if (!verificationResult.second.isEmpty()) { - qCWarning(dcDeviceManager()) << pluginName() << "Skipping device class because of unknown fields:" << verificationResult.second.join(", ") << endl << deviceClassObject; - broken = true; - break; - } - - DeviceClass deviceClass(pluginId(), vendorId, deviceClassObject.value("id").toString()); - deviceClass.setName(deviceClassObject.value("name").toString()); - deviceClass.setDisplayName(deviceClassObject.value("displayName").toString()); - - // Read create methods - DeviceClass::CreateMethods createMethods; - if (!deviceClassObject.contains("createMethods")) { - // Default if not specified - createMethods |= DeviceClass::CreateMethodUser; - } else { - foreach (const QJsonValue &createMethodValue, deviceClassObject.value("createMethods").toArray()) { - if (createMethodValue.toString().toLower() == "discovery") { - createMethods |= DeviceClass::CreateMethodDiscovery; - } else if (createMethodValue.toString().toLower() == "auto") { - createMethods |= DeviceClass::CreateMethodAuto; - } else if (createMethodValue.toString().toLower() == "user") { - createMethods |= DeviceClass::CreateMethodUser; - } else { - qCWarning(dcDeviceManager()) << "Unknown createMehtod" << createMethodValue.toString() << "in deviceClass " - << deviceClass.name() << ". Falling back to CreateMethodUser."; - createMethods |= DeviceClass::CreateMethodUser; - } - } - } - deviceClass.setCreateMethods(createMethods); - - // Read params - QPair > paramTypesVerification = parseParamTypes(deviceClassObject.value("paramTypes").toArray()); - if (!paramTypesVerification.first) { - broken = true; - break; - } else { - deviceClass.setParamTypes(paramTypesVerification.second); - } - - // Read settings - QPair > settingsTypesVerification = parseParamTypes(deviceClassObject.value("settingsTypes").toArray()); - if (!settingsTypesVerification.first) { - broken = true; - break; - } else { - deviceClass.setSettingsTypes(settingsTypesVerification.second); - } - - // Read discover params - QPair > discoveryParamVerification = parseParamTypes(deviceClassObject.value("discoveryParamTypes").toArray()); - if (!discoveryParamVerification.first) { - broken = true; - break; - } else { - deviceClass.setDiscoveryParamTypes(discoveryParamVerification.second); - } - - // Read setup method - DeviceClass::SetupMethod setupMethod = DeviceClass::SetupMethodJustAdd; - if (deviceClassObject.contains("setupMethod")) { - QString setupMethodString = deviceClassObject.value("setupMethod").toString(); - if (setupMethodString.toLower() == "pushbutton") { - setupMethod = DeviceClass::SetupMethodPushButton; - } else if (setupMethodString.toLower() == "displaypin") { - setupMethod = DeviceClass::SetupMethodDisplayPin; - } else if (setupMethodString.toLower() == "enterpin") { - setupMethod = DeviceClass::SetupMethodEnterPin; - } else if (setupMethodString.toLower() == "justadd") { - setupMethod = DeviceClass::SetupMethodJustAdd; - } else { - qCWarning(dcDeviceManager()) << "Unknown setupMehtod" << setupMethod << "in deviceClass" - << deviceClass.name() << ". Falling back to SetupMethodJustAdd."; - setupMethod = DeviceClass::SetupMethodJustAdd; - } - } - deviceClass.setSetupMethod(setupMethod); - - // Read pairing info - deviceClass.setPairingInfo(deviceClassObject.value("pairingInfo").toString()); - - QList actionTypes; - QList stateTypes; - QList eventTypes; - - // Read StateTypes - int index = 0; - foreach (const QJsonValue &stateTypesJson, deviceClassObject.value("stateTypes").toArray()) { - QJsonObject st = stateTypesJson.toObject(); - bool writableState = false; - - QPair verificationResult = verifyFields(StateType::typeProperties(), StateType::mandatoryTypeProperties(), st); - - // Check mandatory fields - if (!verificationResult.first.isEmpty()) { - qCWarning(dcDeviceManager()) << "Skipping device class" << deviceClass.name() << "because of missing" << verificationResult.first.join(", ") << "in stateType" << st; - broken = true; - break; - } - - // Check if there are any unknown fields - if (!verificationResult.second.isEmpty()) { - qCWarning(dcDeviceManager()) << "Skipping device class" << deviceClass.name() << "because of unknown properties" << verificationResult.second.join(", ") << "in stateType" << st; - broken = true; - break; - } - - // If this is a writable stateType, there must be also the displayNameAction property - if (st.contains("writable") && st.value("writable").toBool()) { - writableState = true; - if (!st.contains("displayNameAction")) { - qCWarning(dcDeviceManager()) << "Skipping device class" << deviceClass.name() << ". The state is writable, but does not define the displayNameAction property" << st; - broken = true; - break; - } - } - - QVariant::Type t = QVariant::nameToType(st.value("type").toString().toLatin1().data()); - if (t == QVariant::Invalid) { - qCWarning(dcDeviceManager()) << "Invalid StateType type:" << st.value("type").toString(); - broken = true; - break; - } - - StateType stateType(st.value("id").toString()); - stateType.setName(st.value("name").toString()); - stateType.setDisplayName(st.value("displayName").toString()); - stateType.setIndex(index++); - stateType.setType(t); - QPair unitVerification = loadAndVerifyUnit(st.value("unit").toString()); - if (!unitVerification.first) { - broken = true; - break; - } else { - stateType.setUnit(unitVerification.second); - } - - stateType.setDefaultValue(st.value("defaultValue").toVariant()); - if (st.contains("minValue")) - stateType.setMinValue(st.value("minValue").toVariant()); - - if (st.contains("maxValue")) - stateType.setMaxValue(st.value("maxValue").toVariant()); - - if (st.contains("possibleValues")) { - QVariantList possibleValues; - foreach (const QJsonValue &possibleValueJson, st.value("possibleValues").toArray()) { - possibleValues.append(possibleValueJson.toVariant()); - } - stateType.setPossibleValues(possibleValues); - - if (!stateType.possibleValues().contains(stateType.defaultValue())) { - qCWarning(dcDeviceManager()) << QString("\"%1\" plugin:").arg(pluginName()).toLatin1().data() << QString("The given default value \"%1\" is not in the possible values of the stateType \"%2\".") - .arg(stateType.defaultValue().toString()).arg(stateType.name()).toLatin1().data(); - broken = true; - break; - } - } - - if (st.contains("cached")) { - stateType.setCached(st.value("cached").toBool()); - } - stateTypes.append(stateType); - - // Events for state changed - EventType eventType(EventTypeId(stateType.id().toString())); - eventType.setName(st.value("name").toString()); - eventType.setDisplayName(st.value("displayNameEvent").toString()); - ParamType paramType(ParamTypeId(stateType.id().toString()), st.value("name").toString(), stateType.type()); - paramType.setDisplayName(st.value("displayName").toString()); - paramType.setAllowedValues(stateType.possibleValues()); - paramType.setDefaultValue(stateType.defaultValue()); - paramType.setMinValue(stateType.minValue()); - paramType.setMaxValue(stateType.maxValue()); - paramType.setUnit(stateType.unit()); - eventType.setParamTypes(QList() << paramType); - eventType.setIndex(stateType.index()); - eventTypes.append(eventType); - - // ActionTypes for writeable StateTypes - if (writableState) { - ActionType actionType(ActionTypeId(stateType.id().toString())); - actionType.setName(stateType.name()); - actionType.setDisplayName(st.value("displayNameAction").toString()); - actionType.setIndex(stateType.index()); - actionType.setParamTypes(QList() << paramType); - actionTypes.append(actionType); - } - } - deviceClass.setStateTypes(stateTypes); - - // ActionTypes - index = 0; - foreach (const QJsonValue &actionTypesJson, deviceClassObject.value("actionTypes").toArray()) { - QJsonObject at = actionTypesJson.toObject(); - QPair verificationResult = verifyFields(ActionType::typeProperties(), ActionType::mandatoryTypeProperties(), at); - - // Check mandatory fields - if (!verificationResult.first.isEmpty()) { - qCWarning(dcDeviceManager()) << pluginName() << "Skipping device class" << deviceClass.name() << "because of missing" << verificationResult.first.join(", ") << "in action type:" << endl << at; - broken = true; - break; - } - - // Check if there are any unknown fields - if (!verificationResult.second.isEmpty()) { - qCWarning(dcDeviceManager()) << pluginName() << "Skipping device class" << deviceClass.name() << "because of unknown fields:" << verificationResult.second.join(", ") << "in action type:" << endl << at; - broken = true; - break; - } - - ActionType actionType(at.value("id").toString()); - actionType.setName(at.value("name").toString()); - actionType.setDisplayName(at.value("displayName").toString()); - actionType.setIndex(index++); - - QPair > paramVerification = parseParamTypes(at.value("paramTypes").toArray()); - if (!paramVerification.first) { - broken = true; - break; - } else { - actionType.setParamTypes(paramVerification.second); - } - - actionTypes.append(actionType); - } - deviceClass.setActionTypes(actionTypes); - - // EventTypes - index = 0; - foreach (const QJsonValue &eventTypesJson, deviceClassObject.value("eventTypes").toArray()) { - QJsonObject et = eventTypesJson.toObject(); - - QPair verificationResult = verifyFields(EventType::typeProperties(), EventType::mandatoryTypeProperties(), et); - - // Check mandatory fields - if (!verificationResult.first.isEmpty()) { - qCWarning(dcDeviceManager()) << pluginName() << "Skipping device class" << deviceClass.name() << "because of missing" << verificationResult.first.join(", ") << "in event type:" << endl << et; - broken = true; - break; - } - - // Check if there are any unknown fields - if (!verificationResult.second.isEmpty()) { - qCWarning(dcDeviceManager()) << pluginName() << "Skipping device class" << deviceClass.name() << "because of unknown fields:" << verificationResult.second.join(", ") << "in event type:" << endl << et; - broken = true; - break; - } - - EventType eventType(et.value("id").toString()); - eventType.setName(et.value("name").toString()); - eventType.setDisplayName(et.value("displayName").toString()); - eventType.setIndex(index++); - - QPair > paramVerification = parseParamTypes(et.value("paramTypes").toArray()); - if (!paramVerification.first) { - broken = true; - break; - } else { - eventType.setParamTypes(paramVerification.second); - } - eventTypes.append(eventType); - } - deviceClass.setEventTypes(eventTypes); - - // Read interfaces - QStringList interfaces; - foreach (const QJsonValue &value, deviceClassObject.value("interfaces").toArray()) { - Interface iface = loadInterface(value.toString()); - - StateTypes stateTypes(deviceClass.stateTypes()); - ActionTypes actionTypes(deviceClass.actionTypes()); - EventTypes eventTypes(deviceClass.eventTypes()); - - bool valid = true; - foreach (const StateType &ifaceStateType, iface.stateTypes()) { - StateType stateType = stateTypes.findByName(ifaceStateType.name()); - if (stateType.id().isNull()) { - qCWarning(dcDeviceManager()) << "DeviceClass" << deviceClass.name() << "claims to implement interface" << value.toString() << "but doesn't implement state" << ifaceStateType.name(); - valid = false; - continue; - } - if (ifaceStateType.type() != stateType.type()) { - qCWarning(dcDeviceManager()) << "DeviceClass" << deviceClass.name() << "claims to implement interface" << value.toString() << "but state" << stateType.name() << "has not matching type" << stateType.type() << "!=" << ifaceStateType.type(); - valid = false; - continue; - } - if (ifaceStateType.minValue().isValid() && !ifaceStateType.minValue().isNull()) { - if (ifaceStateType.minValue().toString() == "any") { - if (stateType.minValue().isNull()) { - qCWarning(dcDeviceManager()) << "DeviceClass" << deviceClass.name() << "claims to implement interface" << value.toString() << "but state" << stateType.name() << "has no minimum value defined."; - valid = false; - continue; - } - } else if (ifaceStateType.minValue() != stateType.minValue()) { - qCWarning(dcDeviceManager()) << "DeviceClass" << deviceClass.name() << "claims to implement interface" << value.toString() << "but state" << stateType.name() << "has not matching minimum value:" << ifaceStateType.minValue() << "!=" << stateType.minValue(); - valid = false; - continue; - } - } - if (ifaceStateType.maxValue().isValid() && !ifaceStateType.maxValue().isNull()) { - if (ifaceStateType.maxValue().toString() == "any") { - if (stateType.maxValue().isNull()) { - qCWarning(dcDeviceManager()) << "DeviceClass" << deviceClass.name() << "claims to implement interface" << value.toString() << "but state" << stateType.name() << "has no maximum value defined."; - valid = false; - continue; - } - } else if (ifaceStateType.maxValue() != stateType.maxValue()) { - qCWarning(dcDeviceManager()) << "DeviceClass" << deviceClass.name() << "claims to implement interface" << value.toString() << "but state" << stateType.name() << "has not matching maximum value:" << ifaceStateType.maxValue() << "!=" << stateType.minValue(); - valid = false; - continue; - } - } - if (!ifaceStateType.possibleValues().isEmpty() && ifaceStateType.possibleValues() != stateType.possibleValues()) { - qCWarning(dcDeviceManager()) << "DeviceClass" << deviceClass.name() << "claims to implement interface" << value.toString() << "but state" << stateType.name() << "has not matching allowed values" << ifaceStateType.possibleValues() << "!=" << stateType.possibleValues(); - valid = false; - continue; - } - } - - foreach (const ActionType &ifaceActionType, iface.actionTypes()) { - ActionType actionType = actionTypes.findByName(ifaceActionType.name()); - if (actionType.id().isNull()) { - qCWarning(dcDeviceManager) << "DeviceClass" << deviceClass.name() << "claims to implement interface" << value.toString() << "but doesn't implement action" << ifaceActionType.name(); - valid = false; - } - foreach (const ParamType &ifaceActionParamType, ifaceActionType.paramTypes()) { - ParamType paramType = actionType.paramTypes().findByName(ifaceActionParamType.name()); - if (!paramType.isValid()) { - qCWarning(dcDeviceManager) << "DeviceClass" << deviceClass.name() << "claims to implement interface" << value.toString() << "but doesn't implement action param" << ifaceActionType.name() << ":" << ifaceActionParamType.name(); - valid = false; - } else { - if (paramType.type() != ifaceActionParamType.type()) { - qCWarning(dcDeviceManager()) << "DeviceClass" << deviceClass.name() << "claims to implement interface" << value.toString() << "but param" << paramType.name() << "is of wrong type:" << QVariant::typeToName(paramType.type()) << "expected:" << QVariant::typeToName(ifaceActionParamType.type()); - valid = false; - } - } - } - } - - foreach (const EventType &ifaceEventType, iface.eventTypes()) { - EventType eventType = eventTypes.findByName(ifaceEventType.name()); - if (!eventType.isValid()) { - qCWarning(dcDeviceManager) << "DeviceClass" << deviceClass.name() << "claims to implement interface" << value.toString() << "but doesn't implement event" << ifaceEventType.name(); - valid = false; - } - foreach (const ParamType &ifaceEventParamType, ifaceEventType.paramTypes()) { - ParamType paramType = eventType.paramTypes().findByName(ifaceEventParamType.name()); - if (!paramType.isValid()) { - qCWarning(dcDeviceManager) << "DeviceClass" << deviceClass.name() << "claims to implement interface" << value.toString() << "but doesn't implement event param" << ifaceEventType.name() << ":" << ifaceEventParamType.name(); - valid = false; - } else { - if (paramType.type() != ifaceEventParamType.type()) { - qCWarning(dcDeviceManager()) << "DeviceClass" << deviceClass.name() << "claims to implement interface" << value.toString() << "but param" << paramType.name() << "is of wrong type:" << QVariant::typeToName(paramType.type()) << "expected:" << QVariant::typeToName(ifaceEventParamType.type()); - valid = false; - } - } - } - } - - if (valid) { - interfaces.append(generateInterfaceParentList(value.toString())); - } - } - interfaces.removeDuplicates(); - deviceClass.setInterfaces(interfaces); - - if (!broken) { - m_supportedDevices.append(deviceClass); - } else { - qCWarning(dcDeviceManager()) << "Skipping device class" << deviceClass.name(); - } - } - } -} - -QPair DevicePlugin::loadAndVerifyUnit(const QString &unitString) const -{ - if (unitString.isEmpty()) - return QPair(true, Types::UnitNone); - - QMetaObject metaObject = Types::staticMetaObject; - int enumIndex = metaObject.indexOfEnumerator(QString("Unit").toLatin1().data()); - QMetaEnum metaEnum = metaObject.enumerator(enumIndex); - - int enumValue = -1; - for (int i = 0; i < metaEnum.keyCount(); i++) { - if (QString(metaEnum.valueToKey(metaEnum.value(i))) == QString("Unit" + unitString)) { - enumValue = metaEnum.value(i); - break; - } - } - - // inform the plugin developer about the error in the plugin json file - if (enumValue == -1) { - qCWarning(dcDeviceManager()) << QString("\"%1\" plugin:").arg(pluginName()).toLatin1().data() << QString("Invalid unit type \"%1\" in json file.").arg(unitString).toLatin1().data(); - return QPair(false, Types::UnitNone); - } - - return QPair(true, (Types::Unit)enumValue); -} - -QPair DevicePlugin::loadAndVerifyInputType(const QString &inputType) const -{ - if (inputType.isEmpty()) - return QPair(true, Types::InputTypeNone); - - QMetaObject metaObject = Types::staticMetaObject; - int enumIndex = metaObject.indexOfEnumerator(QString("InputType").toLatin1().data()); - QMetaEnum metaEnum = metaObject.enumerator(enumIndex); - - int enumValue = -1; - for (int i = 0; i < metaEnum.keyCount(); i++) { - if (QString(metaEnum.valueToKey(metaEnum.value(i))) == QString("InputType" + inputType)) { - enumValue = metaEnum.value(i); - break; - } - } - - // inform the plugin developer about the error in the plugin json file - if (enumValue == -1) { - qCWarning(dcDeviceManager()) << QString("\"%1\" plugin:").arg(pluginName()).toLatin1().data() << QString("Invalid inputType \"%1\" in json file.").arg(inputType).toLatin1().data(); - return QPair(false, Types::InputTypeNone); - } - - return QPair(true, (Types::InputType)enumValue); -} - -Interfaces DevicePlugin::allInterfaces() -{ - Interfaces ret; - QDir dir(":/interfaces/"); - foreach (const QFileInfo &ifaceFile, dir.entryInfoList()) { - ret.append(loadInterface(ifaceFile.baseName())); - } - return ret; -} - -Interface DevicePlugin::loadInterface(const QString &name) -{ - Interface iface; - QFile f(QString(":/interfaces/%1.json").arg(name)); - if (!f.open(QFile::ReadOnly)) { - qCWarning(dcDeviceManager()) << "Failed to load interface" << name; - return iface; - } - QJsonParseError error; - QJsonDocument jsonDoc = QJsonDocument::fromJson(f.readAll(), &error); - if (error.error != QJsonParseError::NoError) { - qCWarning(dcDeviceManager) << "Cannot load interface definition for interface" << name << ":" << error.errorString(); - return iface; - } - QVariantMap content = jsonDoc.toVariant().toMap(); - if (content.contains("extends")) { - if (!content.value("extends").toString().isEmpty()) { - iface = loadInterface(content.value("extends").toString()); - } else if (content.value("extends").toList().count() > 0) { - foreach (const QVariant &extendedIface, content.value("extends").toList()) { - Interface tmp = loadInterface(extendedIface.toString()); - iface = mergeInterfaces(iface, tmp); - } - } - } - - StateTypes stateTypes; - ActionTypes actionTypes; - EventTypes eventTypes; - foreach (const QVariant &stateVariant, content.value("states").toList()) { - StateType stateType(StateTypeId::fromUuid(QUuid())); - stateType.setName(stateVariant.toMap().value("name").toString()); - stateType.setType(QVariant::nameToType(stateVariant.toMap().value("type").toByteArray())); - stateType.setPossibleValues(stateVariant.toMap().value("allowedValues").toList()); - stateType.setMinValue(stateVariant.toMap().value("minValue")); - stateType.setMaxValue(stateVariant.toMap().value("maxValue")); - stateTypes.append(stateType); - - EventType stateChangeEventType(EventTypeId::fromUuid(QUuid())); - stateChangeEventType.setName(stateType.name()); - ParamType stateChangeEventParamType; - stateChangeEventParamType.setName(stateType.name()); - stateChangeEventParamType.setType(stateType.type()); - stateChangeEventParamType.setAllowedValues(stateType.possibleValues()); - stateChangeEventParamType.setMinValue(stateType.minValue()); - stateChangeEventParamType.setMaxValue(stateType.maxValue()); - stateChangeEventType.setParamTypes(ParamTypes() << stateChangeEventParamType); - eventTypes.append(stateChangeEventType); - - if (stateVariant.toMap().value("writable", false).toBool()) { - ActionType stateChangeActionType(ActionTypeId::fromUuid(QUuid())); - stateChangeActionType.setName(stateType.name()); - stateChangeActionType.setParamTypes(ParamTypes() << stateChangeEventParamType); - actionTypes.append(stateChangeActionType); - } - } - - foreach (const QVariant &actionVariant, content.value("actions").toList()) { - ActionType actionType(ActionTypeId::fromUuid(QUuid())); - actionType.setName(actionVariant.toMap().value("name").toString()); - ParamTypes paramTypes; - foreach (const QVariant &actionParamVariant, actionVariant.toMap().value("params").toList()) { - ParamType paramType; - paramType.setName(actionParamVariant.toMap().value("name").toString()); - paramType.setType(QVariant::nameToType(actionParamVariant.toMap().value("type").toByteArray())); - paramType.setAllowedValues(actionParamVariant.toMap().value("allowedValues").toList()); - paramType.setMinValue(actionParamVariant.toMap().value("min")); - paramTypes.append(paramType); - } - actionType.setParamTypes(paramTypes); - actionTypes.append(actionType); - } - - foreach (const QVariant &eventVariant, content.value("events").toList()) { - EventType eventType(EventTypeId::fromUuid(QUuid())); - eventType.setName(eventVariant.toMap().value("name").toString()); - ParamTypes paramTypes; - foreach (const QVariant &eventParamVariant, eventVariant.toMap().value("params").toList()) { - ParamType paramType; - paramType.setName(eventParamVariant.toMap().value("name").toString()); - paramType.setType(QVariant::nameToType(eventParamVariant.toMap().value("type").toByteArray())); - paramType.setAllowedValues(eventParamVariant.toMap().value("allowedValues").toList()); - paramType.setMinValue(eventParamVariant.toMap().value("minValue")); - paramType.setMaxValue(eventParamVariant.toMap().value("maxValue")); - paramTypes.append(paramType); - } - eventType.setParamTypes(paramTypes); - eventTypes.append(eventType); - } - - return Interface(name, iface.actionTypes() << actionTypes, iface.eventTypes() << eventTypes, iface.stateTypes() << stateTypes); -} - -Interface DevicePlugin::mergeInterfaces(const Interface &iface1, const Interface &iface2) -{ - EventTypes eventTypes = iface1.eventTypes(); - foreach (const EventType &et, iface2.eventTypes()) { - if (eventTypes.findByName(et.name()).name().isEmpty()) { - eventTypes.append(et); - } - } - StateTypes stateTypes = iface1.stateTypes(); - foreach (const StateType &st, iface2.stateTypes()) { - if (stateTypes.findByName(st.name()).name().isEmpty()) { - stateTypes.append(st); - } - } - ActionTypes actionTypes = iface1.actionTypes(); - foreach (const ActionType &at, iface2.actionTypes()) { - if (actionTypes.findByName(at.name()).name().isEmpty()) { - actionTypes.append(at); - } - } - return Interface(QString(), actionTypes, eventTypes, stateTypes); -} - -QStringList DevicePlugin::generateInterfaceParentList(const QString &interface) -{ - QFile f(QString(":/interfaces/%1.json").arg(interface)); - if (!f.open(QFile::ReadOnly)) { - qCWarning(dcDeviceManager()) << "Failed to load interface" << interface; - return QStringList(); - } - QJsonParseError error; - QJsonDocument jsonDoc = QJsonDocument::fromJson(f.readAll(), &error); - if (error.error != QJsonParseError::NoError) { - qCWarning(dcDeviceManager) << "Cannot load interface definition for interface" << interface << ":" << error.errorString(); - return QStringList(); - } - QStringList ret = {interface}; - QVariantMap content = jsonDoc.toVariant().toMap(); - if (content.contains("extends")) { - if (!content.value("extends").toString().isEmpty()) { - ret << generateInterfaceParentList(content.value("extends").toString()); - } else if (content.value("extends").toList().count() > 0) { - foreach (const QVariant &extendedIface, content.value("extends").toList()) { - ret << generateInterfaceParentList(extendedIface.toString()); - } - } - } - return ret; -} diff --git a/libnymea/types/deviceclass.cpp b/libnymea/types/deviceclass.cpp index c3013d4d..c7641d9d 100644 --- a/libnymea/types/deviceclass.cpp +++ b/libnymea/types/deviceclass.cpp @@ -314,22 +314,27 @@ bool DeviceClass::operator==(const DeviceClass &deviceClass) const return m_id == deviceClass.id(); } -/*! Returns a list of all valid JSON properties a DeviceClass JSON definition can have. */ -QStringList DeviceClass::typeProperties() -{ - return QStringList() << "id" << "name" << "displayName" << "createMethods" << "setupMethod" - << "interfaces" << "pairingInfo" << "discoveryParamTypes" << "discoveryParamTypes" - << "paramTypes" << "settingsTypes" << "stateTypes" << "actionTypes" << "eventTypes"; -} - -/*! Returns a list of mandatory JSON properties a DeviceClass JSON definition must have. */ -QStringList DeviceClass::mandatoryTypeProperties() -{ - return QStringList() << "id" << "name" << "displayName"; -} - QDebug operator<<(QDebug &dbg, const DeviceClass &deviceClass) { dbg << "DeviceClass ID:" << deviceClass.id() << "Name:" << deviceClass.name(); return dbg; } + +DeviceClasses::DeviceClasses() +{ + +} + +DeviceClasses::DeviceClasses(const QList &other): QList (other) +{ +} + +DeviceClass DeviceClasses::findById(const DeviceClassId &id) const +{ + foreach (const DeviceClass &deviceClass, *this) { + if (deviceClass.id() == id) { + return deviceClass; + } + } + return DeviceClass(); +} diff --git a/libnymea/types/deviceclass.h b/libnymea/types/deviceclass.h index 298d6dd5..cd5bf07d 100644 --- a/libnymea/types/deviceclass.h +++ b/libnymea/types/deviceclass.h @@ -107,9 +107,6 @@ public: bool operator==(const DeviceClass &device) const; - static QStringList typeProperties(); - static QStringList mandatoryTypeProperties(); - private: DeviceClassId m_id; VendorId m_vendorId; @@ -132,4 +129,12 @@ Q_DECLARE_OPERATORS_FOR_FLAGS(DeviceClass::CreateMethods) QDebug operator<<(QDebug &dbg, const DeviceClass &deviceClass); +class LIBNYMEA_EXPORT DeviceClasses: public QList +{ +public: + DeviceClasses(); + DeviceClasses(const QList &other); + DeviceClass findById(const DeviceClassId &id) const; +}; + #endif diff --git a/libnymea/types/interface.h b/libnymea/types/interface.h index 978a5337..a7ff91d5 100644 --- a/libnymea/types/interface.h +++ b/libnymea/types/interface.h @@ -47,7 +47,7 @@ private: StateTypes m_stateTypes; }; -class Interfaces: public QList +class LIBNYMEA_EXPORT Interfaces: public QList { public: Interfaces() = default; diff --git a/libnymea/types/param.cpp b/libnymea/types/param.cpp index 6b2993a4..f49f39f6 100644 --- a/libnymea/types/param.cpp +++ b/libnymea/types/param.cpp @@ -97,6 +97,18 @@ QDebug operator<<(QDebug dbg, const ParamList ¶ms) \sa Param, */ +/*! Constructs an empty ParamList. */ +ParamList::ParamList() +{ + +} + +/*! Constructs a ParamList from a QList. */ +ParamList::ParamList(const QList &other): QList(other) +{ + +} + /*! Returns true if this ParamList contains a Param with the given \a paramTypeId. */ bool ParamList::hasParam(const ParamTypeId ¶mTypeId) const { diff --git a/libnymea/types/param.h b/libnymea/types/param.h index cfcb170c..04c14fe5 100644 --- a/libnymea/types/param.h +++ b/libnymea/types/param.h @@ -53,6 +53,8 @@ QDebug operator<<(QDebug dbg, const Param ¶m); class LIBNYMEA_EXPORT ParamList: public QList { public: + ParamList(); + ParamList(const QList &other); bool hasParam(const ParamTypeId ¶mTypeId) const; QVariant paramValue(const ParamTypeId ¶mTypeId) const; bool setParamValue(const ParamTypeId ¶mTypeId, const QVariant &value); diff --git a/libnymea/types/paramtype.cpp b/libnymea/types/paramtype.cpp index 8d0ae2f6..246d4a8e 100644 --- a/libnymea/types/paramtype.cpp +++ b/libnymea/types/paramtype.cpp @@ -251,11 +251,8 @@ QDebug operator<<(QDebug dbg, const QList ¶mTypes) return dbg.space(); } -ParamTypes::ParamTypes(const QList &other) +ParamTypes::ParamTypes(const QList &other): QList(other) { - foreach (const ParamType &pt, other) { - append(pt); - } } ParamType ParamTypes::findByName(const QString &name) diff --git a/libnymea/types/vendor.cpp b/libnymea/types/vendor.cpp index ada2ecdd..1f0faa71 100644 --- a/libnymea/types/vendor.cpp +++ b/libnymea/types/vendor.cpp @@ -79,3 +79,23 @@ bool Vendor::operator==(const Vendor &other) const { return m_id == other.id(); } + +Vendors::Vendors() +{ + +} + +Vendors::Vendors(const QList &other): QList(other) +{ + +} + +Vendor Vendors::findById(const VendorId &vendorId) const +{ + foreach (const Vendor &vendor, *this) { + if (vendor.id() == vendorId) { + return vendor; + } + } + return Vendor(VendorId()); +} diff --git a/libnymea/types/vendor.h b/libnymea/types/vendor.h index 7521aa69..cdbb32ae 100644 --- a/libnymea/types/vendor.h +++ b/libnymea/types/vendor.h @@ -28,6 +28,7 @@ #include "typeutils.h" #include +#include class LIBNYMEA_EXPORT Vendor { @@ -51,4 +52,13 @@ private: QString m_displayName; }; +class LIBNYMEA_EXPORT Vendors: public QList +{ +public: + Vendors(); + Vendors(const QList &other); + + Vendor findById(const VendorId &vendorId) const; +}; + #endif // VENDOR_H diff --git a/plugins/mock/devicepluginmock.cpp b/plugins/mock/devicepluginmock.cpp index 667a9058..c5975021 100644 --- a/plugins/mock/devicepluginmock.cpp +++ b/plugins/mock/devicepluginmock.cpp @@ -41,14 +41,13 @@ #include "devicepluginmock.h" #include "httpdaemon.h" -#include "plugin/device.h" -#include "devicemanager.h" +#include "devices/device.h" #include "plugininfo.h" #include #include #include - +#include DevicePluginMock::DevicePluginMock() { @@ -59,28 +58,28 @@ DevicePluginMock::~DevicePluginMock() { } -DeviceManager::DeviceError DevicePluginMock::discoverDevices(const DeviceClassId &deviceClassId, const ParamList ¶ms) +Device::DeviceError DevicePluginMock::discoverDevices(const DeviceClassId &deviceClassId, const ParamList ¶ms) { if (deviceClassId == mockDeviceClassId) { qCDebug(dcMockDevice) << "starting mock discovery:" << params; m_discoveredDeviceCount = params.paramValue(mockDiscoveryResultCountParamTypeId).toInt(); QTimer::singleShot(1000, this, SLOT(emitDevicesDiscovered())); - return DeviceManager::DeviceErrorAsync; + return Device::DeviceErrorAsync; } else if (deviceClassId == mockPushButtonDeviceClassId) { qCDebug(dcMockDevice) << "starting mock push button discovery:" << params; m_discoveredDeviceCount = params.paramValue(mockPushButtonDiscoveryResultCountParamTypeId).toInt(); QTimer::singleShot(1000, this, SLOT(emitPushButtonDevicesDiscovered())); - return DeviceManager::DeviceErrorAsync; + return Device::DeviceErrorAsync; } else if (deviceClassId == mockDisplayPinDeviceClassId) { qCDebug(dcMockDevice) << "starting mock display pin discovery:" << params; m_discoveredDeviceCount = params.paramValue(mockDisplayPinDiscoveryResultCountParamTypeId).toInt(); QTimer::singleShot(1000, this, SLOT(emitDisplayPinDevicesDiscovered())); - return DeviceManager::DeviceErrorAsync; + return Device::DeviceErrorAsync; } - return DeviceManager::DeviceErrorDeviceClassNotFound; + return Device::DeviceErrorDeviceClassNotFound; } -DeviceManager::DeviceSetupStatus DevicePluginMock::setupDevice(Device *device) +Device::DeviceSetupStatus DevicePluginMock::setupDevice(Device *device) { if (device->deviceClassId() == mockDeviceClassId || device->deviceClassId() == mockDeviceAutoDeviceClassId) { bool async = false; @@ -95,7 +94,7 @@ DeviceManager::DeviceSetupStatus DevicePluginMock::setupDevice(Device *device) if (broken) { qCWarning(dcMockDevice) << "This device is intentionally broken."; - return DeviceManager::DeviceSetupStatusFailure; + return Device::DeviceSetupStatusFailure; } HttpDaemon *daemon = new HttpDaemon(device, this); @@ -103,7 +102,7 @@ DeviceManager::DeviceSetupStatus DevicePluginMock::setupDevice(Device *device) if (!daemon->isListening()) { qCWarning(dcMockDevice) << "HTTP port opening failed:" << device->paramValue(mockDeviceHttpportParamTypeId).toInt(); - return DeviceManager::DeviceSetupStatusFailure; + return Device::DeviceSetupStatusFailure; } connect(daemon, &HttpDaemon::triggerEvent, this, &DevicePluginMock::triggerEvent); @@ -115,27 +114,27 @@ DeviceManager::DeviceSetupStatus DevicePluginMock::setupDevice(Device *device) if (async) { m_asyncSetupDevices.append(device); QTimer::singleShot(1000, this, SLOT(emitDeviceSetupFinished())); - return DeviceManager::DeviceSetupStatusAsync; + return Device::DeviceSetupStatusAsync; } - return DeviceManager::DeviceSetupStatusSuccess; + return Device::DeviceSetupStatusSuccess; } else if (device->deviceClassId() == mockPushButtonDeviceClassId) { qCDebug(dcMockDevice) << "Setup PushButton mock device" << device->params(); - return DeviceManager::DeviceSetupStatusSuccess; + return Device::DeviceSetupStatusSuccess; } else if (device->deviceClassId() == mockDisplayPinDeviceClassId) { qCDebug(dcMockDevice) << "Setup DisplayPin mock device" << device->params(); - return DeviceManager::DeviceSetupStatusSuccess; + return Device::DeviceSetupStatusSuccess; } else if (device->deviceClassId() == mockParentDeviceClassId) { qCDebug(dcMockDevice) << "Setup Parent mock device" << device->params(); - return DeviceManager::DeviceSetupStatusSuccess; + return Device::DeviceSetupStatusSuccess; } else if (device->deviceClassId() == mockChildDeviceClassId) { qCDebug(dcMockDevice) << "Setup Child mock device" << device->params(); - return DeviceManager::DeviceSetupStatusSuccess; + return Device::DeviceSetupStatusSuccess; } else if (device->deviceClassId() == mockInputTypeDeviceClassId) { qCDebug(dcMockDevice) << "Setup InputType mock device" << device->params(); - return DeviceManager::DeviceSetupStatusSuccess; + return Device::DeviceSetupStatusSuccess; } - return DeviceManager::DeviceSetupStatusFailure; + return Device::DeviceSetupStatusFailure; } void DevicePluginMock::postSetupDevice(Device *device) @@ -179,7 +178,7 @@ void DevicePluginMock::startMonitoringAutoDevices() emit autoDevicesAppeared(mockDeviceAutoDeviceClassId, deviceDescriptorList); } -DeviceManager::DeviceSetupStatus DevicePluginMock::confirmPairing(const PairingTransactionId &pairingTransactionId, const DeviceClassId &deviceClassId, const ParamList ¶ms, const QString &secret) +Device::DeviceSetupStatus DevicePluginMock::confirmPairing(const PairingTransactionId &pairingTransactionId, const DeviceClassId &deviceClassId, const ParamList ¶ms, const QString &secret) { Q_UNUSED(params) Q_UNUSED(secret) @@ -189,133 +188,133 @@ DeviceManager::DeviceSetupStatus DevicePluginMock::confirmPairing(const PairingT if (deviceClassId == mockPushButtonDeviceClassId) { if (!m_pushbuttonPressed) { qCDebug(dcMockDevice) << "PushButton not pressed yet!"; - return DeviceManager::DeviceSetupStatusFailure; + return Device::DeviceSetupStatusFailure; } m_pairingId = pairingTransactionId; QTimer::singleShot(1000, this, SLOT(onPushButtonPairingFinished())); - return DeviceManager::DeviceSetupStatusAsync; + return Device::DeviceSetupStatusAsync; } else if (deviceClassId == mockDisplayPinDeviceClassId) { if (secret != "243681") { qCWarning(dcMockDevice) << "Invalid pin:" << secret; - return DeviceManager::DeviceSetupStatusFailure; + return Device::DeviceSetupStatusFailure; } m_pairingId = pairingTransactionId; QTimer::singleShot(500, this, SLOT(onDisplayPinPairingFinished())); - return DeviceManager::DeviceSetupStatusAsync; + return Device::DeviceSetupStatusAsync; } qCWarning(dcMockDevice) << "Invalid deviceclassId -> no pairing possible with this device"; - return DeviceManager::DeviceSetupStatusFailure; + return Device::DeviceSetupStatusFailure; } -DeviceManager::DeviceError DevicePluginMock::displayPin(const PairingTransactionId &pairingTransactionId, const DeviceDescriptor &deviceDescriptor) +Device::DeviceError DevicePluginMock::displayPin(const PairingTransactionId &pairingTransactionId, const DeviceDescriptor &deviceDescriptor) { Q_UNUSED(pairingTransactionId) Q_UNUSED(deviceDescriptor) qCDebug(dcMockDevice) << QString(tr("Display pin!! The pin is 243681")); - return DeviceManager::DeviceErrorNoError; + return Device::DeviceErrorNoError; } -DeviceManager::DeviceError DevicePluginMock::executeAction(Device *device, const Action &action) +Device::DeviceError DevicePluginMock::executeAction(Device *device, const Action &action) { if (!myDevices().contains(device)) - return DeviceManager::DeviceErrorDeviceNotFound; + return Device::DeviceErrorDeviceNotFound; if (device->deviceClassId() == mockDeviceClassId) { if (action.actionTypeId() == mockMockAsyncActionTypeId || action.actionTypeId() == mockMockAsyncFailingActionTypeId) { m_asyncActions.append(qMakePair(action, device)); QTimer::singleShot(1000, this, SLOT(emitActionExecuted())); - return DeviceManager::DeviceErrorAsync; + return Device::DeviceErrorAsync; } if (action.actionTypeId() == mockMockFailingActionTypeId) - return DeviceManager::DeviceErrorSetupFailed; + return Device::DeviceErrorSetupFailed; if (action.actionTypeId() == mockPowerActionTypeId) { qCDebug(dcMockDevice()) << "Setting power to" << action.param(mockPowerActionPowerParamTypeId).value().toBool(); device->setStateValue(mockPowerStateTypeId, action.param(mockPowerActionPowerParamTypeId).value().toBool()); } m_daemons.value(device)->actionExecuted(action.actionTypeId()); - return DeviceManager::DeviceErrorNoError; + return Device::DeviceErrorNoError; } else if (device->deviceClassId() == mockDeviceAutoDeviceClassId) { if (action.actionTypeId() == mockDeviceAutoMockActionAsyncActionTypeId || action.actionTypeId() == mockDeviceAutoMockActionAsyncBrokenActionTypeId) { m_asyncActions.append(qMakePair(action, device)); QTimer::singleShot(1000, this, SLOT(emitActionExecuted())); - return DeviceManager::DeviceErrorAsync; + return Device::DeviceErrorAsync; } if (action.actionTypeId() == mockDeviceAutoMockActionBrokenActionTypeId) - return DeviceManager::DeviceErrorSetupFailed; + return Device::DeviceErrorSetupFailed; m_daemons.value(device)->actionExecuted(action.actionTypeId()); - return DeviceManager::DeviceErrorNoError; + return Device::DeviceErrorNoError; } else if (device->deviceClassId() == mockPushButtonDeviceClassId) { if (action.actionTypeId() == mockPushButtonColorActionTypeId) { QString colorString = action.param(mockPushButtonColorActionColorParamTypeId).value().toString(); QColor color(colorString); if (!color.isValid()) { qCWarning(dcMockDevice) << "Invalid color parameter"; - return DeviceManager::DeviceErrorInvalidParameter; + return Device::DeviceErrorInvalidParameter; } device->setStateValue(mockPushButtonColorStateTypeId, colorString); - return DeviceManager::DeviceErrorNoError; + return Device::DeviceErrorNoError; } else if (action.actionTypeId() == mockPushButtonPercentageActionTypeId) { device->setStateValue(mockPushButtonPercentageStateTypeId, action.param(mockPushButtonPercentageActionPercentageParamTypeId).value().toInt()); - return DeviceManager::DeviceErrorNoError; + return Device::DeviceErrorNoError; } else if (action.actionTypeId() == mockPushButtonAllowedValuesActionTypeId) { device->setStateValue(mockPushButtonAllowedValuesStateTypeId, action.param(mockPushButtonAllowedValuesActionAllowedValuesParamTypeId).value().toString()); - return DeviceManager::DeviceErrorNoError; + return Device::DeviceErrorNoError; } else if (action.actionTypeId() == mockPushButtonDoubleActionTypeId) { device->setStateValue(mockPushButtonDoubleStateTypeId, action.param(mockPushButtonDoubleActionDoubleParamTypeId).value().toDouble()); - return DeviceManager::DeviceErrorNoError; + return Device::DeviceErrorNoError; } else if (action.actionTypeId() == mockPushButtonBoolActionTypeId) { device->setStateValue(mockPushButtonBoolStateTypeId, action.param(mockPushButtonBoolActionBoolParamTypeId).value().toBool()); - return DeviceManager::DeviceErrorNoError; + return Device::DeviceErrorNoError; } else if (action.actionTypeId() == mockPushButtonTimeoutActionTypeId) { - return DeviceManager::DeviceErrorAsync; + return Device::DeviceErrorAsync; } - return DeviceManager::DeviceErrorActionTypeNotFound; + return Device::DeviceErrorActionTypeNotFound; } else if (device->deviceClassId() == mockDisplayPinDeviceClassId) { if (action.actionTypeId() == mockDisplayPinColorActionTypeId) { QString colorString = action.param(mockDisplayPinColorActionColorParamTypeId).value().toString(); QColor color(colorString); if (!color.isValid()) { qCWarning(dcMockDevice) << "Invalid color parameter"; - return DeviceManager::DeviceErrorInvalidParameter; + return Device::DeviceErrorInvalidParameter; } device->setStateValue(mockDisplayPinColorStateTypeId, colorString); - return DeviceManager::DeviceErrorNoError; + return Device::DeviceErrorNoError; } else if (action.actionTypeId() == mockDisplayPinPercentageActionTypeId) { device->setStateValue(mockDisplayPinPercentageStateTypeId, action.param(mockDisplayPinPercentageActionPercentageParamTypeId).value().toInt()); - return DeviceManager::DeviceErrorNoError; + return Device::DeviceErrorNoError; } else if (action.actionTypeId() == mockDisplayPinAllowedValuesActionTypeId) { device->setStateValue(mockDisplayPinAllowedValuesStateTypeId, action.param(mockDisplayPinAllowedValuesActionAllowedValuesParamTypeId).value().toString()); - return DeviceManager::DeviceErrorNoError; + return Device::DeviceErrorNoError; } else if (action.actionTypeId() == mockDisplayPinDoubleActionTypeId) { device->setStateValue(mockDisplayPinDoubleStateTypeId, action.param(mockDisplayPinDoubleActionDoubleParamTypeId).value().toDouble()); - return DeviceManager::DeviceErrorNoError; + return Device::DeviceErrorNoError; } else if (action.actionTypeId() == mockDisplayPinBoolActionTypeId) { device->setStateValue(mockDisplayPinBoolStateTypeId, action.param(mockDisplayPinBoolActionBoolParamTypeId).value().toBool()); - return DeviceManager::DeviceErrorNoError; + return Device::DeviceErrorNoError; } else if (action.actionTypeId() == mockDisplayPinTimeoutActionTypeId) { - return DeviceManager::DeviceErrorAsync; + return Device::DeviceErrorAsync; } - return DeviceManager::DeviceErrorActionTypeNotFound; + return Device::DeviceErrorActionTypeNotFound; } else if (device->deviceClassId() == mockParentDeviceClassId) { if (action.actionTypeId() == mockParentBoolValueActionTypeId) { device->setStateValue(mockParentBoolValueStateTypeId, action.param(mockParentBoolValueActionBoolValueParamTypeId).value().toBool()); - return DeviceManager::DeviceErrorNoError; + return Device::DeviceErrorNoError; } - return DeviceManager::DeviceErrorActionTypeNotFound; + return Device::DeviceErrorActionTypeNotFound; } else if (device->deviceClassId() == mockChildDeviceClassId) { if (action.actionTypeId() == mockChildBoolValueActionTypeId) { device->setStateValue(mockChildBoolValueStateTypeId, action.param(mockChildBoolValueActionBoolValueParamTypeId).value().toBool()); - return DeviceManager::DeviceErrorNoError; + return Device::DeviceErrorNoError; } - return DeviceManager::DeviceErrorActionTypeNotFound; + return Device::DeviceErrorActionTypeNotFound; } else if (device->deviceClassId() == mockInputTypeDeviceClassId) { if (action.actionTypeId() == mockInputTypeWritableBoolActionTypeId) { device->setStateValue(mockInputTypeWritableBoolStateTypeId, action.param(mockInputTypeWritableBoolActionWritableBoolParamTypeId).value().toULongLong()); @@ -346,7 +345,7 @@ DeviceManager::DeviceError DevicePluginMock::executeAction(Device *device, const } } - return DeviceManager::DeviceErrorDeviceClassNotFound; + return Device::DeviceErrorDeviceClassNotFound; } void DevicePluginMock::setState(const StateTypeId &stateTypeId, const QVariant &value) @@ -506,9 +505,9 @@ void DevicePluginMock::emitDeviceSetupFinished() qCDebug(dcMockDevice) << "Emitting setup finised"; Device *device = m_asyncSetupDevices.takeFirst(); if (device->paramValue(mockDeviceBrokenParamTypeId).toBool()) { - emit deviceSetupFinished(device, DeviceManager::DeviceSetupStatusFailure); + emit deviceSetupFinished(device, Device::DeviceSetupStatusFailure); } else { - emit deviceSetupFinished(device, DeviceManager::DeviceSetupStatusSuccess); + emit deviceSetupFinished(device, Device::DeviceSetupStatusSuccess); } } @@ -517,22 +516,22 @@ void DevicePluginMock::emitActionExecuted() QPair action = m_asyncActions.takeFirst(); if (action.first.actionTypeId() == mockMockAsyncActionTypeId) { m_daemons.value(action.second)->actionExecuted(action.first.actionTypeId()); - emit actionExecutionFinished(action.first.id(), DeviceManager::DeviceErrorNoError); + emit actionExecutionFinished(action.first.id(), Device::DeviceErrorNoError); } else if (action.first.actionTypeId() == mockMockAsyncFailingActionTypeId) { - emit actionExecutionFinished(action.first.id(), DeviceManager::DeviceErrorSetupFailed); + emit actionExecutionFinished(action.first.id(), Device::DeviceErrorSetupFailed); } } void DevicePluginMock::onPushButtonPairingFinished() { qCDebug(dcMockDevice) << "Pairing PushButton Device finished"; - emit pairingFinished(m_pairingId, DeviceManager::DeviceSetupStatusSuccess); + emit pairingFinished(m_pairingId, Device::DeviceSetupStatusSuccess); } void DevicePluginMock::onDisplayPinPairingFinished() { qCDebug(dcMockDevice) << "Pairing DisplayPin Device finished"; - emit pairingFinished(m_pairingId, DeviceManager::DeviceSetupStatusSuccess); + emit pairingFinished(m_pairingId, Device::DeviceSetupStatusSuccess); } void DevicePluginMock::onChildDeviceDiscovered(const DeviceId &parentId) diff --git a/plugins/mock/devicepluginmock.h b/plugins/mock/devicepluginmock.h index 8efe6d25..49beefa8 100644 --- a/plugins/mock/devicepluginmock.h +++ b/plugins/mock/devicepluginmock.h @@ -24,7 +24,7 @@ #ifndef DEVICEPLUGINMOCK_H #define DEVICEPLUGINMOCK_H -#include "plugin/deviceplugin.h" +#include "devices/deviceplugin.h" #include @@ -41,19 +41,19 @@ public: explicit DevicePluginMock(); ~DevicePluginMock(); - DeviceManager::DeviceError discoverDevices(const DeviceClassId &deviceClassId, const ParamList ¶ms) override; + Device::DeviceError discoverDevices(const DeviceClassId &deviceClassId, const ParamList ¶ms) override; - DeviceManager::DeviceSetupStatus setupDevice(Device *device) override; + Device::DeviceSetupStatus setupDevice(Device *device) override; void postSetupDevice(Device *device) override; void deviceRemoved(Device *device) override; void startMonitoringAutoDevices() override; - DeviceManager::DeviceSetupStatus confirmPairing(const PairingTransactionId &pairingTransactionId, const DeviceClassId &deviceClassId, const ParamList ¶ms, const QString &secret) override; - DeviceManager::DeviceError displayPin(const PairingTransactionId &pairingTransactionId, const DeviceDescriptor &deviceDescriptor) override; + Device::DeviceSetupStatus confirmPairing(const PairingTransactionId &pairingTransactionId, const DeviceClassId &deviceClassId, const ParamList ¶ms, const QString &secret) override; + Device::DeviceError displayPin(const PairingTransactionId &pairingTransactionId, const DeviceDescriptor &deviceDescriptor) override; public slots: - DeviceManager::DeviceError executeAction(Device *device, const Action &action) override; + Device::DeviceError executeAction(Device *device, const Action &action) override; private slots: void setState(const StateTypeId &stateTypeId, const QVariant &value); diff --git a/plugins/mock/httpdaemon.cpp b/plugins/mock/httpdaemon.cpp index c0799b7b..42e59f9c 100644 --- a/plugins/mock/httpdaemon.cpp +++ b/plugins/mock/httpdaemon.cpp @@ -23,8 +23,8 @@ #include "httpdaemon.h" -#include "plugin/device.h" -#include "plugin/deviceplugin.h" +#include "devices/device.h" +#include "devices/deviceplugin.h" #include "types/deviceclass.h" #include "types/statetype.h" #include "extern-plugininfo.h" diff --git a/plugins/plugins.pri b/plugins/plugins.pri index 405d9dd6..66d11c8c 100644 --- a/plugins/plugins.pri +++ b/plugins/plugins.pri @@ -14,7 +14,7 @@ JSONFILE=$$PWD/$$TARGET/deviceplugin"$$TARGET".json plugininfo.input = JSONFILE plugininfo.output = plugininfo.h plugininfo.CONFIG = no_link target_predeps -plugininfo.commands = $$top_srcdir/libnymea/plugin/nymea-generateplugininfo \ +plugininfo.commands = $$top_srcdir/libnymea/devices/nymea-generateplugininfo \ --filetype i \ --jsonfile $$PWD/$$TARGET/deviceplugin"$$TARGET".json \ --output plugininfo.h \ @@ -22,7 +22,7 @@ plugininfo.commands = $$top_srcdir/libnymea/plugin/nymea-generateplugininfo \ extern-plugininfo.input = JSONFILE extern-plugininfo.output = extern-plugininfo.h extern-plugininfo.CONFIG = no_link target_predeps -extern-plugininfo.commands = $$top_srcdir/libnymea/plugin/nymea-generateplugininfo \ +extern-plugininfo.commands = $$top_srcdir/libnymea/devices/nymea-generateplugininfo \ --filetype e \ --jsonfile $$PWD/$$TARGET/deviceplugin"$$TARGET".json \ --output extern-plugininfo.h \ diff --git a/server/main.cpp b/server/main.cpp index 99380740..b8a6d054 100644 --- a/server/main.cpp +++ b/server/main.cpp @@ -105,6 +105,7 @@ int main(int argc, char *argv[]) "Platform", "PlatformUpdate", "PlatformZeroConf", + "Device", "DeviceManager", "RuleEngine", "RuleEngineDebug", @@ -141,7 +142,7 @@ int main(int argc, char *argv[]) }; QStringList loggingFiltersPlugins; - foreach (const QJsonObject &pluginMetadata, DeviceManager::pluginsMetadata()) { + foreach (const QJsonObject &pluginMetadata, DeviceManagerImplementation::pluginsMetadata()) { QString pluginName = pluginMetadata.value("name").toString(); loggingFiltersPlugins << pluginName.left(1).toUpper() + pluginName.mid(1); } diff --git a/tests/auto/actions/testactions.cpp b/tests/auto/actions/testactions.cpp index d5d1d295..04a4e572 100644 --- a/tests/auto/actions/testactions.cpp +++ b/tests/auto/actions/testactions.cpp @@ -41,7 +41,7 @@ void TestActions::executeAction_data() QTest::addColumn("deviceId"); QTest::addColumn("actionTypeId"); QTest::addColumn("actionParams"); - QTest::addColumn("error"); + QTest::addColumn("error"); QVariantList params; QVariantMap param1; @@ -53,13 +53,13 @@ void TestActions::executeAction_data() param2.insert("value", true); params.append(param2); - QTest::newRow("valid action") << m_mockDeviceId << mockActionIdWithParams << params << DeviceManager::DeviceErrorNoError; - QTest::newRow("invalid deviceId") << DeviceId::createDeviceId() << mockActionIdWithParams << params << DeviceManager::DeviceErrorDeviceNotFound; - QTest::newRow("invalid actionTypeId") << m_mockDeviceId << ActionTypeId::createActionTypeId() << params << DeviceManager::DeviceErrorActionTypeNotFound; - QTest::newRow("missing params") << m_mockDeviceId << mockActionIdWithParams << QVariantList() << DeviceManager::DeviceErrorMissingParameter; - QTest::newRow("async action") << m_mockDeviceId << mockActionIdAsync << QVariantList() << DeviceManager::DeviceErrorNoError; - QTest::newRow("broken action") << m_mockDeviceId << mockActionIdFailing << QVariantList() << DeviceManager::DeviceErrorSetupFailed; - QTest::newRow("async broken action") << m_mockDeviceId << mockActionIdAsyncFailing << QVariantList() << DeviceManager::DeviceErrorSetupFailed; + QTest::newRow("valid action") << m_mockDeviceId << mockActionIdWithParams << params << Device::DeviceErrorNoError; + QTest::newRow("invalid deviceId") << DeviceId::createDeviceId() << mockActionIdWithParams << params << Device::DeviceErrorDeviceNotFound; + QTest::newRow("invalid actionTypeId") << m_mockDeviceId << ActionTypeId::createActionTypeId() << params << Device::DeviceErrorActionTypeNotFound; + QTest::newRow("missing params") << m_mockDeviceId << mockActionIdWithParams << QVariantList() << Device::DeviceErrorMissingParameter; + QTest::newRow("async action") << m_mockDeviceId << mockActionIdAsync << QVariantList() << Device::DeviceErrorNoError; + QTest::newRow("broken action") << m_mockDeviceId << mockActionIdFailing << QVariantList() << Device::DeviceErrorSetupFailed; + QTest::newRow("async broken action") << m_mockDeviceId << mockActionIdAsyncFailing << QVariantList() << Device::DeviceErrorSetupFailed; } void TestActions::executeAction() @@ -67,7 +67,7 @@ void TestActions::executeAction() QFETCH(DeviceId, deviceId); QFETCH(ActionTypeId, actionTypeId); QFETCH(QVariantList, actionParams); - QFETCH(DeviceManager::DeviceError, error); + QFETCH(Device::DeviceError, error); QVariantMap params; params.insert("actionTypeId", actionTypeId); @@ -88,7 +88,7 @@ void TestActions::executeAction() reply->deleteLater(); QByteArray data = reply->readAll(); - if (error == DeviceManager::DeviceErrorNoError) { + if (error == Device::DeviceErrorNoError) { QVERIFY2(actionTypeId == ActionTypeId(data), QString("ActionTypeId mismatch. Got %1, Expected: %2") .arg(ActionTypeId(data).toString()).arg(actionTypeId.toString()).toLatin1().data()); } else { @@ -117,16 +117,16 @@ void TestActions::executeAction() void TestActions::getActionType_data() { QTest::addColumn("actionTypeId"); - QTest::addColumn("error"); + QTest::addColumn("error"); - QTest::newRow("valid actiontypeid") << mockActionIdWithParams << DeviceManager::DeviceErrorNoError; - QTest::newRow("invalid actiontypeid") << ActionTypeId::createActionTypeId() << DeviceManager::DeviceErrorActionTypeNotFound; + QTest::newRow("valid actiontypeid") << mockActionIdWithParams << Device::DeviceErrorNoError; + QTest::newRow("invalid actiontypeid") << ActionTypeId::createActionTypeId() << Device::DeviceErrorActionTypeNotFound; } void TestActions::getActionType() { QFETCH(ActionTypeId, actionTypeId); - QFETCH(DeviceManager::DeviceError, error); + QFETCH(Device::DeviceError, error); QVariantMap params; params.insert("actionTypeId", actionTypeId.toString()); @@ -134,7 +134,7 @@ void TestActions::getActionType() verifyDeviceError(response, error); - if (error == DeviceManager::DeviceErrorNoError) { + if (error == Device::DeviceErrorNoError) { QVERIFY2(ActionTypeId(response.toMap().value("params").toMap().value("actionType").toMap().value("id").toString()) == actionTypeId, "Didn't get a reply for the same actionTypeId as requested."); } } diff --git a/tests/auto/devices/testdevices.cpp b/tests/auto/devices/testdevices.cpp index cb65782e..f00585bd 100644 --- a/tests/auto/devices/testdevices.cpp +++ b/tests/auto/devices/testdevices.cpp @@ -120,16 +120,16 @@ void TestDevices::getPlugins() void TestDevices::getPluginConfig_data() { QTest::addColumn("pluginId"); - QTest::addColumn("error"); + QTest::addColumn("error"); - QTest::newRow("valid plugin") << mockPluginId << DeviceManager::DeviceErrorNoError; - QTest::newRow("invalid plugin") << PluginId::createPluginId() << DeviceManager::DeviceErrorPluginNotFound; + QTest::newRow("valid plugin") << mockPluginId << Device::DeviceErrorNoError; + QTest::newRow("invalid plugin") << PluginId::createPluginId() << Device::DeviceErrorPluginNotFound; } void TestDevices::getPluginConfig() { QFETCH(PluginId, pluginId); - QFETCH(DeviceManager::DeviceError, error); + QFETCH(Device::DeviceError, error); QVariantMap params; params.insert("pluginId", pluginId); @@ -141,20 +141,20 @@ void TestDevices::setPluginConfig_data() { QTest::addColumn("pluginId"); QTest::addColumn("value"); - QTest::addColumn("error"); + QTest::addColumn("error"); - QTest::newRow("valid") << mockPluginId << QVariant(13) << DeviceManager::DeviceErrorNoError; - QTest::newRow("invalid plugin") << PluginId::createPluginId() << QVariant(13) << DeviceManager::DeviceErrorPluginNotFound; - QTest::newRow("too big") << mockPluginId << QVariant(130) << DeviceManager::DeviceErrorInvalidParameter; - QTest::newRow("too small") << mockPluginId << QVariant(-13) << DeviceManager::DeviceErrorInvalidParameter; - QTest::newRow("wrong type") << mockPluginId << QVariant("wrontType") << DeviceManager::DeviceErrorInvalidParameter; + QTest::newRow("valid") << mockPluginId << QVariant(13) << Device::DeviceErrorNoError; + QTest::newRow("invalid plugin") << PluginId::createPluginId() << QVariant(13) << Device::DeviceErrorPluginNotFound; + QTest::newRow("too big") << mockPluginId << QVariant(130) << Device::DeviceErrorInvalidParameter; + QTest::newRow("too small") << mockPluginId << QVariant(-13) << Device::DeviceErrorInvalidParameter; + QTest::newRow("wrong type") << mockPluginId << QVariant("wrontType") << Device::DeviceErrorInvalidParameter; } void TestDevices::setPluginConfig() { QFETCH(PluginId, pluginId); QFETCH(QVariant, value); - QFETCH(DeviceManager::DeviceError, error); + QFETCH(Device::DeviceError, error); QVariantMap params; params.insert("pluginId", pluginId); @@ -168,7 +168,7 @@ void TestDevices::setPluginConfig() QVariant response = injectAndWait("Devices.SetPluginConfiguration", params); verifyDeviceError(response, error); - if (error == DeviceManager::DeviceErrorNoError) { + if (error == Device::DeviceErrorNoError) { params.clear(); params.insert("pluginId", pluginId); response = injectAndWait("Devices.GetPluginConfiguration", params); @@ -252,7 +252,7 @@ void TestDevices::addConfiguredDevice_data() { QTest::addColumn("deviceClassId"); QTest::addColumn("deviceParams"); - QTest::addColumn("deviceError"); + QTest::addColumn("deviceError"); QVariantMap httpportParam; httpportParam.insert("paramTypeId", httpportParamTypeId.toString()); @@ -267,27 +267,27 @@ void TestDevices::addConfiguredDevice_data() QVariantList deviceParams; deviceParams.clear(); deviceParams << httpportParam; - QTest::newRow("User, JustAdd") << mockDeviceClassId << deviceParams << DeviceManager::DeviceErrorNoError; + QTest::newRow("User, JustAdd") << mockDeviceClassId << deviceParams << Device::DeviceErrorNoError; deviceParams.clear(); deviceParams << httpportParam << asyncParam; - QTest::newRow("User, JustAdd, Async") << mockDeviceClassId << deviceParams << DeviceManager::DeviceErrorNoError; - QTest::newRow("Invalid DeviceClassId") << DeviceClassId::createDeviceClassId() << deviceParams << DeviceManager::DeviceErrorDeviceClassNotFound; + QTest::newRow("User, JustAdd, Async") << mockDeviceClassId << deviceParams << Device::DeviceErrorNoError; + QTest::newRow("Invalid DeviceClassId") << DeviceClassId::createDeviceClassId() << deviceParams << Device::DeviceErrorDeviceClassNotFound; deviceParams.clear(); deviceParams << httpportParam << brokenParam; - QTest::newRow("Setup failure") << mockDeviceClassId << deviceParams << DeviceManager::DeviceErrorSetupFailed; + QTest::newRow("Setup failure") << mockDeviceClassId << deviceParams << Device::DeviceErrorSetupFailed; deviceParams.clear(); deviceParams << httpportParam << asyncParam << brokenParam; - QTest::newRow("Setup failure, Async") << mockDeviceClassId << deviceParams << DeviceManager::DeviceErrorSetupFailed; + QTest::newRow("Setup failure, Async") << mockDeviceClassId << deviceParams << Device::DeviceErrorSetupFailed; QVariantList invalidDeviceParams; - QTest::newRow("User, JustAdd, missing params") << mockDeviceClassId << invalidDeviceParams << DeviceManager::DeviceErrorMissingParameter; + QTest::newRow("User, JustAdd, missing params") << mockDeviceClassId << invalidDeviceParams << Device::DeviceErrorMissingParameter; QVariantMap fakeparam; fakeparam.insert("paramTypeId", ParamTypeId::createParamTypeId()); invalidDeviceParams.append(fakeparam); - QTest::newRow("User, JustAdd, invalid param") << mockDeviceClassId << invalidDeviceParams << DeviceManager::DeviceErrorInvalidParameter; + QTest::newRow("User, JustAdd, invalid param") << mockDeviceClassId << invalidDeviceParams << Device::DeviceErrorInvalidParameter; fakeparam.insert("value", "buhuu"); invalidDeviceParams.clear(); invalidDeviceParams.append(fakeparam); - QTest::newRow("User, JustAdd, wrong param") << mockDeviceClassId << invalidDeviceParams << DeviceManager::DeviceErrorInvalidParameter; + QTest::newRow("User, JustAdd, wrong param") << mockDeviceClassId << invalidDeviceParams << Device::DeviceErrorInvalidParameter; } @@ -295,7 +295,7 @@ void TestDevices::addConfiguredDevice() { QFETCH(DeviceClassId, deviceClassId); QFETCH(QVariantList, deviceParams); - QFETCH(DeviceManager::DeviceError, deviceError); + QFETCH(Device::DeviceError, deviceError); QVariantMap params; params.insert("deviceClassId", deviceClassId); @@ -306,7 +306,7 @@ void TestDevices::addConfiguredDevice() verifyDeviceError(response, deviceError); - if (deviceError == DeviceManager::DeviceErrorNoError) { + if (deviceError == Device::DeviceErrorNoError) { QUuid deviceId(response.toMap().value("params").toMap().value("deviceId").toString()); params.clear(); params.insert("deviceId", deviceId.toString()); @@ -375,7 +375,7 @@ void TestDevices::discoverDevices_data() { QTest::addColumn("deviceClassId"); QTest::addColumn("resultCount"); - QTest::addColumn("error"); + QTest::addColumn("error"); QTest::addColumn("discoveryParams"); QVariantList discoveryParams; @@ -384,16 +384,16 @@ void TestDevices::discoverDevices_data() resultCountParam.insert("value", 1); discoveryParams.append(resultCountParam); - QTest::newRow("valid deviceClassId") << mockDeviceClassId << 2 << DeviceManager::DeviceErrorNoError << QVariantList(); - QTest::newRow("valid deviceClassId with params") << mockDeviceClassId << 1 << DeviceManager::DeviceErrorNoError << discoveryParams; - QTest::newRow("invalid deviceClassId") << DeviceClassId::createDeviceClassId() << 0 << DeviceManager::DeviceErrorDeviceClassNotFound << QVariantList(); + QTest::newRow("valid deviceClassId") << mockDeviceClassId << 2 << Device::DeviceErrorNoError << QVariantList(); + QTest::newRow("valid deviceClassId with params") << mockDeviceClassId << 1 << Device::DeviceErrorNoError << discoveryParams; + QTest::newRow("invalid deviceClassId") << DeviceClassId::createDeviceClassId() << 0 << Device::DeviceErrorDeviceClassNotFound << QVariantList(); } void TestDevices::discoverDevices() { QFETCH(DeviceClassId, deviceClassId); QFETCH(int, resultCount); - QFETCH(DeviceManager::DeviceError, error); + QFETCH(Device::DeviceError, error); QFETCH(QVariantList, discoveryParams); QVariantMap params; @@ -402,12 +402,12 @@ void TestDevices::discoverDevices() QVariant response = injectAndWait("Devices.GetDiscoveredDevices", params); verifyDeviceError(response, error); - if (error == DeviceManager::DeviceErrorNoError) { + if (error == Device::DeviceErrorNoError) { QCOMPARE(response.toMap().value("params").toMap().value("deviceDescriptors").toList().count(), resultCount); } // If we found something, lets try to add it - if (DeviceManager::DeviceErrorNoError) { + if (Device::DeviceErrorNoError) { DeviceDescriptorId descriptorId = DeviceDescriptorId(response.toMap().value("params").toMap().value("deviceDescriptors").toList().first().toMap().value("id").toString()); params.clear(); @@ -429,17 +429,17 @@ void TestDevices::discoverDevices() void TestDevices::addPushButtonDevices_data() { QTest::addColumn("deviceClassId"); - QTest::addColumn("error"); + QTest::addColumn("error"); QTest::addColumn("waitForButtonPressed"); - QTest::newRow("Valid: Add PushButton device") << mockPushButtonDeviceClassId << DeviceManager::DeviceErrorNoError << true; - QTest::newRow("Invalid: Add PushButton device (press to early)") << mockPushButtonDeviceClassId << DeviceManager::DeviceErrorSetupFailed << false; + QTest::newRow("Valid: Add PushButton device") << mockPushButtonDeviceClassId << Device::DeviceErrorNoError << true; + QTest::newRow("Invalid: Add PushButton device (press to early)") << mockPushButtonDeviceClassId << Device::DeviceErrorSetupFailed << false; } void TestDevices::addPushButtonDevices() { QFETCH(DeviceClassId, deviceClassId); - QFETCH(DeviceManager::DeviceError, error); + QFETCH(Device::DeviceError, error); QFETCH(bool, waitForButtonPressed); // Discover device @@ -454,7 +454,7 @@ void TestDevices::addPushButtonDevices() params.insert("discoveryParams", discoveryParams); QVariant response = injectAndWait("Devices.GetDiscoveredDevices", params); - verifyDeviceError(response, DeviceManager::DeviceErrorNoError); + verifyDeviceError(response, Device::DeviceErrorNoError); QCOMPARE(response.toMap().value("params").toMap().value("deviceDescriptors").toList().count(), 1); @@ -483,7 +483,7 @@ void TestDevices::addPushButtonDevices() verifyDeviceError(response, error); - if (error == DeviceManager::DeviceErrorNoError) { + if (error == Device::DeviceErrorNoError) { DeviceId deviceId(response.toMap().value("params").toMap().value("deviceId").toString()); params.clear(); params.insert("deviceId", deviceId.toString()); @@ -495,17 +495,17 @@ void TestDevices::addPushButtonDevices() void TestDevices::addDisplayPinDevices_data() { QTest::addColumn("deviceClassId"); - QTest::addColumn("error"); + QTest::addColumn("error"); QTest::addColumn("secret"); - QTest::newRow("Valid: Add DisplayPin device") << mockDisplayPinDeviceClassId << DeviceManager::DeviceErrorNoError << "243681"; - QTest::newRow("Invalid: Add DisplayPin device (wrong pin)") << mockDisplayPinDeviceClassId << DeviceManager::DeviceErrorSetupFailed << "243682"; + QTest::newRow("Valid: Add DisplayPin device") << mockDisplayPinDeviceClassId << Device::DeviceErrorNoError << "243681"; + QTest::newRow("Invalid: Add DisplayPin device (wrong pin)") << mockDisplayPinDeviceClassId << Device::DeviceErrorSetupFailed << "243682"; } void TestDevices::addDisplayPinDevices() { QFETCH(DeviceClassId, deviceClassId); - QFETCH(DeviceManager::DeviceError, error); + QFETCH(Device::DeviceError, error); QFETCH(QString, secret); // Discover device @@ -520,7 +520,7 @@ void TestDevices::addDisplayPinDevices() params.insert("discoveryParams", discoveryParams); QVariant response = injectAndWait("Devices.GetDiscoveredDevices", params); - verifyDeviceError(response, DeviceManager::DeviceErrorNoError); + verifyDeviceError(response, Device::DeviceErrorNoError); QCOMPARE(response.toMap().value("params").toMap().value("deviceDescriptors").toList().count(), 1); // Pair device @@ -545,7 +545,7 @@ void TestDevices::addDisplayPinDevices() verifyDeviceError(response, error); - if (error == DeviceManager::DeviceErrorNoError) { + if (error == Device::DeviceErrorNoError) { DeviceId deviceId(response.toMap().value("params").toMap().value("deviceId").toString()); params.clear(); params.insert("deviceId", deviceId.toString()); @@ -591,7 +591,7 @@ void TestDevices::parentChildDevices() params.clear(); params.insert("deviceId", childDeviceId.toString()); response = injectAndWait("Devices.RemoveConfiguredDevice", params); - verifyDeviceError(response, DeviceManager::DeviceErrorDeviceIsChild); + verifyDeviceError(response, Device::DeviceErrorDeviceIsChild); // check if the child device is still there response = injectAndWait("Devices.GetConfiguredDevices"); @@ -716,24 +716,24 @@ void TestDevices::getStateTypes() void TestDevices::getStateType_data() { QTest::addColumn("stateTypeId"); - QTest::addColumn("error"); + QTest::addColumn("error"); - QTest::newRow("valid int state") << mockIntStateId << DeviceManager::DeviceErrorNoError; - QTest::newRow("valid bool state") << mockBoolStateId << DeviceManager::DeviceErrorNoError; - QTest::newRow("invalid stateTypeId") << StateTypeId::createStateTypeId() << DeviceManager::DeviceErrorStateTypeNotFound; + QTest::newRow("valid int state") << mockIntStateId << Device::DeviceErrorNoError; + QTest::newRow("valid bool state") << mockBoolStateId << Device::DeviceErrorNoError; + QTest::newRow("invalid stateTypeId") << StateTypeId::createStateTypeId() << Device::DeviceErrorStateTypeNotFound; } void TestDevices::getStateType() { QFETCH(StateTypeId, stateTypeId); - QFETCH(DeviceManager::DeviceError, error); + QFETCH(Device::DeviceError, error); QVariantMap params; params.insert("stateTypeId", stateTypeId); QVariant response = injectAndWait("States.GetStateType", params); verifyDeviceError(response, error); - if (error != DeviceManager::DeviceErrorNoError) + if (error != Device::DeviceErrorNoError) return; QVariantMap stateType = response.toMap().value("params").toMap().value("stateType").toMap(); @@ -748,18 +748,18 @@ void TestDevices::getStateValue_data() { QTest::addColumn("deviceId"); QTest::addColumn("stateTypeId"); - QTest::addColumn("statusCode"); + QTest::addColumn("statusCode"); - QTest::newRow("valid deviceId") << m_mockDeviceId << mockIntStateId << DeviceManager::DeviceErrorNoError; - QTest::newRow("invalid deviceId") << DeviceId("094f8024-5caa-48c1-ab6a-de486a92088f") << mockIntStateId << DeviceManager::DeviceErrorDeviceNotFound; - QTest::newRow("invalid statetypeId") << m_mockDeviceId << StateTypeId("120514f1-343e-4621-9bff-dac616169df9") << DeviceManager::DeviceErrorStateTypeNotFound; + QTest::newRow("valid deviceId") << m_mockDeviceId << mockIntStateId << Device::DeviceErrorNoError; + QTest::newRow("invalid deviceId") << DeviceId("094f8024-5caa-48c1-ab6a-de486a92088f") << mockIntStateId << Device::DeviceErrorDeviceNotFound; + QTest::newRow("invalid statetypeId") << m_mockDeviceId << StateTypeId("120514f1-343e-4621-9bff-dac616169df9") << Device::DeviceErrorStateTypeNotFound; } void TestDevices::getStateValue() { QFETCH(DeviceId, deviceId); QFETCH(StateTypeId, stateTypeId); - QFETCH(DeviceManager::DeviceError, statusCode); + QFETCH(Device::DeviceError, statusCode); QVariantMap params; params.insert("deviceId", deviceId); @@ -767,7 +767,7 @@ void TestDevices::getStateValue() QVariant response = injectAndWait("Devices.GetStateValue", params); QCOMPARE(response.toMap().value("params").toMap().value("deviceError").toString(), JsonTypes::deviceErrorToString(statusCode)); - if (statusCode == DeviceManager::DeviceErrorNoError) { + if (statusCode == Device::DeviceErrorNoError) { QVariant value = response.toMap().value("params").toMap().value("value"); QCOMPARE(value.toInt(), 10); // Mock device has value 10 by default... } @@ -776,23 +776,23 @@ void TestDevices::getStateValue() void TestDevices::getStateValues_data() { QTest::addColumn("deviceId"); - QTest::addColumn("statusCode"); + QTest::addColumn("statusCode"); - QTest::newRow("valid deviceId") << m_mockDeviceId << DeviceManager::DeviceErrorNoError; - QTest::newRow("invalid deviceId") << DeviceId("094f8024-5caa-48c1-ab6a-de486a92088f") << DeviceManager::DeviceErrorDeviceNotFound; + QTest::newRow("valid deviceId") << m_mockDeviceId << Device::DeviceErrorNoError; + QTest::newRow("invalid deviceId") << DeviceId("094f8024-5caa-48c1-ab6a-de486a92088f") << Device::DeviceErrorDeviceNotFound; } void TestDevices::getStateValues() { QFETCH(DeviceId, deviceId); - QFETCH(DeviceManager::DeviceError, statusCode); + QFETCH(Device::DeviceError, statusCode); QVariantMap params; params.insert("deviceId", deviceId); QVariant response = injectAndWait("Devices.GetStateValues", params); QCOMPARE(response.toMap().value("params").toMap().value("deviceError").toString(), JsonTypes::deviceErrorToString(statusCode)); - if (statusCode == DeviceManager::DeviceErrorNoError) { + if (statusCode == Device::DeviceErrorNoError) { QVariantList values = response.toMap().value("params").toMap().value("values").toList(); QCOMPARE(values.count(), 6); // Mock device has 6 states... } @@ -980,19 +980,19 @@ void TestDevices::reconfigureDevices_data() QTest::addColumn("broken"); QTest::addColumn("newDeviceParams"); - QTest::addColumn("deviceError"); + QTest::addColumn("deviceError"); - QTest::newRow("valid - change async param") << false << asyncChangeDeviceParams << DeviceManager::DeviceErrorParameterNotWritable; - QTest::newRow("valid - change httpport param") << false << httpportChangeDeviceParams << DeviceManager::DeviceErrorNoError; - QTest::newRow("invalid - change httpport and async param") << false << asyncAndPortChangeDeviceParams << DeviceManager::DeviceErrorParameterNotWritable; - QTest::newRow("invalid - change all params (except broken)") << false << changeAllWritableDeviceParams << DeviceManager::DeviceErrorParameterNotWritable; + QTest::newRow("valid - change async param") << false << asyncChangeDeviceParams << Device::DeviceErrorParameterNotWritable; + QTest::newRow("valid - change httpport param") << false << httpportChangeDeviceParams << Device::DeviceErrorNoError; + QTest::newRow("invalid - change httpport and async param") << false << asyncAndPortChangeDeviceParams << Device::DeviceErrorParameterNotWritable; + QTest::newRow("invalid - change all params (except broken)") << false << changeAllWritableDeviceParams << Device::DeviceErrorParameterNotWritable; } void TestDevices::reconfigureDevices() { QFETCH(bool, broken); QFETCH(QVariantList, newDeviceParams); - QFETCH(DeviceManager::DeviceError, deviceError); + QFETCH(Device::DeviceError, deviceError); // add device QVariantMap params; @@ -1029,7 +1029,7 @@ void TestDevices::reconfigureDevices() verifyDeviceError(response, deviceError); // if the edit should have been successful - if (deviceError == DeviceManager::DeviceErrorNoError) { + if (deviceError == Device::DeviceErrorNoError) { response = injectAndWait("Devices.GetConfiguredDevices", QVariantMap()); bool found = false; @@ -1118,7 +1118,7 @@ void TestDevices::reconfigureByDiscovery_data() { QTest::addColumn("deviceClassId"); QTest::addColumn("resultCount"); - QTest::addColumn("error"); + QTest::addColumn("error"); QTest::addColumn("discoveryParams"); QVariantList discoveryParams; @@ -1127,14 +1127,14 @@ void TestDevices::reconfigureByDiscovery_data() resultCountParam.insert("value", 2); discoveryParams.append(resultCountParam); - QTest::newRow("discover 2 devices with params") << mockDeviceClassId << 2 << DeviceManager::DeviceErrorNoError << discoveryParams; + QTest::newRow("discover 2 devices with params") << mockDeviceClassId << 2 << Device::DeviceErrorNoError << discoveryParams; } void TestDevices::reconfigureByDiscovery() { QFETCH(DeviceClassId, deviceClassId); QFETCH(int, resultCount); - QFETCH(DeviceManager::DeviceError, error); + QFETCH(Device::DeviceError, error); QFETCH(QVariantList, discoveryParams); QVariantMap params; @@ -1143,7 +1143,7 @@ void TestDevices::reconfigureByDiscovery() QVariant response = injectAndWait("Devices.GetDiscoveredDevices", params); verifyDeviceError(response); - if (error == DeviceManager::DeviceErrorNoError) { + if (error == Device::DeviceErrorNoError) { QCOMPARE(response.toMap().value("params").toMap().value("deviceDescriptors").toList().count(), resultCount); } @@ -1182,7 +1182,7 @@ void TestDevices::reconfigureByDiscovery() response = injectAndWait("Devices.GetDiscoveredDevices", params); verifyDeviceError(response, error); - if (error == DeviceManager::DeviceErrorNoError) { + if (error == Device::DeviceErrorNoError) { QCOMPARE(response.toMap().value("params").toMap().value("deviceDescriptors").toList().count(), resultCount); } @@ -1320,7 +1320,7 @@ void TestDevices::reconfigureByDiscoveryAndPair() deviceDescriptors = response.toMap().value("params").toMap().value("deviceDescriptors").toList(); qCDebug(dcTests()) << "Discovery result:" << qUtf8Printable(QJsonDocument::fromVariant(deviceDescriptors).toJson(QJsonDocument::Indented)); - verifyDeviceError(response, DeviceManager::DeviceErrorNoError); + verifyDeviceError(response, Device::DeviceErrorNoError); QCOMPARE(deviceDescriptors.count(), 1); descriptor = deviceDescriptors.first(); @@ -1390,21 +1390,21 @@ void TestDevices::reconfigureAutodevice() void TestDevices::removeDevice_data() { QTest::addColumn("deviceId"); - QTest::addColumn("deviceError"); + QTest::addColumn("deviceError"); - QTest::newRow("Existing Device") << m_mockDeviceId << DeviceManager::DeviceErrorNoError; - QTest::newRow("Not existing Device") << DeviceId::createDeviceId() << DeviceManager::DeviceErrorDeviceNotFound; -// QTest::newRow("Auto device") << m_mockDeviceAutoId << DeviceManager::DeviceErrorCreationMethodNotSupported; + QTest::newRow("Existing Device") << m_mockDeviceId << Device::DeviceErrorNoError; + QTest::newRow("Not existing Device") << DeviceId::createDeviceId() << Device::DeviceErrorDeviceNotFound; +// QTest::newRow("Auto device") << m_mockDeviceAutoId << Device::DeviceErrorCreationMethodNotSupported; } void TestDevices::removeDevice() { QFETCH(DeviceId, deviceId); - QFETCH(DeviceManager::DeviceError, deviceError); + QFETCH(Device::DeviceError, deviceError); NymeaSettings settings(NymeaSettings::SettingsRoleDevices); settings.beginGroup("DeviceConfig"); - if (deviceError == DeviceManager::DeviceErrorNoError) { + if (deviceError == Device::DeviceErrorNoError) { settings.beginGroup(m_mockDeviceId.toString()); // Make sure we have some config values for this device QVERIFY(settings.allKeys().count() > 0); @@ -1417,7 +1417,7 @@ void TestDevices::removeDevice() verifyDeviceError(response, deviceError); - if (DeviceManager::DeviceErrorNoError) { + if (Device::DeviceErrorNoError) { // Make sure the device is gone from settings too QCOMPARE(settings.allKeys().count(), 0); } diff --git a/tests/auto/events/testevents.cpp b/tests/auto/events/testevents.cpp index 03bafc5b..67954c5d 100644 --- a/tests/auto/events/testevents.cpp +++ b/tests/auto/events/testevents.cpp @@ -113,16 +113,16 @@ void TestEvents::params() void TestEvents::getEventType_data() { QTest::addColumn("eventTypeId"); - QTest::addColumn("error"); + QTest::addColumn("error"); - QTest::newRow("valid eventypeid") << mockEvent1Id << DeviceManager::DeviceErrorNoError; - QTest::newRow("invalid eventypeid") << EventTypeId::createEventTypeId() << DeviceManager::DeviceErrorEventTypeNotFound; + QTest::newRow("valid eventypeid") << mockEvent1Id << Device::DeviceErrorNoError; + QTest::newRow("invalid eventypeid") << EventTypeId::createEventTypeId() << Device::DeviceErrorEventTypeNotFound; } void TestEvents::getEventType() { QFETCH(EventTypeId, eventTypeId); - QFETCH(DeviceManager::DeviceError, error); + QFETCH(Device::DeviceError, error); QVariantMap params; params.insert("eventTypeId", eventTypeId.toString()); @@ -130,7 +130,7 @@ void TestEvents::getEventType() verifyDeviceError(response, error); - if (error == DeviceManager::DeviceErrorNoError) { + if (error == Device::DeviceErrorNoError) { QVERIFY2(EventTypeId(response.toMap().value("params").toMap().value("eventType").toMap().value("id").toString()) == eventTypeId, "Didn't get a reply for the same actionTypeId as requested."); } } diff --git a/tests/auto/logging/testlogging.cpp b/tests/auto/logging/testlogging.cpp index b60de707..43651049 100644 --- a/tests/auto/logging/testlogging.cpp +++ b/tests/auto/logging/testlogging.cpp @@ -348,7 +348,7 @@ void TestLogging::actionLog() params.insert("actionTypeId", mockActionIdFailing); params.insert("deviceId", m_mockDeviceId); response = injectAndWait("Actions.ExecuteAction", params); - verifyDeviceError(response, DeviceManager::DeviceErrorSetupFailed); + verifyDeviceError(response, Device::DeviceErrorSetupFailed); clientSpy.wait(200); @@ -367,7 +367,7 @@ void TestLogging::actionLog() QCOMPARE(logEntry.value("eventType").toString(), JsonTypes::loggingEventTypeToString(Logging::LoggingEventTypeTrigger)); QCOMPARE(logEntry.value("source").toString(), JsonTypes::loggingSourceToString(Logging::LoggingSourceActions)); QCOMPARE(logEntry.value("loggingLevel").toString(), JsonTypes::loggingLevelToString(Logging::LoggingLevelAlert)); - QCOMPARE(logEntry.value("errorCode").toString(), JsonTypes::deviceErrorToString(DeviceManager::DeviceErrorSetupFailed)); + QCOMPARE(logEntry.value("errorCode").toString(), JsonTypes::deviceErrorToString(Device::DeviceErrorSetupFailed)); break; } } @@ -474,7 +474,7 @@ void TestLogging::testDoubleValues() params.insert("discoveryParams", discoveryParams); QVariant response = injectAndWait("Devices.GetDiscoveredDevices", params); - verifyDeviceError(response, DeviceManager::DeviceErrorNoError); + verifyDeviceError(response, Device::DeviceErrorNoError); // Pair device DeviceDescriptorId descriptorId = DeviceDescriptorId(response.toMap().value("params").toMap().value("deviceDescriptors").toList().first().toMap().value("id").toString()); diff --git a/tests/auto/restdeviceclasses/testrestdeviceclasses.cpp b/tests/auto/restdeviceclasses/testrestdeviceclasses.cpp index 0cae1266..7643a372 100644 --- a/tests/auto/restdeviceclasses/testrestdeviceclasses.cpp +++ b/tests/auto/restdeviceclasses/testrestdeviceclasses.cpp @@ -105,7 +105,7 @@ void TestRestDeviceClasses::getSupportedDevices() url.setQuery(query); response = getAndWait(QNetworkRequest(url), 400); - QCOMPARE(JsonTypes::deviceErrorToString(DeviceManager::DeviceErrorVendorNotFound), response.toMap().value("error").toString()); + QCOMPARE(JsonTypes::deviceErrorToString(Device::DeviceErrorVendorNotFound), response.toMap().value("error").toString()); } void TestRestDeviceClasses::invalidMethod() @@ -136,17 +136,17 @@ void TestRestDeviceClasses::getActionTypes_data() QTest::addColumn("deviceClassId"); QTest::addColumn("actionTypeId"); QTest::addColumn("expectedStatusCode"); - QTest::addColumn("error"); + QTest::addColumn("error"); - QTest::newRow("all ActionTypes") << mockDeviceClassId.toString() << QString() << 200 << DeviceManager::DeviceErrorNoError; - QTest::newRow("ActionType async") << mockDeviceClassId.toString() << mockActionIdAsync.toString() << 200 << DeviceManager::DeviceErrorNoError; - QTest::newRow("ActionType no params") << mockDeviceClassId.toString() << mockActionIdNoParams.toString() << 200 << DeviceManager::DeviceErrorNoError; - QTest::newRow("ActionType failing") << mockDeviceClassId.toString() << mockActionIdFailing.toString() << 200 << DeviceManager::DeviceErrorNoError; - QTest::newRow("ActionType with params") << mockDeviceClassId.toString() << mockActionIdWithParams.toString() << 200 << DeviceManager::DeviceErrorNoError; - QTest::newRow("invalid DeviceClassId") << DeviceClassId::createDeviceClassId().toString() << mockActionIdNoParams.toString() << 404 << DeviceManager::DeviceErrorDeviceClassNotFound; - QTest::newRow("invalid ActionTypeId") << mockDeviceClassId.toString() << ActionTypeId::createActionTypeId().toString() << 404 << DeviceManager::DeviceErrorActionTypeNotFound; - QTest::newRow("invalid ActionTypeId format") << mockDeviceClassId.toString() << "uuid" << 400 << DeviceManager::DeviceErrorActionTypeNotFound; - QTest::newRow("invalid DeviceClassId format") << "uuid" << "uuid" << 400 << DeviceManager::DeviceErrorDeviceClassNotFound; + QTest::newRow("all ActionTypes") << mockDeviceClassId.toString() << QString() << 200 << Device::DeviceErrorNoError; + QTest::newRow("ActionType async") << mockDeviceClassId.toString() << mockActionIdAsync.toString() << 200 << Device::DeviceErrorNoError; + QTest::newRow("ActionType no params") << mockDeviceClassId.toString() << mockActionIdNoParams.toString() << 200 << Device::DeviceErrorNoError; + QTest::newRow("ActionType failing") << mockDeviceClassId.toString() << mockActionIdFailing.toString() << 200 << Device::DeviceErrorNoError; + QTest::newRow("ActionType with params") << mockDeviceClassId.toString() << mockActionIdWithParams.toString() << 200 << Device::DeviceErrorNoError; + QTest::newRow("invalid DeviceClassId") << DeviceClassId::createDeviceClassId().toString() << mockActionIdNoParams.toString() << 404 << Device::DeviceErrorDeviceClassNotFound; + QTest::newRow("invalid ActionTypeId") << mockDeviceClassId.toString() << ActionTypeId::createActionTypeId().toString() << 404 << Device::DeviceErrorActionTypeNotFound; + QTest::newRow("invalid ActionTypeId format") << mockDeviceClassId.toString() << "uuid" << 400 << Device::DeviceErrorActionTypeNotFound; + QTest::newRow("invalid DeviceClassId format") << "uuid" << "uuid" << 400 << Device::DeviceErrorDeviceClassNotFound; } @@ -155,7 +155,7 @@ void TestRestDeviceClasses::getActionTypes() QFETCH(QString, deviceClassId); QFETCH(QString, actionTypeId); QFETCH(int, expectedStatusCode); - QFETCH(DeviceManager::DeviceError, error); + QFETCH(Device::DeviceError, error); QNetworkRequest request; if (!actionTypeId.isEmpty()) { @@ -177,15 +177,15 @@ void TestRestDeviceClasses::getStateTypes_data() QTest::addColumn("deviceClassId"); QTest::addColumn("stateTypeId"); QTest::addColumn("expectedStatusCode"); - QTest::addColumn("error"); + QTest::addColumn("error"); - QTest::newRow("all ActionTypes") << mockDeviceClassId.toString() << QString() << 200 << DeviceManager::DeviceErrorNoError; - QTest::newRow("StateType bool") << mockDeviceClassId.toString() << mockBoolStateId.toString() << 200 << DeviceManager::DeviceErrorNoError; - QTest::newRow("StateType int") << mockDeviceClassId.toString() << mockIntStateId.toString() << 200 << DeviceManager::DeviceErrorNoError; - QTest::newRow("invalid DeviceClassId") << DeviceClassId::createDeviceClassId().toString() << mockBoolStateId.toString() << 404 << DeviceManager::DeviceErrorDeviceClassNotFound; - QTest::newRow("invalid StateTypeId") << mockDeviceClassId.toString() << StateTypeId::createStateTypeId().toString() << 404 << DeviceManager::DeviceErrorStateTypeNotFound; - QTest::newRow("invalid StateTypeId format") << mockDeviceClassId.toString() << "uuid" << 400 << DeviceManager::DeviceErrorStateTypeNotFound; - QTest::newRow("invalid DeviceClassId format") << "uuid" << "uuid" << 400 << DeviceManager::DeviceErrorDeviceClassNotFound; + QTest::newRow("all ActionTypes") << mockDeviceClassId.toString() << QString() << 200 << Device::DeviceErrorNoError; + QTest::newRow("StateType bool") << mockDeviceClassId.toString() << mockBoolStateId.toString() << 200 << Device::DeviceErrorNoError; + QTest::newRow("StateType int") << mockDeviceClassId.toString() << mockIntStateId.toString() << 200 << Device::DeviceErrorNoError; + QTest::newRow("invalid DeviceClassId") << DeviceClassId::createDeviceClassId().toString() << mockBoolStateId.toString() << 404 << Device::DeviceErrorDeviceClassNotFound; + QTest::newRow("invalid StateTypeId") << mockDeviceClassId.toString() << StateTypeId::createStateTypeId().toString() << 404 << Device::DeviceErrorStateTypeNotFound; + QTest::newRow("invalid StateTypeId format") << mockDeviceClassId.toString() << "uuid" << 400 << Device::DeviceErrorStateTypeNotFound; + QTest::newRow("invalid DeviceClassId format") << "uuid" << "uuid" << 400 << Device::DeviceErrorDeviceClassNotFound; } void TestRestDeviceClasses::getStateTypes() @@ -193,7 +193,7 @@ void TestRestDeviceClasses::getStateTypes() QFETCH(QString, deviceClassId); QFETCH(QString, stateTypeId); QFETCH(int, expectedStatusCode); - QFETCH(DeviceManager::DeviceError, error); + QFETCH(Device::DeviceError, error); QNetworkRequest request; if (!stateTypeId.isEmpty()) { @@ -215,15 +215,15 @@ void TestRestDeviceClasses::getEventTypes_data() QTest::addColumn("deviceClassId"); QTest::addColumn("eventTypeId"); QTest::addColumn("expectedStatusCode"); - QTest::addColumn("error"); + QTest::addColumn("error"); - QTest::newRow("all ActionTypes") << mockDeviceClassId.toString() << QString() << 200 << DeviceManager::DeviceErrorNoError; - QTest::newRow("EventType 1") << mockDeviceClassId.toString() << mockEvent1Id.toString() << 200 << DeviceManager::DeviceErrorNoError; - QTest::newRow("EventType 2") << mockDeviceClassId.toString() << mockEvent2Id.toString() << 200 << DeviceManager::DeviceErrorNoError; - QTest::newRow("invalid DeviceClassId") << DeviceClassId::createDeviceClassId().toString() << mockEvent2Id.toString() << 404 << DeviceManager::DeviceErrorDeviceClassNotFound; - QTest::newRow("invalid EventTypeId") << mockDeviceClassId.toString() << EventTypeId::createEventTypeId().toString() << 404 << DeviceManager::DeviceErrorEventTypeNotFound; - QTest::newRow("invalid EventTypeId format") << mockDeviceClassId.toString() << "uuid" << 400 << DeviceManager::DeviceErrorEventTypeNotFound; - QTest::newRow("invalid DeviceClassId format") << "uuid" << "uuid" << 400 << DeviceManager::DeviceErrorDeviceClassNotFound; + QTest::newRow("all ActionTypes") << mockDeviceClassId.toString() << QString() << 200 << Device::DeviceErrorNoError; + QTest::newRow("EventType 1") << mockDeviceClassId.toString() << mockEvent1Id.toString() << 200 << Device::DeviceErrorNoError; + QTest::newRow("EventType 2") << mockDeviceClassId.toString() << mockEvent2Id.toString() << 200 << Device::DeviceErrorNoError; + QTest::newRow("invalid DeviceClassId") << DeviceClassId::createDeviceClassId().toString() << mockEvent2Id.toString() << 404 << Device::DeviceErrorDeviceClassNotFound; + QTest::newRow("invalid EventTypeId") << mockDeviceClassId.toString() << EventTypeId::createEventTypeId().toString() << 404 << Device::DeviceErrorEventTypeNotFound; + QTest::newRow("invalid EventTypeId format") << mockDeviceClassId.toString() << "uuid" << 400 << Device::DeviceErrorEventTypeNotFound; + QTest::newRow("invalid DeviceClassId format") << "uuid" << "uuid" << 400 << Device::DeviceErrorDeviceClassNotFound; } void TestRestDeviceClasses::getEventTypes() @@ -231,7 +231,7 @@ void TestRestDeviceClasses::getEventTypes() QFETCH(QString, deviceClassId); QFETCH(QString, eventTypeId); QFETCH(int, expectedStatusCode); - QFETCH(DeviceManager::DeviceError, error); + QFETCH(Device::DeviceError, error); QNetworkRequest request; if (!eventTypeId.isNull()) { @@ -254,7 +254,7 @@ void TestRestDeviceClasses::discoverDevices_data() QTest::addColumn("resultCount"); QTest::addColumn("discoveryParams"); QTest::addColumn("expectedStatusCode"); - QTest::addColumn("error"); + QTest::addColumn("error"); QVariantMap resultCountParam; resultCountParam.insert("paramTypeId", resultCountParamTypeId); @@ -270,10 +270,10 @@ void TestRestDeviceClasses::discoverDevices_data() QVariantList invalidDiscoveryParams; invalidDiscoveryParams.append(invalidResultCountParam); - QTest::newRow("valid deviceClassId without params") << mockDeviceClassId << 2 << QVariantList() << 200 << DeviceManager::DeviceErrorNoError; - QTest::newRow("valid deviceClassId with params") << mockDeviceClassId << 1 << discoveryParams << 200 << DeviceManager::DeviceErrorNoError; - QTest::newRow("invalid deviceClassId") << DeviceClassId::createDeviceClassId() << 0 << QVariantList() << 404 << DeviceManager::DeviceErrorDeviceClassNotFound; - QTest::newRow("valid deviceClassId with invalid params") << mockDeviceClassId << 10 << invalidDiscoveryParams << 500 << DeviceManager::DeviceErrorInvalidParameter; + QTest::newRow("valid deviceClassId without params") << mockDeviceClassId << 2 << QVariantList() << 200 << Device::DeviceErrorNoError; + QTest::newRow("valid deviceClassId with params") << mockDeviceClassId << 1 << discoveryParams << 200 << Device::DeviceErrorNoError; + QTest::newRow("invalid deviceClassId") << DeviceClassId::createDeviceClassId() << 0 << QVariantList() << 404 << Device::DeviceErrorDeviceClassNotFound; + QTest::newRow("valid deviceClassId with invalid params") << mockDeviceClassId << 10 << invalidDiscoveryParams << 500 << Device::DeviceErrorInvalidParameter; } void TestRestDeviceClasses::discoverDevices() @@ -282,7 +282,7 @@ void TestRestDeviceClasses::discoverDevices() QFETCH(int, resultCount); QFETCH(QVariantList, discoveryParams); QFETCH(int, expectedStatusCode); - QFETCH(DeviceManager::DeviceError, error); + QFETCH(Device::DeviceError, error); QVariantMap params; params.insert("deviceClassId", deviceClassId); diff --git a/tests/auto/restdevices/testrestdevices.cpp b/tests/auto/restdevices/testrestdevices.cpp index b83fa252..8b42b751 100644 --- a/tests/auto/restdevices/testrestdevices.cpp +++ b/tests/auto/restdevices/testrestdevices.cpp @@ -371,7 +371,7 @@ void TestRestDevices::parentChildDevices() QNetworkRequest deleteRequest(QUrl(QString("https://localhost:3333/api/v1/devices/%1").arg(childDeviceId.toString()))); response = deleteAndWait(deleteRequest, 400); //QVERIFY2(!response.isNull(), "Could not delete device"); - QCOMPARE(JsonTypes::deviceErrorToString(DeviceManager::DeviceErrorDeviceIsChild), response.toMap().value("error").toString()); + QCOMPARE(JsonTypes::deviceErrorToString(Device::DeviceErrorDeviceIsChild), response.toMap().value("error").toString()); // check if the child device is still there response = getAndWait(QNetworkRequest(QUrl("https://localhost:3333/api/v1/devices"))); @@ -415,7 +415,7 @@ void TestRestDevices::executeAction_data() QTest::addColumn("actionTypeId"); QTest::addColumn("actionParams"); QTest::addColumn("expectedStatusCode"); - QTest::addColumn("error"); + QTest::addColumn("error"); QVariantList params; QVariantMap param1; @@ -427,13 +427,13 @@ void TestRestDevices::executeAction_data() param2.insert("value", true); params.append(param2); - QTest::newRow("valid action") << m_mockDeviceId << mockActionIdWithParams << params << 200 << DeviceManager::DeviceErrorNoError; - QTest::newRow("invalid deviceId") << DeviceId::createDeviceId() << mockActionIdWithParams << params << 404 << DeviceManager::DeviceErrorDeviceNotFound; - QTest::newRow("invalid actionTypeId") << m_mockDeviceId << ActionTypeId::createActionTypeId() << params << 404 << DeviceManager::DeviceErrorActionTypeNotFound; - QTest::newRow("missing params") << m_mockDeviceId << mockActionIdWithParams << QVariantList() << 500 << DeviceManager::DeviceErrorMissingParameter; - QTest::newRow("async action") << m_mockDeviceId << mockActionIdAsync << QVariantList() << 200 << DeviceManager::DeviceErrorNoError; - QTest::newRow("broken action") << m_mockDeviceId << mockActionIdFailing << QVariantList() << 500 << DeviceManager::DeviceErrorSetupFailed; - QTest::newRow("async broken action") << m_mockDeviceId << mockActionIdAsyncFailing << QVariantList() << 500 << DeviceManager::DeviceErrorSetupFailed; + QTest::newRow("valid action") << m_mockDeviceId << mockActionIdWithParams << params << 200 << Device::DeviceErrorNoError; + QTest::newRow("invalid deviceId") << DeviceId::createDeviceId() << mockActionIdWithParams << params << 404 << Device::DeviceErrorDeviceNotFound; + QTest::newRow("invalid actionTypeId") << m_mockDeviceId << ActionTypeId::createActionTypeId() << params << 404 << Device::DeviceErrorActionTypeNotFound; + QTest::newRow("missing params") << m_mockDeviceId << mockActionIdWithParams << QVariantList() << 500 << Device::DeviceErrorMissingParameter; + QTest::newRow("async action") << m_mockDeviceId << mockActionIdAsync << QVariantList() << 200 << Device::DeviceErrorNoError; + QTest::newRow("broken action") << m_mockDeviceId << mockActionIdFailing << QVariantList() << 500 << Device::DeviceErrorSetupFailed; + QTest::newRow("async broken action") << m_mockDeviceId << mockActionIdAsyncFailing << QVariantList() << 500 << Device::DeviceErrorSetupFailed; } void TestRestDevices::executeAction() @@ -442,7 +442,7 @@ void TestRestDevices::executeAction() QFETCH(ActionTypeId, actionTypeId); QFETCH(QVariantList, actionParams); QFETCH(int, expectedStatusCode); - QFETCH(DeviceManager::DeviceError, error); + QFETCH(Device::DeviceError, error); // execute action QVariantMap params; @@ -465,7 +465,7 @@ void TestRestDevices::executeAction() reply->deleteLater(); QByteArray data = reply->readAll(); - if (error == DeviceManager::DeviceErrorNoError) { + if (error == Device::DeviceErrorNoError) { QVERIFY2(actionTypeId == ActionTypeId(data), QString("ActionTypeId mismatch. Got %1, Expected: %2") .arg(ActionTypeId(data).toString()).arg(actionTypeId.toString()).toLatin1().data()); } else { @@ -499,14 +499,14 @@ void TestRestDevices::getStateValue_data() QTest::addColumn("deviceId"); QTest::addColumn("stateTypeId"); QTest::addColumn("expectedStatusCode"); - QTest::addColumn("error"); + QTest::addColumn("error"); - QTest::newRow("existing state") << device->id().toString() << mockIntStateId.toString() << 200 << DeviceManager::DeviceErrorNoError; - QTest::newRow("all states") << device->id().toString() << QString() << 200 << DeviceManager::DeviceErrorNoError; - QTest::newRow("invalid device") << DeviceId::createDeviceId().toString() << mockIntStateId.toString() << 404 << DeviceManager::DeviceErrorDeviceNotFound; - QTest::newRow("invalid device id format") << "uuid" << StateTypeId::createStateTypeId().toString() << 400 << DeviceManager::DeviceErrorDeviceNotFound; - QTest::newRow("invalid statetype") << device->id().toString() << StateTypeId::createStateTypeId().toString() << 404 << DeviceManager::DeviceErrorStateTypeNotFound; - QTest::newRow("invalid statetype format") << device->id().toString() << "uuid" << 400 << DeviceManager::DeviceErrorStateTypeNotFound; + QTest::newRow("existing state") << device->id().toString() << mockIntStateId.toString() << 200 << Device::DeviceErrorNoError; + QTest::newRow("all states") << device->id().toString() << QString() << 200 << Device::DeviceErrorNoError; + QTest::newRow("invalid device") << DeviceId::createDeviceId().toString() << mockIntStateId.toString() << 404 << Device::DeviceErrorDeviceNotFound; + QTest::newRow("invalid device id format") << "uuid" << StateTypeId::createStateTypeId().toString() << 400 << Device::DeviceErrorDeviceNotFound; + QTest::newRow("invalid statetype") << device->id().toString() << StateTypeId::createStateTypeId().toString() << 404 << Device::DeviceErrorStateTypeNotFound; + QTest::newRow("invalid statetype format") << device->id().toString() << "uuid" << 400 << Device::DeviceErrorStateTypeNotFound; } void TestRestDevices::getStateValue() @@ -514,7 +514,7 @@ void TestRestDevices::getStateValue() QFETCH(QString, deviceId); QFETCH(QString, stateTypeId); QFETCH(int, expectedStatusCode); - QFETCH(DeviceManager::DeviceError, error); + QFETCH(Device::DeviceError, error); QNetworkRequest request; request.setHeader(QNetworkRequest::ContentTypeHeader, "text/json"); @@ -572,7 +572,7 @@ void TestRestDevices::editDevices() deviceRequest.setHeader(QNetworkRequest::ContentTypeHeader, "application/json"); response = postAndWait(deviceRequest, params); - QVERIFY2(response.toMap().value("error").toString() == JsonTypes::deviceErrorToString(DeviceManager::DeviceErrorNoError), "Could not edit device name"); + QVERIFY2(response.toMap().value("error").toString() == JsonTypes::deviceErrorToString(Device::DeviceErrorNoError), "Could not edit device name"); // check device name response = getAndWait(deviceRequest); @@ -580,7 +580,7 @@ void TestRestDevices::editDevices() // Remove the device response = deleteAndWait(deviceRequest); - QVERIFY2(response.toMap().value("error").toString() == JsonTypes::deviceErrorToString(DeviceManager::DeviceErrorNoError), "Could not remove device"); + QVERIFY2(response.toMap().value("error").toString() == JsonTypes::deviceErrorToString(Device::DeviceErrorNoError), "Could not remove device"); } void TestRestDevices::reconfigureDevices_data() @@ -614,12 +614,12 @@ void TestRestDevices::reconfigureDevices_data() QTest::addColumn("broken"); QTest::addColumn("newDeviceParams"); QTest::addColumn("expectedStatusCode"); - QTest::addColumn("error"); + QTest::addColumn("error"); - QTest::newRow("invalid - change async param") << false << asyncChangeDeviceParams << 500 << DeviceManager::DeviceErrorParameterNotWritable; - QTest::newRow("valid - change httpport param") << false << httpportChangeDeviceParams << 200 << DeviceManager::DeviceErrorNoError; - QTest::newRow("valid - change httpport and async param") << false << asyncAndPortChangeDeviceParams << 500 << DeviceManager::DeviceErrorParameterNotWritable; - QTest::newRow("invalid - change all params (except broken)") << false << changeAllWritableDeviceParams << 500 << DeviceManager::DeviceErrorParameterNotWritable; + QTest::newRow("invalid - change async param") << false << asyncChangeDeviceParams << 500 << Device::DeviceErrorParameterNotWritable; + QTest::newRow("valid - change httpport param") << false << httpportChangeDeviceParams << 200 << Device::DeviceErrorNoError; + QTest::newRow("valid - change httpport and async param") << false << asyncAndPortChangeDeviceParams << 500 << Device::DeviceErrorParameterNotWritable; + QTest::newRow("invalid - change all params (except broken)") << false << changeAllWritableDeviceParams << 500 << Device::DeviceErrorParameterNotWritable; } void TestRestDevices::reconfigureDevices() @@ -627,7 +627,7 @@ void TestRestDevices::reconfigureDevices() QFETCH(bool, broken); QFETCH(QVariantList, newDeviceParams); QFETCH(int, expectedStatusCode); - QFETCH(DeviceManager::DeviceError, error); + QFETCH(Device::DeviceError, error); // add device QVariantMap params; diff --git a/tests/auto/restlogging/testrestlogging.cpp b/tests/auto/restlogging/testrestlogging.cpp index 0f91bc2b..303f7d0c 100644 --- a/tests/auto/restlogging/testrestlogging.cpp +++ b/tests/auto/restlogging/testrestlogging.cpp @@ -272,7 +272,7 @@ void TestRestLogging::actionLog() params.insert("actionTypeId", mockActionIdFailing); params.insert("deviceId", m_mockDeviceId); response = injectAndWait("Actions.ExecuteAction", params); - verifyDeviceError(response, DeviceManager::DeviceErrorSetupFailed); + verifyDeviceError(response, Device::DeviceErrorSetupFailed); clientSpy.wait(200); notification = checkNotification(clientSpy, "Logging.LogEntryAdded"); @@ -286,7 +286,7 @@ void TestRestLogging::actionLog() QCOMPARE(logEntry.value("eventType").toString(), JsonTypes::loggingEventTypeToString(Logging::LoggingEventTypeTrigger)); QCOMPARE(logEntry.value("source").toString(), JsonTypes::loggingSourceToString(Logging::LoggingSourceActions)); QCOMPARE(logEntry.value("loggingLevel").toString(), JsonTypes::loggingLevelToString(Logging::LoggingLevelAlert)); - QCOMPARE(logEntry.value("errorCode").toString(), JsonTypes::deviceErrorToString(DeviceManager::DeviceErrorSetupFailed)); + QCOMPARE(logEntry.value("errorCode").toString(), JsonTypes::deviceErrorToString(Device::DeviceErrorSetupFailed)); // get this logentry with filter params.clear(); diff --git a/tests/auto/restplugins/testrestplugins.cpp b/tests/auto/restplugins/testrestplugins.cpp index f98987d1..11366f8b 100644 --- a/tests/auto/restplugins/testrestplugins.cpp +++ b/tests/auto/restplugins/testrestplugins.cpp @@ -146,7 +146,7 @@ void TestRestPlugins::invalidPlugin() QNetworkRequest request(QUrl("https://localhost:3333/api/v1/vendors/" + path)); QVariant response = getAndWait(request, expectedStatusCode); - QCOMPARE(JsonTypes::deviceErrorToString(DeviceManager::DeviceErrorVendorNotFound), response.toMap().value("error").toString()); + QCOMPARE(JsonTypes::deviceErrorToString(Device::DeviceErrorVendorNotFound), response.toMap().value("error").toString()); } void TestRestPlugins::getPluginConfiguration() diff --git a/tests/auto/restvendors/testrestvendors.cpp b/tests/auto/restvendors/testrestvendors.cpp index b5a3eca6..0a41ebe7 100644 --- a/tests/auto/restvendors/testrestvendors.cpp +++ b/tests/auto/restvendors/testrestvendors.cpp @@ -139,7 +139,7 @@ void TestRestVendors::invalidVendor() QNetworkRequest request(QUrl("https://localhost:3333/api/v1/vendors/" + path)); QVariant response = getAndWait(request, expectedStatusCode); - QCOMPARE(JsonTypes::deviceErrorToString(DeviceManager::DeviceErrorVendorNotFound), response.toMap().value("error").toString()); + QCOMPARE(JsonTypes::deviceErrorToString(Device::DeviceErrorVendorNotFound), response.toMap().value("error").toString()); } #include "testrestvendors.moc" diff --git a/tests/auto/rules/testrules.cpp b/tests/auto/rules/testrules.cpp index f86d3a0d..f51a21e9 100644 --- a/tests/auto/rules/testrules.cpp +++ b/tests/auto/rules/testrules.cpp @@ -154,7 +154,7 @@ DeviceId TestRules::addDisplayPinDevice() params.insert("discoveryParams", discoveryParams); QVariant response = injectAndWait("Devices.GetDiscoveredDevices", params); - verifyDeviceError(response, DeviceManager::DeviceErrorNoError); + verifyDeviceError(response, Device::DeviceErrorNoError); // Pair device DeviceDescriptorId descriptorId = DeviceDescriptorId(response.toMap().value("params").toMap().value("deviceDescriptors").toList().first().toMap().value("id").toString()); @@ -2362,13 +2362,13 @@ void TestRules::removePolicyUpdate() params.clear(); response.clear(); params.insert("deviceId", childDeviceId); response = injectAndWait("Devices.RemoveConfiguredDevice", params); - verifyDeviceError(response, DeviceManager::DeviceErrorDeviceIsChild); + verifyDeviceError(response, Device::DeviceErrorDeviceIsChild); // Try to remove child device params.clear(); response.clear(); params.insert("deviceId", parentDeviceId); response = injectAndWait("Devices.RemoveConfiguredDevice", params); - verifyDeviceError(response, DeviceManager::DeviceErrorDeviceInRule); + verifyDeviceError(response, Device::DeviceErrorDeviceInRule); // Remove policy params.clear(); response.clear(); @@ -2445,13 +2445,13 @@ void TestRules::removePolicyCascade() params.clear(); response.clear(); params.insert("deviceId", childDeviceId); response = injectAndWait("Devices.RemoveConfiguredDevice", params); - verifyDeviceError(response, DeviceManager::DeviceErrorDeviceIsChild); + verifyDeviceError(response, Device::DeviceErrorDeviceIsChild); // Try to remove child device params.clear(); response.clear(); params.insert("deviceId", parentDeviceId); response = injectAndWait("Devices.RemoveConfiguredDevice", params); - verifyDeviceError(response, DeviceManager::DeviceErrorDeviceInRule); + verifyDeviceError(response, Device::DeviceErrorDeviceInRule); // Remove policy params.clear(); response.clear(); @@ -2530,14 +2530,14 @@ void TestRules::removePolicyUpdateRendersUselessRule() params.clear(); response.clear(); params.insert("deviceId", childDeviceId); response = injectAndWait("Devices.RemoveConfiguredDevice", params); - verifyDeviceError(response, DeviceManager::DeviceErrorDeviceIsChild); + verifyDeviceError(response, Device::DeviceErrorDeviceIsChild); // Try to remove child device qCDebug(dcTests()) << "Removing device (expeciting failure - device in use)"; params.clear(); response.clear(); params.insert("deviceId", parentDeviceId); response = injectAndWait("Devices.RemoveConfiguredDevice", params); - verifyDeviceError(response, DeviceManager::DeviceErrorDeviceInRule); + verifyDeviceError(response, Device::DeviceErrorDeviceInRule); // Remove policy qCDebug(dcTests()) << "Removing device with update policy"; diff --git a/tests/auto/states/teststates.cpp b/tests/auto/states/teststates.cpp index 1eb3c046..70e1a683 100644 --- a/tests/auto/states/teststates.cpp +++ b/tests/auto/states/teststates.cpp @@ -54,18 +54,18 @@ void TestStates::getStateValue_data() QTest::addColumn("deviceId"); QTest::addColumn("stateTypeId"); - QTest::addColumn("error"); + QTest::addColumn("error"); - QTest::newRow("existing state") << device->id() << mockIntStateId << DeviceManager::DeviceErrorNoError; - QTest::newRow("invalid device") << DeviceId::createDeviceId() << mockIntStateId << DeviceManager::DeviceErrorDeviceNotFound; - QTest::newRow("invalid statetype") << device->id() << StateTypeId::createStateTypeId() << DeviceManager::DeviceErrorStateTypeNotFound; + QTest::newRow("existing state") << device->id() << mockIntStateId << Device::DeviceErrorNoError; + QTest::newRow("invalid device") << DeviceId::createDeviceId() << mockIntStateId << Device::DeviceErrorDeviceNotFound; + QTest::newRow("invalid statetype") << device->id() << StateTypeId::createStateTypeId() << Device::DeviceErrorStateTypeNotFound; } void TestStates::getStateValue() { QFETCH(DeviceId, deviceId); QFETCH(StateTypeId, stateTypeId); - QFETCH(DeviceManager::DeviceError, error); + QFETCH(Device::DeviceError, error); QVariantMap params; params.insert("deviceId", deviceId.toString()); diff --git a/tests/auto/userloading/testuserloading.cpp b/tests/auto/userloading/testuserloading.cpp index 2f4498cc..f6daab21 100644 --- a/tests/auto/userloading/testuserloading.cpp +++ b/tests/auto/userloading/testuserloading.cpp @@ -23,7 +23,7 @@ #include "logging/logengine.h" #include "logging/logvaluetool.h" -#include "usermanager.h" +#include "usermanager/usermanager.h" using namespace nymeaserver; diff --git a/tests/testlib/nymeatestbase.h b/tests/testlib/nymeatestbase.h index a1985a88..e8074fe9 100644 --- a/tests/testlib/nymeatestbase.h +++ b/tests/testlib/nymeatestbase.h @@ -139,7 +139,7 @@ protected: verifyError(response, "ruleError", JsonTypes::ruleErrorToString(error)); } - inline void verifyDeviceError(const QVariant &response, DeviceManager::DeviceError error = DeviceManager::DeviceErrorNoError) { + inline void verifyDeviceError(const QVariant &response, Device::DeviceError error = Device::DeviceErrorNoError) { verifyError(response, "deviceError", JsonTypes::deviceErrorToString(error)); }