From 3b0cd827fcd18193b29842a2d2700288d09cf184 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Simon=20St=C3=BCrz?= Date: Tue, 28 Sep 2021 12:21:58 +0200 Subject: [PATCH] Rework Keba commands and connection status --- keba/integrationpluginkeba.cpp | 95 +++++++++++++------- keba/integrationpluginkeba.h | 3 +- keba/integrationpluginkeba.json | 6 +- keba/kecontact.cpp | 153 ++++++++++++++++++++++++++------ keba/kecontact.h | 21 +++-- keba/kecontactdatalayer.cpp | 15 +++- keba/kecontactdatalayer.h | 6 +- 7 files changed, 226 insertions(+), 73 deletions(-) diff --git a/keba/integrationpluginkeba.cpp b/keba/integrationpluginkeba.cpp index 6d1079b9..f608b6f0 100644 --- a/keba/integrationpluginkeba.cpp +++ b/keba/integrationpluginkeba.cpp @@ -49,7 +49,7 @@ void IntegrationPluginKeba::init() void IntegrationPluginKeba::discoverThings(ThingDiscoveryInfo *info) { if (info->thingClassId() == wallboxThingClassId) { - qCDebug(dcKebaKeContact()) << "Discovering Keba Wallbox"; + qCDebug(dcKebaKeContact()) << "Discovering Keba Wallbox..."; NetworkDeviceDiscoveryReply *discoveryReply = hardwareManager()->networkDeviceDiscovery()->discover(); connect(discoveryReply, &NetworkDeviceDiscoveryReply::finished, this, [=](){ ThingDescriptors descriptors; @@ -59,9 +59,9 @@ void IntegrationPluginKeba::discoverThings(ThingDiscoveryInfo *info) continue; qCDebug(dcKebaKeContact()) << " - Keba Wallbox" << networkDeviceInfo; - QString title = "Wallbox "; + QString title = "Keba Wallbox "; if (networkDeviceInfo.hostName().isEmpty()) { - title += networkDeviceInfo.address().toString(); + title += "(" + networkDeviceInfo.address().toString() + ")"; } else { title += networkDeviceInfo.hostName() + " (" + networkDeviceInfo.address().toString() + ")"; } @@ -92,7 +92,7 @@ void IntegrationPluginKeba::discoverThings(ThingDiscoveryInfo *info) info->finish(Thing::ThingErrorNoError); }); } else { - qCWarning(dcKebaKeContact()) << "Discover device, unhandled device class" << info->thingClassId(); + qCWarning(dcKebaKeContact()) << "Could not discover things because of unhandled thing class id" << info->thingClassId().toString(); info->finish(Thing::ThingErrorThingClassNotFound); } } @@ -100,24 +100,23 @@ void IntegrationPluginKeba::discoverThings(ThingDiscoveryInfo *info) void IntegrationPluginKeba::setupThing(ThingSetupInfo *info) { Thing *thing = info->thing(); - - qCDebug(dcKebaKeContact()) << "Setting up a new thing:" << thing->name() << thing->params(); + qCDebug(dcKebaKeContact()) << "Setting up" << thing->name() << thing->params(); if (thing->thingClassId() == wallboxThingClassId) { - - if(!m_kebaData){ - qCDebug(dcKebaKeContact()) << "Creating new Keba data layer"; - m_kebaData = new KeContactDataLayer(this); - if (!m_kebaData->init()) { - m_kebaData->deleteLater(); - m_kebaData = nullptr; - connect(info, &ThingSetupInfo::aborted, m_kebaData, &KeContactDataLayer::deleteLater); // Clean up if the setup fails + if (!m_kebaDataLayer){ + qCDebug(dcKebaKeContact()) << "Creating new Keba data layer..."; + m_kebaDataLayer= new KeContactDataLayer(this); + if (!m_kebaDataLayer->init()) { + m_kebaDataLayer->deleteLater(); + m_kebaDataLayer = nullptr; + connect(info, &ThingSetupInfo::aborted, m_kebaDataLayer, &KeContactDataLayer::deleteLater); // Clean up if the setup fails return info->finish(Thing::ThingErrorHardwareNotAvailable, QT_TR_NOOP("Error opening network port.")); } } QHostAddress address = QHostAddress(thing->paramValue(wallboxThingIpAddressParamTypeId).toString()); - KeContact *keba = new KeContact(address, m_kebaData, m_kebaData); + + KeContact *keba = new KeContact(address, m_kebaDataLayer, this); connect(keba, &KeContact::reachableChanged, this, &IntegrationPluginKeba::onConnectionChanged); connect(keba, &KeContact::commandExecuted, this, &IntegrationPluginKeba::onCommandExecuted); connect(keba, &KeContact::reportTwoReceived, this, &IntegrationPluginKeba::onReportTwoReceived); @@ -125,7 +124,6 @@ void IntegrationPluginKeba::setupThing(ThingSetupInfo *info) connect(keba, &KeContact::report1XXReceived, this, &IntegrationPluginKeba::onReport1XXReceived); connect(keba, &KeContact::broadcastReceived, this, &IntegrationPluginKeba::onBroadcastReceived); - keba->getReport1(); connect(keba, &KeContact::reportOneReceived, info, [info, this, keba] (const KeContact::ReportOne &report) { Thing *thing = info->thing(); @@ -145,12 +143,16 @@ void IntegrationPluginKeba::setupThing(ThingSetupInfo *info) m_kebaDevices.insert(thing->id(), keba); info->finish(Thing::ThingErrorNoError); }); + + keba->getReport1(); + connect(info, &ThingSetupInfo::aborted, keba, &KeContact::deleteLater); // Clean up if the setup fails connect(keba, &KeContact::destroyed, this, [thing, this]{ m_kebaDevices.remove(thing->id()); }); + } else { - qCWarning(dcKebaKeContact()) << "setupDevice, unhandled device class" << thing->thingClass(); + qCWarning(dcKebaKeContact()) << "Could not setup thing: unhandled device class" << thing->thingClass(); info->finish(Thing::ThingErrorThingClassNotFound); } } @@ -162,7 +164,7 @@ void IntegrationPluginKeba::postSetupThing(Thing *thing) qCWarning(dcKebaKeContact()) << "Thing class id not supported" << thing->thingClassId(); return; } - thing->setStateValue(wallboxConnectedStateTypeId, true); + KeContact *keba = m_kebaDevices.value(thing->id()); if (!keba) { qCWarning(dcKebaKeContact()) << "No Keba connection found for this thing"; @@ -172,14 +174,14 @@ void IntegrationPluginKeba::postSetupThing(Thing *thing) keba->getReport3(); } - if (thing->paramValue(wallboxThingMacAddressParamTypeId).toString().isEmpty()) { + // Try to find the mac address in case the user added the ip manually + if (thing->paramValue(wallboxThingMacAddressParamTypeId).toString().isEmpty() || thing->paramValue(wallboxThingMacAddressParamTypeId).toString() == "00:00:00:00:00:00") { searchNetworkDevices(); } if (!m_updateTimer) { m_updateTimer = hardwareManager()->pluginTimerManager()->registerTimer(60); - connect(m_updateTimer, &PluginTimer::timeout, this, [this] { - + connect(m_updateTimer, &PluginTimer::timeout, this, [this]() { foreach (Thing *thing, myThings().filterByThingClassId(wallboxThingClassId)) { KeContact *keba = m_kebaDevices.value(thing->id()); if (!keba) { @@ -193,13 +195,29 @@ void IntegrationPluginKeba::postSetupThing(Thing *thing) } } }); + + m_updateTimer->start(); } if (!m_reconnectTimer) { m_reconnectTimer = hardwareManager()->pluginTimerManager()->registerTimer(60*5); connect(m_reconnectTimer, &PluginTimer::timeout, this, [this] { - searchNetworkDevices(); + // Only search for new network devices if there is one keba which is not connected + foreach (Thing *thing, myThings().filterByThingClassId(wallboxThingClassId)) { + KeContact *keba = m_kebaDevices.value(thing->id()); + if (!keba) { + qCWarning(dcKebaKeContact()) << "No Keba connection found for" << thing->name(); + continue; + } + + if (!keba->reachable()) { + searchNetworkDevices(); + return; + } + } }); + + m_reconnectTimer->start(); } } @@ -213,14 +231,19 @@ void IntegrationPluginKeba::thingRemoved(Thing *thing) if (myThings().empty()) { qCDebug(dcKebaKeContact()) << "Closing UDP Ports"; - m_kebaData->deleteLater(); - m_kebaData = nullptr; + m_kebaDataLayer->deleteLater(); + m_kebaDataLayer= nullptr; - qCDebug(dcKebaKeContact()) << "Stopping plugin timers"; - hardwareManager()->pluginTimerManager()->unregisterTimer(m_reconnectTimer); - m_reconnectTimer = nullptr; - hardwareManager()->pluginTimerManager()->unregisterTimer(m_updateTimer); - m_updateTimer = nullptr; + qCDebug(dcKebaKeContact()) << "Stopping plugin timers ..."; + if (m_reconnectTimer) { + hardwareManager()->pluginTimerManager()->unregisterTimer(m_reconnectTimer); + m_reconnectTimer = nullptr; + } + + if (m_updateTimer) { + hardwareManager()->pluginTimerManager()->unregisterTimer(m_updateTimer); + m_updateTimer = nullptr; + } } } @@ -294,6 +317,7 @@ void IntegrationPluginKeba::searchNetworkDevices() existingThing->setParamValue(wallboxThingMacAddressParamTypeId, networkDeviceInfo.macAddress()); } } else if (existingThing->paramValue(wallboxThingMacAddressParamTypeId).toString() == networkDeviceInfo.macAddress()) { + // We found the existing keba thing, lets check if the ip has changed if (existingThing->paramValue(wallboxThingIpAddressParamTypeId).toString() != networkDeviceInfo.address().toString()) { qCDebug(dcKebaKeContact()) << "Keba Wallbox IP Address has changed, from" << existingThing->paramValue(wallboxThingIpAddressParamTypeId).toString() << "to" << networkDeviceInfo.address().toString(); existingThing->setParamValue(wallboxThingIpAddressParamTypeId, networkDeviceInfo.address().toString()); @@ -321,6 +345,7 @@ void IntegrationPluginKeba::onConnectionChanged(bool status) qCWarning(dcKebaKeContact()) << "On connection changed: missing device object"; return; } + thing->setStateValue(wallboxConnectedStateTypeId, status); if (!status) { searchNetworkDevices(); @@ -339,6 +364,7 @@ void IntegrationPluginKeba::onCommandExecuted(QUuid requestId, bool success) qCWarning(dcKebaKeContact()) << "On command executed: missing device object"; return; } + ThingActionInfo *info = m_asyncActions.take(requestId); if (success) { info->finish(Thing::ThingErrorNoError); @@ -536,7 +562,7 @@ void IntegrationPluginKeba::executeAction(ThingActionInfo *info) QUuid requestId; if(action.actionTypeId() == wallboxMaxChargingCurrentActionTypeId){ - int milliAmpere = action.param(wallboxMaxChargingCurrentActionMaxChargingCurrentParamTypeId).value().toDouble()*1000; + int milliAmpere = action.param(wallboxMaxChargingCurrentActionMaxChargingCurrentParamTypeId).value().toDouble() * 1000; requestId = keba->setMaxAmpere(milliAmpere); } else if(action.actionTypeId() == wallboxPowerActionTypeId){ @@ -558,8 +584,15 @@ void IntegrationPluginKeba::executeAction(ThingActionInfo *info) qCWarning(dcKebaKeContact()) << "Unhandled ActionTypeId:" << action.actionTypeId(); return info->finish(Thing::ThingErrorActionTypeNotFound); } + + // If the keba returns an invalid uuid, something went wrong + if (requestId.isNull()) { + info->finish(Thing::ThingErrorHardwareFailure); + return; + } + m_asyncActions.insert(requestId, info); - connect(info, &ThingActionInfo::aborted, this, [requestId, this]{m_asyncActions.remove(requestId);}); + connect(info, &ThingActionInfo::aborted, this, [requestId, this]{ m_asyncActions.remove(requestId); }); } else { qCWarning(dcKebaKeContact()) << "Execute action, unhandled device class" << thing->thingClass(); info->finish(Thing::ThingErrorThingClassNotFound); diff --git a/keba/integrationpluginkeba.h b/keba/integrationpluginkeba.h index 5543270e..03abbcc6 100644 --- a/keba/integrationpluginkeba.h +++ b/keba/integrationpluginkeba.h @@ -52,6 +52,7 @@ public: explicit IntegrationPluginKeba(); void init() override; + void discoverThings(ThingDiscoveryInfo *info) override; void setupThing(ThingSetupInfo *info) override; @@ -64,7 +65,7 @@ private: PluginTimer *m_updateTimer = nullptr; PluginTimer *m_reconnectTimer = nullptr; - KeContactDataLayer *m_kebaData = nullptr; + KeContactDataLayer *m_kebaDataLayer = nullptr; QHash m_kebaDevices; QHash m_lastSessionId; diff --git a/keba/integrationpluginkeba.json b/keba/integrationpluginkeba.json index 4875a3cc..d3d23ce9 100644 --- a/keba/integrationpluginkeba.json +++ b/keba/integrationpluginkeba.json @@ -143,9 +143,9 @@ "displayNameAction": "Set maximal charging current", "type": "double", "unit": "Ampere", - "defaultValue": 6.00, - "minValue": 6.00, - "maxValue": 63.00, + "defaultValue": 6.0, + "minValue": 6.0, + "maxValue": 32.0, "writable": true }, { diff --git a/keba/kecontact.cpp b/keba/kecontact.cpp index ec02fac0..525c28b8 100644 --- a/keba/kecontact.cpp +++ b/keba/kecontact.cpp @@ -1,6 +1,6 @@ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * -* Copyright 2013 - 2020, nymea GmbH +* Copyright 2013 - 2021, nymea GmbH * Contact: contact@nymea.io * * This file is part of nymea. @@ -33,7 +33,6 @@ #include - KeContact::KeContact(const QHostAddress &address, KeContactDataLayer *dataLayer, QObject *parent) : QObject(parent), m_dataLayer(dataLayer), @@ -43,8 +42,9 @@ KeContact::KeContact(const QHostAddress &address, KeContactDataLayer *dataLayer, m_requestTimeoutTimer = new QTimer(this); m_requestTimeoutTimer->setSingleShot(true); connect(m_requestTimeoutTimer, &QTimer::timeout, this, [this] { - //This timer will be started when a request is sent and stopped or resetted when a response has been received - emit reachableChanged(false); + // This timer will be started when a request is sent and stopped or resetted when a response has been received + setReachable(false); + //Try to send the next command handleNextCommandInQueue(); m_deviceBlocked = false; @@ -58,16 +58,22 @@ KeContact::~KeContact() qCDebug(dcKebaKeContact()) << "Deleting KeContact connection for address" << m_address; } -QHostAddress KeContact::address() +QHostAddress KeContact::address() const { return m_address; } QUuid KeContact::start(const QByteArray &rfidToken, const QByteArray &rfidClassifier) { + if (!m_dataLayer) { + qCWarning(dcKebaKeContact()) << "UDP socket not initialized"; + setReachable(false); + return QUuid(); + } + QUuid requestId = QUuid::createUuid(); m_pendingRequests.append(requestId); - QByteArray datagram = "start "+rfidToken + " " + rfidClassifier; + QByteArray datagram = "start " + rfidToken + " " + rfidClassifier; qCDebug(dcKebaKeContact()) << "Datagram : " << datagram; sendCommand(datagram, requestId);; return requestId; @@ -75,9 +81,15 @@ QUuid KeContact::start(const QByteArray &rfidToken, const QByteArray &rfidClassi QUuid KeContact::stop(const QByteArray &rfidToken) { + if (!m_dataLayer) { + qCWarning(dcKebaKeContact()) << "UDP socket not initialized"; + setReachable(false); + return QUuid(); + } + QUuid requestId = QUuid::createUuid(); m_pendingRequests.append(requestId); - QByteArray datagram = "stop "+rfidToken; + QByteArray datagram = "stop " + rfidToken; qCDebug(dcKebaKeContact()) << "Datagram : " << datagram; sendCommand(datagram, requestId); return requestId; @@ -85,10 +97,17 @@ QUuid KeContact::stop(const QByteArray &rfidToken) void KeContact::setAddress(const QHostAddress &address) { - qCDebug(dcKebaKeContact()) << "Updating Keba connection address" << address.toString(); + if (m_address == address) + return; + + qCDebug(dcKebaKeContact()) << "Updating Keba connection address from" << m_address.toString() << "to" << address.toString(); m_address = address; } +bool KeContact::reachable() const +{ + return m_reachable; +} void KeContact::sendCommand(const QByteArray &command, const QUuid &requestId) { @@ -98,6 +117,7 @@ void KeContact::sendCommand(const QByteArray &command, const QUuid &requestId) emit commandExecuted(requestId, false); } }); + sendCommand(command); } @@ -105,16 +125,16 @@ void KeContact::sendCommand(const QByteArray &command) { if (!m_dataLayer) { qCWarning(dcKebaKeContact()) << "UDP socket not initialized"; - emit reachableChanged(false); + setReachable(false); return; } - if(m_deviceBlocked) { - //add command to queue + if (m_deviceBlocked) { + // Add command to queue m_commandList.append(command); } else { qCDebug(dcKebaKeContact()) << "Writing datagram" << command << m_address; - m_dataLayer->write( m_address, command); + m_dataLayer->write(m_address, command); m_requestTimeoutTimer->start(5000); m_deviceBlocked = true; } @@ -124,13 +144,11 @@ void KeContact::handleNextCommandInQueue() { if (!m_dataLayer) { qCWarning(dcKebaKeContact()) << "Data layer not initialized"; - if (m_reachable == true) { - m_reachable = false; - emit reachableChanged(false); - } + setReachable(false); return; } - qCDebug(dcKebaKeContact()) << "Handle Command Queue- Pending commands" << m_commandList.length() << "Pending requestIds" << m_pendingRequests.length(); + + qCDebug(dcKebaKeContact()) << "Handle Command Queue - Pending commands" << m_commandList.length() << "Pending requestIds" << m_pendingRequests.length(); if (!m_commandList.isEmpty()) { QByteArray command = m_commandList.takeFirst(); qCDebug(dcKebaKeContact()) << "Writing datagram" << command << m_address; @@ -139,18 +157,39 @@ void KeContact::handleNextCommandInQueue() } } +void KeContact::setReachable(bool reachable) +{ + if (m_reachable == reachable) + return; + + if (reachable) { + qCDebug(dcKebaKeContact()) << "The keba wallbox on" << m_address.toString() << "is now reachable again."; + } else { + qCWarning(dcKebaKeContact()) << "The keba wallbox on" << m_address.toString() << "is not reachable any more."; + } + + m_reachable = reachable; + emit reachableChanged(m_reachable); +} QUuid KeContact::enableOutput(bool state) { + if (!m_dataLayer) { + qCWarning(dcKebaKeContact()) << "UDP socket not initialized"; + setReachable(false); + return QUuid(); + } + QUuid requestId = QUuid::createUuid(); m_pendingRequests.append(requestId); // Print information that we are executing now the update action; QByteArray datagram; - if(state){ + if (state){ datagram.append("ena 1"); } else{ datagram.append("ena 0"); } + qCDebug(dcKebaKeContact()) << "Enable output, command:" << datagram; sendCommand(datagram, requestId); return requestId; @@ -158,16 +197,23 @@ QUuid KeContact::enableOutput(bool state) QUuid KeContact::setMaxAmpere(int milliAmpere) { + if (!m_dataLayer) { + qCWarning(dcKebaKeContact()) << "UDP socket not initialized"; + setReachable(false); + return QUuid(); + } + if (milliAmpere < 6000 || milliAmpere > 63000) { qCWarning(dcKebaKeContact()) << "KeContact: Set max ampere, mA out of range [6000, 63000]" << milliAmpere; - return ""; + return QUuid(); } + QUuid requestId = QUuid::createUuid(); m_pendingRequests.append(requestId); // Print information that we are executing now the update action qCDebug(dcKebaKeContact()) << "Update max current to : " << milliAmpere; - QByteArray data; - data.append("curr " + QVariant(milliAmpere).toByteArray()); + QString commandLine = QString("currtime %1 %2").arg(milliAmpere, 1); + QByteArray data = commandLine.toUtf8(); qCDebug(dcKebaKeContact()) << "Set max. ampere, command: " << data; sendCommand(data, requestId); return requestId; @@ -175,6 +221,12 @@ QUuid KeContact::setMaxAmpere(int milliAmpere) QUuid KeContact::displayMessage(const QByteArray &message) { + if (!m_dataLayer) { + qCWarning(dcKebaKeContact()) << "UDP socket not initialized"; + setReachable(false); + return QUuid(); + } + /* Text shown on the display. Maximum 23 ASCII characters can be used. 0 .. 23 characters ~ == Σ $ == blank @@ -197,6 +249,12 @@ QUuid KeContact::displayMessage(const QByteArray &message) QUuid KeContact::chargeWithEnergyLimit(double energy) { + if (!m_dataLayer) { + qCWarning(dcKebaKeContact()) << "UDP socket not initialized"; + setReachable(false); + return QUuid(); + } + QUuid requestId = QUuid::createUuid(); m_pendingRequests.append(requestId); @@ -209,6 +267,12 @@ QUuid KeContact::chargeWithEnergyLimit(double energy) QUuid KeContact::setFailsafe(int timeout, int current, bool save) { + if (!m_dataLayer) { + qCWarning(dcKebaKeContact()) << "UDP socket not initialized"; + setReachable(false); + return QUuid(); + } + QUuid requestId = QUuid::createUuid(); m_pendingRequests.append(requestId); @@ -222,7 +286,6 @@ QUuid KeContact::setFailsafe(int timeout, int current, bool save) return requestId; } - void KeContact::getDeviceInformation() { QByteArray data; @@ -253,6 +316,12 @@ void KeContact::getReport1XX(int reportNumber) QUuid KeContact::setOutputX2(bool state) { + if (!m_dataLayer) { + qCWarning(dcKebaKeContact()) << "UDP socket not initialized"; + setReachable(false); + return QUuid(); + } + QUuid requestId = QUuid::createUuid(); m_pendingRequests.append(requestId); QByteArray data; @@ -272,6 +341,12 @@ void KeContact::getReport(int reportNumber) QUuid KeContact::unlockCharger() { + if (!m_dataLayer) { + qCWarning(dcKebaKeContact()) << "UDP socket not initialized"; + setReachable(false); + return QUuid(); + } + QUuid requestId = QUuid::createUuid(); m_pendingRequests.append(requestId); QByteArray data; @@ -283,11 +358,14 @@ QUuid KeContact::unlockCharger() void KeContact::onReceivedDatagram(const QHostAddress &address, const QByteArray &datagram) { + // Make sure the datagram is for this keba if (address != m_address) { return; } - if(datagram.contains("TCH-OK")){ + if (datagram.contains("TCH-OK")){ + // We received valid data from the address over the data link, so the wallbox must be reachable + setReachable(true); //Command response has been received, now send the next command m_deviceBlocked = false; @@ -304,7 +382,10 @@ void KeContact::onReceivedDatagram(const QHostAddress &address, const QByteArray } else { //Probably the response has taken too long and the requestId has been already removed } - } else if(datagram.left(8).contains("Firmware")){ + + } else if (datagram.left(8).contains("Firmware")){ + // We received valid data from the address over the data link, so the wallbox must be reachable + setReachable(true); //Command response has been received, now send the next command m_deviceBlocked = false; @@ -328,13 +409,17 @@ void KeContact::onReceivedDatagram(const QHostAddress &address, const QByteArray QJsonDocument jsonDoc = QJsonDocument::fromJson(datagram, &error); if (error.error != QJsonParseError::NoError) { qCWarning(dcKebaKeContact()) << "Failed to parse JSON data" << datagram << ":" << error.errorString(); + return; } QVariantMap data = jsonDoc.toVariant().toMap(); - if(data.contains("ID")) { + if (data.contains("ID")) { int id = data.value("ID").toInt(); if (id == 1) { + // We received valid data from the address over the data link, so the wallbox must be reachable + setReachable(true); + ReportOne reportOne; qCDebug(dcKebaKeContact()) << "Report 1 received"; reportOne.product = data.value("Product").toString(); @@ -357,6 +442,8 @@ void KeContact::onReceivedDatagram(const QHostAddress &address, const QByteArray emit reportOneReceived(reportOne); } else if (id == 2) { + // We received valid data from the address over the data link, so the wallbox must be reachable + setReachable(true); ReportTwo reportTwo; qCDebug(dcKebaKeContact()) << "Report 2 received"; @@ -384,6 +471,8 @@ void KeContact::onReceivedDatagram(const QHostAddress &address, const QByteArray emit reportTwoReceived(reportTwo); } else if (id == 3) { + // We received valid data from the address over the data link, so the wallbox must be reachable + setReachable(true); ReportThree reportThree; qCDebug(dcKebaKeContact()) << "Report 3 received"; @@ -401,6 +490,8 @@ void KeContact::onReceivedDatagram(const QHostAddress &address, const QByteArray reportThree.seconds = data.value("Sec").toInt(); emit reportThreeReceived(reportThree); } else if (id >= 100) { + // We received valid data from the address over the data link, so the wallbox must be reachable + setReachable(true); Report1XX report; qCDebug(dcKebaKeContact()) << "Report" << id << "received"; @@ -419,21 +510,33 @@ void KeContact::onReceivedDatagram(const QHostAddress &address, const QByteArray } } else { if (data.contains("State")) { + // We received valid data from the address over the data link, so the wallbox must be reachable + setReachable(true); emit broadcastReceived(BroadcastType::BroadcastTypeState, data.value("State")); } if (data.contains("Plug")) { + // We received valid data from the address over the data link, so the wallbox must be reachable + setReachable(true); emit broadcastReceived(BroadcastType::BroadcastTypePlug, data.value("Plug")); } if (data.contains("Input")) { + // We received valid data from the address over the data link, so the wallbox must be reachable + setReachable(true); emit broadcastReceived(BroadcastType::BroadcastTypeInput, data.value("Input")); } if (data.contains("Enable sys")) { + // We received valid data from the address over the data link, so the wallbox must be reachable + setReachable(true); emit broadcastReceived(BroadcastType::BroadcastTypeEnableSys, data.value("Enable sys")); } if (data.contains("Max curr")) { + // We received valid data from the address over the data link, so the wallbox must be reachable + setReachable(true); emit broadcastReceived(BroadcastType::BroadcastTypeMaxCurr, data.value("Max curr")); } if (data.contains("E pres")) { + // We received valid data from the address over the data link, so the wallbox must be reachable + setReachable(true); emit broadcastReceived(BroadcastType::BroadcastTypeEPres, data.value("E pres")); } } diff --git a/keba/kecontact.h b/keba/kecontact.h index af04d23f..3622130a 100644 --- a/keba/kecontact.h +++ b/keba/kecontact.h @@ -1,6 +1,6 @@ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * -* Copyright 2013 - 2020, nymea GmbH +* Copyright 2013 - 2021, nymea GmbH * Contact: contact@nymea.io * * This file is part of nymea. @@ -44,10 +44,6 @@ class KeContact : public QObject { Q_OBJECT public: - explicit KeContact(const QHostAddress &address, KeContactDataLayer *dataLayer, QObject *parent = nullptr); - ~KeContact(); - bool init(); - enum State { StateStarting = 0, StateNotReady, @@ -136,10 +132,14 @@ public: int seconds; // current time when the report was generated }; - QHostAddress address(); + + explicit KeContact(const QHostAddress &address, KeContactDataLayer *dataLayer, QObject *parent = nullptr); + ~KeContact(); + + QHostAddress address() const; void setAddress(const QHostAddress &address); - bool reachable(); + bool reachable() const; QUuid start(const QByteArray &rfidToken, const QByteArray &rfidClassifier); // Command “start” QUuid stop(const QByteArray &rfidToken); // Command “stop” @@ -161,7 +161,7 @@ public: QUuid setOutputX2(bool state); // Command “output” private: - KeContactDataLayer *m_dataLayer; + KeContactDataLayer *m_dataLayer = nullptr; bool m_reachable = false; QHostAddress m_address; @@ -169,7 +169,7 @@ private: bool m_deviceBlocked = false; QTimer *m_requestTimeoutTimer = nullptr; - int m_serialNumber; + int m_serialNumber = 0; QList m_pendingRequests; void getReport(int reportNumber); @@ -177,6 +177,8 @@ private: void sendCommand(const QByteArray &command); void handleNextCommandInQueue(); + void setReachable(bool reachable); + signals: void reachableChanged(bool status); void commandExecuted(QUuid requestId, bool success); @@ -189,6 +191,7 @@ signals: private slots: void onReceivedDatagram(const QHostAddress &address, const QByteArray &datagram); + }; #endif // KECONTACT_H diff --git a/keba/kecontactdatalayer.cpp b/keba/kecontactdatalayer.cpp index e1f3a9ec..24c4c7ba 100644 --- a/keba/kecontactdatalayer.cpp +++ b/keba/kecontactdatalayer.cpp @@ -1,6 +1,6 @@ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * -* Copyright 2013 - 2020, nymea GmbH +* Copyright 2013 - 2021, nymea GmbH * Contact: contact@nymea.io * * This file is part of nymea. @@ -47,13 +47,23 @@ KeContactDataLayer::~KeContactDataLayer() bool KeContactDataLayer::init() { + m_udpSocket->close(); + m_initialized = false; + if (!m_udpSocket->bind(QHostAddress::AnyIPv4, m_port, QAbstractSocket::ShareAddress)) { qCWarning(dcKebaKeContact()) << "KeContactDataLayer: Cannot bind to port" << m_port; return false; } + + m_initialized = true; return true; } +bool KeContactDataLayer::initialized() const +{ + return m_initialized; +} + void KeContactDataLayer::write(const QHostAddress &address, const QByteArray &data) { m_udpSocket->writeDatagram(data, address, m_port); @@ -68,10 +78,9 @@ void KeContactDataLayer::readPendingDatagrams() quint16 senderPort; while (socket->hasPendingDatagrams()) { - datagram.resize(socket->pendingDatagramSize()); socket->readDatagram(datagram.data(), datagram.size(), &senderAddress, &senderPort); - qCDebug(dcKebaKeContact()) << "KeContactDataLayer: Data received" << datagram << senderAddress; + qCDebug(dcKebaKeContact()) << "KeContactDataLayer: Data received from" << senderAddress << datagram ; emit datagramReceived(senderAddress, datagram); } } diff --git a/keba/kecontactdatalayer.h b/keba/kecontactdatalayer.h index b938bcd1..e188d820 100644 --- a/keba/kecontactdatalayer.h +++ b/keba/kecontactdatalayer.h @@ -1,6 +1,6 @@ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * -* Copyright 2013 - 2020, nymea GmbH +* Copyright 2013 - 2021, nymea GmbH * Contact: contact@nymea.io * * This file is part of nymea. @@ -40,11 +40,14 @@ class KeContactDataLayer : public QObject public: explicit KeContactDataLayer(QObject *parent = nullptr); ~KeContactDataLayer(); + bool init(); + bool initialized() const; void write(const QHostAddress &address, const QByteArray &data); private: + bool m_initialized = false; int m_port = 7090; QUdpSocket *m_udpSocket = nullptr; @@ -55,6 +58,7 @@ private slots: void readPendingDatagrams(); void onSocketError(QAbstractSocket::SocketError error); void onSocketStateChanged(QAbstractSocket::SocketState socketState); + }; #endif // KECONTACTDATALAYER_H