fix awattar setup

This commit is contained in:
Simon Stürz 2016-01-20 12:45:54 +01:00 committed by Michael Zanetti
parent b07d9a9494
commit b4155184bc
2 changed files with 90 additions and 97 deletions

View File

@ -72,9 +72,10 @@
#include <QJsonDocument> #include <QJsonDocument>
#include <QSslConfiguration> #include <QSslConfiguration>
DevicePluginAwattar::DevicePluginAwattar() DevicePluginAwattar::DevicePluginAwattar() :
m_device(0),
m_setupRetry(0)
{ {
} }
DeviceManager::HardwareResources DevicePluginAwattar::requiredHardware() const DeviceManager::HardwareResources DevicePluginAwattar::requiredHardware() const
@ -86,17 +87,29 @@ DeviceManager::DeviceSetupStatus DevicePluginAwattar::setupDevice(Device *device
{ {
if (!myDevices().isEmpty()) { if (!myDevices().isEmpty()) {
qCWarning(dcAwattar) << "Only one aWATTar device can be configured."; qCWarning(dcAwattar) << "Only one aWATTar device can be configured.";
return DeviceManager::DeviceSetupStatusFailure;
} }
QString token = device->paramValue("token").toString();
qCDebug(dcAwattar) << "Setup device" << device->params(); qCDebug(dcAwattar) << "Setup device" << device->params();
QNetworkReply *reply = requestPriceData(token); m_device = device;
m_asyncSetup.insert(reply, device); m_token = device->paramValue("token").toString();
m_userUuid = device->paramValue("user uuid").toString();
connectionTest();
return DeviceManager::DeviceSetupStatusAsync; return DeviceManager::DeviceSetupStatusAsync;
} }
void DevicePluginAwattar::postSetupDevice(Device *device)
{
if (device != m_device)
return;
searchHeatPumps();
updateData();
}
void DevicePluginAwattar::startMonitoringAutoDevices() void DevicePluginAwattar::startMonitoringAutoDevices()
{ {
searchHeatPumps(); searchHeatPumps();
@ -110,22 +123,36 @@ void DevicePluginAwattar::deviceRemoved(Device *device)
qCDebug(dcAwattar) << "Delete pump" << pump->address().toString(); qCDebug(dcAwattar) << "Delete pump" << pump->address().toString();
pump->deleteLater(); pump->deleteLater();
} }
m_device = 0;
} }
void DevicePluginAwattar::networkManagerReplyReady(QNetworkReply *reply) void DevicePluginAwattar::networkManagerReplyReady(QNetworkReply *reply)
{ {
int status = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); int status = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
// create user finished if (m_asyncSetup.contains(reply)) {
if (m_asyncSetup.keys().contains(reply)) {
Device *device = m_asyncSetup.take(reply); m_asyncSetup.removeAll(reply);
// check HTTP status code // check HTTP status code
if (status != 200) { if (status != 200) {
qCWarning(dcAwattar) << "Setup reply HTTP error:" << status << reply->errorString(); qCWarning(dcAwattar) << "Setup reply HTTP error:" << status << reply->errorString();
emit deviceSetupFinished(device, DeviceManager::DeviceSetupStatusFailure);
reply->deleteLater(); if (m_setupRetry == 3) {
return; emit deviceSetupFinished(m_device, DeviceManager::DeviceSetupStatusFailure);
m_setupRetry = 0;
reply->deleteLater();
return;
} else {
m_setupRetry++;
reply->deleteLater();
// retry in 1 sec
qCWarning(dcAwattar) << "Retry to connect" << m_setupRetry << "/ 3";
QTimer::singleShot(2000, this, SLOT(connectionTest()));
return;
}
} }
// check JSON file // check JSON file
@ -133,18 +160,16 @@ void DevicePluginAwattar::networkManagerReplyReady(QNetworkReply *reply)
QJsonDocument jsonDoc = QJsonDocument::fromJson(reply->readAll(), &error); QJsonDocument jsonDoc = QJsonDocument::fromJson(reply->readAll(), &error);
if (error.error != QJsonParseError::NoError) { if (error.error != QJsonParseError::NoError) {
qCWarning(dcAwattar) << "Setup reply JSON error:" << error.errorString(); qCWarning(dcAwattar) << "Setup reply JSON error:" << error.errorString();
emit deviceSetupFinished(device, DeviceManager::DeviceSetupStatusFailure); emit deviceSetupFinished(m_device, DeviceManager::DeviceSetupStatusFailure);
reply->deleteLater(); reply->deleteLater();
return; return;
} }
processPriceData(device, jsonDoc.toVariant().toMap(), true); emit deviceSetupFinished(m_device, DeviceManager::DeviceSetupStatusSuccess);
QNetworkReply *userReply = requestUserData(device->paramValue("token").toString(), device->paramValue("user uuid").toString()); } else if (m_updatePrice.contains(reply)) {
m_updateUserData.insert(userReply, device);
} else if (m_updatePrice.keys().contains(reply)) { m_updatePrice.removeAll(reply);
Device *device = m_updatePrice.take(reply);
// check HTTP status code // check HTTP status code
if (status != 200) { if (status != 200) {
@ -162,13 +187,14 @@ void DevicePluginAwattar::networkManagerReplyReady(QNetworkReply *reply)
return; return;
} }
processPriceData(device, jsonDoc.toVariant().toMap()); processPriceData(jsonDoc.toVariant().toMap());
QNetworkReply *userReply = requestUserData(device->paramValue("token").toString(), device->paramValue("user uuid").toString()); // start user data update
m_updateUserData.insert(userReply, device); m_updateUserData.append(requestUserData(m_token, m_userUuid));
} else if (m_updateUserData.keys().contains(reply)) { } else if (m_updateUserData.contains(reply)) {
Device *device = m_updateUserData.take(reply);
m_updateUserData.removeAll(reply);
// check HTTP status code // check HTTP status code
if (status != 200) { if (status != 200) {
@ -186,7 +212,7 @@ void DevicePluginAwattar::networkManagerReplyReady(QNetworkReply *reply)
return; return;
} }
processUserData(device, jsonDoc.toVariant().toMap()); processUserData(jsonDoc.toVariant().toMap());
} else if (m_searchPumpReplies.contains(reply)) { } else if (m_searchPumpReplies.contains(reply)) {
@ -207,48 +233,14 @@ void DevicePluginAwattar::networkManagerReplyReady(QNetworkReply *reply)
void DevicePluginAwattar::guhTimer() void DevicePluginAwattar::guhTimer()
{ {
foreach (Device *device, myDevices()) { updateData();
//qCDebug(dcAwattar) << "Update device" << device->id().toString(); searchHeatPumps();
searchHeatPumps();
updateDevice(device);
}
} }
DeviceManager::DeviceError DevicePluginAwattar::executeAction(Device *device, const Action &action) void DevicePluginAwattar::processPriceData(const QVariantMap &data)
{ {
Q_UNUSED(device) if (!m_device)
Q_UNUSED(action)
// if (action.actionTypeId() == ledPowerActionTypeId) {
// foreach (HeatPump *pump, m_heatPumps) {
// if (!pump->reachable())
// return DeviceManager::DeviceErrorHardwareNotAvailable;
// pump->setLed(action.param("led power").value().toBool());
// }
// } else if (action.actionTypeId() == sgModeActionTypeId) {
// foreach (HeatPump *pump, m_heatPumps) {
// if (!pump->reachable())
// return DeviceManager::DeviceErrorHardwareNotAvailable;
// pump->setSgMode(action.param("sg-mode").value().toInt());
// }
// }
return DeviceManager::DeviceErrorNoError;
}
void DevicePluginAwattar::processPriceData(Device *device, const QVariantMap &data, const bool &fromSetup)
{
if (!data.contains("data")) {
if (fromSetup) {
qCWarning(dcAwattar) << "Device setup failed." << device->id().toString() << "No data element received";
emit deviceSetupFinished(device, DeviceManager::DeviceSetupStatusFailure);
return;
}
qCWarning(dcAwattar) << "Update failed for device" << device->id().toString() << "No data element received";
return; return;
}
QVariantList dataElements = data.value("data").toList(); QVariantList dataElements = data.value("data").toList();
@ -290,9 +282,8 @@ void DevicePluginAwattar::processPriceData(Device *device, const QVariantMap &da
if (price < minPrice) if (price < minPrice)
minPrice = price; minPrice = price;
//qCDebug(dcAwattar) << startTime.toString() << " -> " << endTime.toString(); m_device->setStateValue(currentMarketPriceStateTypeId, currentPrice / 10.0);
device->setStateValue(currentMarketPriceStateTypeId, currentPrice / 10.0); m_device->setStateValue(validUntilStateTypeId, endTime.toLocalTime().toTime_t());
device->setStateValue(validUntilStateTypeId, endTime.toLocalTime().toTime_t());
} }
} }
@ -305,24 +296,17 @@ void DevicePluginAwattar::processPriceData(Device *device, const QVariantMap &da
deviation = qRound(-100 * (averagePrice - currentPrice) / (maxPrice - averagePrice)); deviation = qRound(-100 * (averagePrice - currentPrice) / (maxPrice - averagePrice));
} }
// qCDebug(dcAwattar) << " price :" << currentPrice << "Eur/MWh"; m_device->setStateValue(averagePriceStateTypeId, averagePrice / 10.0);
// qCDebug(dcAwattar) << " average :" << averagePrice << "Eur/MWh"; m_device->setStateValue(lowestPriceStateTypeId, minPrice / 10.0);
// qCDebug(dcAwattar) << " deviation:" << deviation << "%"; m_device->setStateValue(highestPriceStateTypeId, maxPrice / 10.0);
// qCDebug(dcAwattar) << " min :" << minPrice << "Eur/MWh"; m_device->setStateValue(averageDeviationStateTypeId, deviation);
// qCDebug(dcAwattar) << " max :" << maxPrice << "Eur/MWh";
device->setStateValue(averagePriceStateTypeId, averagePrice / 10.0);
device->setStateValue(lowestPriceStateTypeId, minPrice / 10.0);
device->setStateValue(highestPriceStateTypeId, maxPrice / 10.0);
device->setStateValue(averageDeviationStateTypeId, deviation);
if (fromSetup)
emit deviceSetupFinished(device, DeviceManager::DeviceSetupStatusSuccess);
} }
void DevicePluginAwattar::processUserData(Device *device, const QVariantMap &data) void DevicePluginAwattar::processUserData(const QVariantMap &data)
{ {
if (!m_device)
return;
QVariantList dataElements = data.value("data").toList(); QVariantList dataElements = data.value("data").toList();
QDateTime currentTime = QDateTime::currentDateTime(); QDateTime currentTime = QDateTime::currentDateTime();
@ -342,19 +326,19 @@ void DevicePluginAwattar::processUserData(Device *device, const QVariantMap &dat
switch (sgMode) { switch (sgMode) {
case 1: case 1:
device->setStateValue(sgModeStateTypeId, "1 - Off"); m_device->setStateValue(sgModeStateTypeId, "1 - Off");
break; break;
case 2: case 2:
device->setStateValue(sgModeStateTypeId, "2 - Normal"); m_device->setStateValue(sgModeStateTypeId, "2 - Normal");
break; break;
case 3: case 3:
device->setStateValue(sgModeStateTypeId, "3 - High Temperature"); m_device->setStateValue(sgModeStateTypeId, "3 - High Temperature");
break; break;
case 4: case 4:
device->setStateValue(sgModeStateTypeId, "4 - On"); m_device->setStateValue(sgModeStateTypeId, "4 - On");
break; break;
default: default:
device->setStateValue(sgModeStateTypeId, "0 - Invalid"); m_device->setStateValue(sgModeStateTypeId, "0 - Invalid");
continue; continue;
} }
@ -367,8 +351,6 @@ void DevicePluginAwattar::processUserData(Device *device, const QVariantMap &dat
void DevicePluginAwattar::processPumpSearchData(const QByteArray &data) void DevicePluginAwattar::processPumpSearchData(const QByteArray &data)
{ {
//qCDebug(dcAwattar) << "Search result:" << endl << data;
QList<QByteArray> lines = data.split('\n'); QList<QByteArray> lines = data.split('\n');
foreach (const QByteArray &line, lines) { foreach (const QByteArray &line, lines) {
if (line.isEmpty()) if (line.isEmpty())
@ -416,12 +398,12 @@ QNetworkReply *DevicePluginAwattar::requestUserData(const QString &token, const
return networkManagerGet(request); return networkManagerGet(request);
} }
void DevicePluginAwattar::updateDevice(Device *device) void DevicePluginAwattar::updateData()
{ {
QNetworkReply *priceReply = requestPriceData(device->paramValue("token").toString()); m_updatePrice.append(requestPriceData(m_token));
m_updatePrice.insert(priceReply, device);
} }
void DevicePluginAwattar::searchHeatPumps() void DevicePluginAwattar::searchHeatPumps()
{ {
QHostAddress rplAddress = QHostAddress(configuration().paramValue("RPL address").toString()); QHostAddress rplAddress = QHostAddress(configuration().paramValue("RPL address").toString());
@ -449,6 +431,11 @@ bool DevicePluginAwattar::heatPumpExists(const QHostAddress &pumpAddress)
return false; return false;
} }
void DevicePluginAwattar::connectionTest()
{
m_asyncSetup.append(requestUserData(m_token, m_userUuid));
}
void DevicePluginAwattar::onHeatPumpReachableChanged() void DevicePluginAwattar::onHeatPumpReachableChanged()
{ {
HeatPump *pump = static_cast<HeatPump *>(sender()); HeatPump *pump = static_cast<HeatPump *>(sender());

View File

@ -40,6 +40,8 @@ public:
DeviceManager::HardwareResources requiredHardware() const override; DeviceManager::HardwareResources requiredHardware() const override;
DeviceManager::DeviceSetupStatus setupDevice(Device *device) override; DeviceManager::DeviceSetupStatus setupDevice(Device *device) override;
void postSetupDevice(Device *device) override;
void startMonitoringAutoDevices() override; void startMonitoringAutoDevices() override;
void deviceRemoved(Device *device) override; void deviceRemoved(Device *device) override;
@ -47,29 +49,33 @@ public:
void guhTimer() override; void guhTimer() override;
DeviceManager::DeviceError executeAction(Device *device, const Action &action) override;
private: private:
QHash<QNetworkReply *, Device *> m_asyncSetup; QList<QNetworkReply *> m_asyncSetup;
QHash<QNetworkReply *, Device *> m_updatePrice;
QHash<QNetworkReply *, Device *> m_updateUserData;
QList<QNetworkReply *> m_searchPumpReplies; QList<QNetworkReply *> m_searchPumpReplies;
QList<QNetworkReply *> m_updatePrice;
QList<QNetworkReply *> m_updateUserData;
Device *m_device;
QList<HeatPump *> m_heatPumps; QList<HeatPump *> m_heatPumps;
void processPriceData(Device *device, const QVariantMap &data, const bool &fromSetup = false); QString m_token;
void processUserData(Device *device, const QVariantMap &data); QString m_userUuid;
int m_setupRetry;
void processPriceData(const QVariantMap &data);
void processUserData(const QVariantMap &data);
void processPumpSearchData(const QByteArray &data); void processPumpSearchData(const QByteArray &data);
QNetworkReply *requestPriceData(const QString& token); QNetworkReply *requestPriceData(const QString& token);
QNetworkReply *requestUserData(const QString& token, const QString &userId); QNetworkReply *requestUserData(const QString& token, const QString &userId);
void updateDevice(Device *device); void updateData();
void searchHeatPumps(); void searchHeatPumps();
bool heatPumpExists(const QHostAddress &pumpAddress); bool heatPumpExists(const QHostAddress &pumpAddress);
private slots: private slots:
void connectionTest();
void onHeatPumpReachableChanged(); void onHeatPumpReachableChanged();
}; };