diff --git a/keba/integrationpluginkeba.cpp b/keba/integrationpluginkeba.cpp index 6d1079b9..b9700134 100644 --- a/keba/integrationpluginkeba.cpp +++ b/keba/integrationpluginkeba.cpp @@ -49,19 +49,19 @@ void IntegrationPluginKeba::init() void IntegrationPluginKeba::discoverThings(ThingDiscoveryInfo *info) { if (info->thingClassId() == wallboxThingClassId) { - qCDebug(dcKebaKeContact()) << "Discovering Keba Wallbox"; + qCDebug(dcKeba()) << "Discovering Keba Wallbox..."; NetworkDeviceDiscoveryReply *discoveryReply = hardwareManager()->networkDeviceDiscovery()->discover(); connect(discoveryReply, &NetworkDeviceDiscoveryReply::finished, this, [=](){ ThingDescriptors descriptors; - qCDebug(dcKebaKeContact()) << "Discovery finished. Found" << discoveryReply->networkDeviceInfos().count() << "devices"; + qCDebug(dcKeba()) << "Discovery finished. Found" << discoveryReply->networkDeviceInfos().count() << "devices"; foreach (const NetworkDeviceInfo &networkDeviceInfo, discoveryReply->networkDeviceInfos()) { if (!networkDeviceInfo.macAddressManufacturer().contains("keba", Qt::CaseSensitivity::CaseInsensitive)) continue; - qCDebug(dcKebaKeContact()) << " - Keba Wallbox" << networkDeviceInfo; - QString title = "Wallbox "; + qCDebug(dcKeba()) << " - Keba Wallbox" << networkDeviceInfo; + QString title = "Keba Wallbox "; if (networkDeviceInfo.hostName().isEmpty()) { - title += networkDeviceInfo.address().toString(); + title += "(" + networkDeviceInfo.address().toString() + ")"; } else { title += networkDeviceInfo.hostName() + " (" + networkDeviceInfo.address().toString() + ")"; } @@ -78,7 +78,7 @@ void IntegrationPluginKeba::discoverThings(ThingDiscoveryInfo *info) // Check if we already have set up this device Things existingThings = myThings().filterByParam(wallboxThingMacAddressParamTypeId, networkDeviceInfo.macAddress()); if (existingThings.count() == 1) { - qCDebug(dcKebaKeContact()) << "This wallbox already exists in the system!" << networkDeviceInfo; + qCDebug(dcKeba()) << "This wallbox already exists in the system!" << networkDeviceInfo; descriptor.setThingId(existingThings.first()->id()); } @@ -92,7 +92,7 @@ void IntegrationPluginKeba::discoverThings(ThingDiscoveryInfo *info) info->finish(Thing::ThingErrorNoError); }); } else { - qCWarning(dcKebaKeContact()) << "Discover device, unhandled device class" << info->thingClassId(); + qCWarning(dcKeba()) << "Could not discover things because of unhandled thing class id" << info->thingClassId().toString(); info->finish(Thing::ThingErrorThingClassNotFound); } } @@ -100,24 +100,34 @@ 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(); - 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 + // Handle reconfigure + if (myThings().contains(thing)) { + KeContact *keba = m_kebaDevices.take(thing->id()); + if (keba) { + qCDebug(dcKeba()) << "Reconfigure" << thing->name() << thing->params(); + delete keba; + // Now continue with the normal setup + } + } + + qCDebug(dcKeba()) << "Setting up" << thing->name() << thing->params(); + + if (!m_kebaDataLayer){ + qCDebug(dcKeba()) << "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,16 +135,15 @@ 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(); - qCDebug(dcKebaKeContact()) << "Report one received for" << thing->name(); - qCDebug(dcKebaKeContact()) << " - Firmware" << report.firmware; - qCDebug(dcKebaKeContact()) << " - Serial" << report.serialNumber; - qCDebug(dcKebaKeContact()) << " - Product" << report.product; - qCDebug(dcKebaKeContact()) << " - Uptime" << report.seconds/60 << "[min]"; - qCDebug(dcKebaKeContact()) << " - Com Module" << report.comModule; + qCDebug(dcKeba()) << "Report one received for" << thing->name(); + qCDebug(dcKeba()) << " - Firmware" << report.firmware; + qCDebug(dcKeba()) << " - Serial" << report.serialNumber; + qCDebug(dcKeba()) << " - Product" << report.product; + qCDebug(dcKeba()) << " - Uptime" << report.seconds/60 << "[min]"; + qCDebug(dcKeba()) << " - Com Module" << report.comModule; thing->setStateValue(wallboxConnectedStateTypeId, true); thing->setStateValue(wallboxFirmwareStateTypeId, report.firmware); @@ -145,45 +154,49 @@ 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(dcKeba()) << "Could not setup thing: unhandled device class" << thing->thingClass(); info->finish(Thing::ThingErrorThingClassNotFound); } } void IntegrationPluginKeba::postSetupThing(Thing *thing) { - qCDebug(dcKebaKeContact()) << "Post setup" << thing->name(); + qCDebug(dcKeba()) << "Post setup" << thing->name(); if (thing->thingClassId() != wallboxThingClassId) { - qCWarning(dcKebaKeContact()) << "Thing class id not supported" << thing->thingClassId(); + qCWarning(dcKeba()) << "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"; + qCWarning(dcKeba()) << "No Keba connection found for this thing"; return; } else { keba->getReport2(); 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) { - qCWarning(dcKebaKeContact()) << "No Keba connection found for" << thing->name(); + qCWarning(dcKeba()) << "No Keba connection found for" << thing->name(); return; } keba->getReport2(); @@ -193,34 +206,55 @@ 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(dcKeba()) << "No Keba connection found for" << thing->name(); + continue; + } + + if (!keba->reachable()) { + searchNetworkDevices(); + return; + } + } }); + + m_reconnectTimer->start(); } } void IntegrationPluginKeba::thingRemoved(Thing *thing) { - qCDebug(dcKebaKeContact()) << "Deleting" << thing->name(); + qCDebug(dcKeba()) << "Deleting" << thing->name(); if (thing->thingClassId() == wallboxThingClassId) { KeContact *keba = m_kebaDevices.take(thing->id()); keba->deleteLater(); } if (myThings().empty()) { - qCDebug(dcKebaKeContact()) << "Closing UDP Ports"; - m_kebaData->deleteLater(); - m_kebaData = nullptr; + qCDebug(dcKeba()) << "Closing UDP Ports"; + 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(dcKeba()) << "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; + } } } @@ -277,11 +311,11 @@ void IntegrationPluginKeba::setDevicePlugState(Thing *thing, KeContact::PlugStat void IntegrationPluginKeba::searchNetworkDevices() { - qCDebug(dcKebaKeContact()) << "Start searching for things..."; + qCDebug(dcKeba()) << "Start searching for things..."; NetworkDeviceDiscoveryReply *discoveryReply = hardwareManager()->networkDeviceDiscovery()->discover(); connect(discoveryReply, &NetworkDeviceDiscoveryReply::finished, this, [=](){ ThingDescriptors descriptors; - qCDebug(dcKebaKeContact()) << "Discovery finished. Found" << discoveryReply->networkDeviceInfos().count() << "devices"; + qCDebug(dcKeba()) << "Discovery finished. Found" << discoveryReply->networkDeviceInfos().count() << "devices"; foreach (const NetworkDeviceInfo &networkDeviceInfo, discoveryReply->networkDeviceInfos()) { if (!networkDeviceInfo.hostName().contains("keba", Qt::CaseSensitivity::CaseInsensitive)) continue; @@ -290,21 +324,22 @@ void IntegrationPluginKeba::searchNetworkDevices() if (existingThing->paramValue(wallboxThingMacAddressParamTypeId).toString().isEmpty()) { //This device got probably manually setup, to enable auto rediscovery the MAC address needs to setup if (existingThing->paramValue(wallboxThingIpAddressParamTypeId).toString() == networkDeviceInfo.address().toString()) { - qCDebug(dcKebaKeContact()) << "Keba Wallbox MAC Address has been discovered" << existingThing->name() << networkDeviceInfo.macAddress(); + qCDebug(dcKeba()) << "Keba Wallbox MAC Address has been discovered" << existingThing->name() << networkDeviceInfo.macAddress(); 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(); + qCDebug(dcKeba()) << "Keba Wallbox IP Address has changed, from" << existingThing->paramValue(wallboxThingIpAddressParamTypeId).toString() << "to" << networkDeviceInfo.address().toString(); existingThing->setParamValue(wallboxThingIpAddressParamTypeId, networkDeviceInfo.address().toString()); KeContact *keba = m_kebaDevices.value(existingThing->id()); if (keba) { keba->setAddress(QHostAddress(networkDeviceInfo.address())); } else { - qCWarning(dcKebaKeContact()) << "Could not update IP address, for" << existingThing; + qCWarning(dcKeba()) << "Could not update IP address, for" << existingThing; } } else { - qCDebug(dcKebaKeContact()) << "Keba Wallbox" << existingThing->name() << "IP address has not changed" << networkDeviceInfo.address().toString(); + qCDebug(dcKeba()) << "Keba Wallbox" << existingThing->name() << "IP address has not changed" << networkDeviceInfo.address().toString(); } break; } @@ -318,9 +353,10 @@ void IntegrationPluginKeba::onConnectionChanged(bool status) KeContact *keba = static_cast(sender()); Thing *thing = myThings().findById(m_kebaDevices.key(keba)); if (!thing) { - qCWarning(dcKebaKeContact()) << "On connection changed: missing device object"; + qCDebug(dcKeba()) << "Received connected changed but the thing seems not to be setup yet."; return; } + thing->setStateValue(wallboxConnectedStateTypeId, status); if (!status) { searchNetworkDevices(); @@ -336,9 +372,10 @@ void IntegrationPluginKeba::onCommandExecuted(QUuid requestId, bool success) Thing *thing = myThings().findById(m_kebaDevices.key(keba)); if (!thing) { - qCWarning(dcKebaKeContact()) << "On command executed: missing device object"; + qCWarning(dcKeba()) << "On command executed: missing device object"; return; } + ThingActionInfo *info = m_asyncActions.take(requestId); if (success) { info->finish(Thing::ThingErrorNoError); @@ -355,25 +392,25 @@ void IntegrationPluginKeba::onReportTwoReceived(const KeContact::ReportTwo &repo if (!thing) return; - qCDebug(dcKebaKeContact()) << "Report 2 received for" << thing->name() << "Serial number:" << thing->stateValue(wallboxSerialnumberStateTypeId).toString(); - qCDebug(dcKebaKeContact()) << " - State:" << reportTwo.state; - qCDebug(dcKebaKeContact()) << " - Error 1:" << reportTwo.error1; - qCDebug(dcKebaKeContact()) << " - Error 2:" << reportTwo.error2; - qCDebug(dcKebaKeContact()) << " - Plug:" << reportTwo.plugState; - qCDebug(dcKebaKeContact()) << " - Enable sys:" << reportTwo.enableSys; - qCDebug(dcKebaKeContact()) << " - Enable user:" << reportTwo.enableUser; - qCDebug(dcKebaKeContact()) << " - Max curr:" << reportTwo.maxCurrent; - qCDebug(dcKebaKeContact()) << " - Max curr %:" << reportTwo.maxCurrentPercentage; - qCDebug(dcKebaKeContact()) << " - Curr HW:" << reportTwo.currentHardwareLimitation; - qCDebug(dcKebaKeContact()) << " - Curr User:" << reportTwo.currentUser; - qCDebug(dcKebaKeContact()) << " - Curr FS:" << reportTwo.currentFailsafe; - qCDebug(dcKebaKeContact()) << " - Tmo FS:" << reportTwo.timeoutFailsafe; - qCDebug(dcKebaKeContact()) << " - Curr timer:" << reportTwo.currTimer; - qCDebug(dcKebaKeContact()) << " - Timeout CT:" << reportTwo.timeoutCt; - qCDebug(dcKebaKeContact()) << " - Output:" << reportTwo.output; - qCDebug(dcKebaKeContact()) << " - Input:" << reportTwo.input; - qCDebug(dcKebaKeContact()) << " - Serial number:" << reportTwo.serialNumber; - qCDebug(dcKebaKeContact()) << " - Uptime:" << reportTwo.seconds/60 << "[min]"; + qCDebug(dcKeba()) << "Report 2 received for" << thing->name() << "Serial number:" << thing->stateValue(wallboxSerialnumberStateTypeId).toString(); + qCDebug(dcKeba()) << " - State:" << reportTwo.state; + qCDebug(dcKeba()) << " - Error 1:" << reportTwo.error1; + qCDebug(dcKeba()) << " - Error 2:" << reportTwo.error2; + qCDebug(dcKeba()) << " - Plug:" << reportTwo.plugState; + qCDebug(dcKeba()) << " - Enable sys:" << reportTwo.enableSys; + qCDebug(dcKeba()) << " - Enable user:" << reportTwo.enableUser; + qCDebug(dcKeba()) << " - Max curr:" << reportTwo.maxCurrent; + qCDebug(dcKeba()) << " - Max curr %:" << reportTwo.maxCurrentPercentage; + qCDebug(dcKeba()) << " - Curr HW:" << reportTwo.currentHardwareLimitation; + qCDebug(dcKeba()) << " - Curr User:" << reportTwo.currentUser; + qCDebug(dcKeba()) << " - Curr FS:" << reportTwo.currentFailsafe; + qCDebug(dcKeba()) << " - Tmo FS:" << reportTwo.timeoutFailsafe; + qCDebug(dcKeba()) << " - Curr timer:" << reportTwo.currTimer; + qCDebug(dcKeba()) << " - Timeout CT:" << reportTwo.timeoutCt; + qCDebug(dcKeba()) << " - Output:" << reportTwo.output; + qCDebug(dcKeba()) << " - Input:" << reportTwo.input; + qCDebug(dcKeba()) << " - Serial number:" << reportTwo.serialNumber; + qCDebug(dcKeba()) << " - Uptime:" << reportTwo.seconds/60 << "[min]"; if (reportTwo.serialNumber == thing->stateValue(wallboxSerialnumberStateTypeId).toString()) { setDeviceState(thing, reportTwo.state); @@ -384,16 +421,21 @@ void IntegrationPluginKeba::onReportTwoReceived(const KeContact::ReportTwo &repo thing->setStateValue(wallboxError2StateTypeId, reportTwo.error2); thing->setStateValue(wallboxSystemEnabledStateTypeId, reportTwo.enableSys); - thing->setStateValue(wallboxMaxChargingCurrentStateTypeId, reportTwo.currentUser); + thing->setStateValue(wallboxMaxChargingCurrentStateTypeId, reportTwo.currTimer); + thing->setStateValue(wallboxMaxChargingCurrentGeneralStateTypeId, reportTwo.currentUser); thing->setStateValue(wallboxMaxChargingCurrentPercentStateTypeId, reportTwo.maxCurrentPercentage); - thing->setStateValue(wallboxMaxPossibleChargingCurrentStateTypeId, reportTwo.currentHardwareLimitation); + + // Set the state limits according to the hardware limits + // FIXME: enable limits once landed + //thing->setStateMaxValue(wallboxMaxChargingCurrentStateTypeId, reportTwo.currentHardwareLimitation); + //thing->setStateMaxValue(wallboxMaxChargingCurrentGeneralStateTypeId, reportTwo.currentHardwareLimitation); thing->setStateValue(wallboxOutputX2StateTypeId, reportTwo.output); thing->setStateValue(wallboxInputStateTypeId, reportTwo.input); - thing->setStateValue(wallboxUptimeStateTypeId, reportTwo.seconds/60); + thing->setStateValue(wallboxUptimeStateTypeId, reportTwo.seconds / 60); } else { - qCWarning(dcKebaKeContact()) << "Received report but the serial number didn't match"; + qCWarning(dcKeba()) << "Received report but the serial number didn't match"; } } @@ -404,23 +446,24 @@ void IntegrationPluginKeba::onReportThreeReceived(const KeContact::ReportThree & if (!thing) return; - qCDebug(dcKebaKeContact()) << "Report 3 received for" << thing->name() << "Serial number:" << thing->stateValue(wallboxSerialnumberStateTypeId).toString(); - qCDebug(dcKebaKeContact()) << " - Current phase 1:" << reportThree.currentPhase1 << "[A]"; - qCDebug(dcKebaKeContact()) << " - Current phase 2:" << reportThree.currentPhase2 << "[A]"; - qCDebug(dcKebaKeContact()) << " - Current phase 3:" << reportThree.currentPhase3 << "[A]"; - qCDebug(dcKebaKeContact()) << " - Voltage phase 1:" << reportThree.voltagePhase1 << "[V]"; - qCDebug(dcKebaKeContact()) << " - Voltage phase 2:" << reportThree.voltagePhase2 << "[V]"; - qCDebug(dcKebaKeContact()) << " - Voltage phase 3:" << reportThree.voltagePhase3 << "[V]"; - qCDebug(dcKebaKeContact()) << " - Power consumption:" << reportThree.power << "[kW]"; - qCDebug(dcKebaKeContact()) << " - Energy session" << reportThree.energySession << "[kWh]"; - qCDebug(dcKebaKeContact()) << " - Energy total" << reportThree.energyTotal << "[kWh]"; - qCDebug(dcKebaKeContact()) << " - Serial number" << reportThree.serialNumber; - qCDebug(dcKebaKeContact()) << " - Uptime" << reportThree.seconds/60 << "[min]"; + qCDebug(dcKeba()) << "Report 3 received for" << thing->name() << "Serial number:" << thing->stateValue(wallboxSerialnumberStateTypeId).toString(); + qCDebug(dcKeba()) << " - Current phase 1:" << reportThree.currentPhase1 << "[A]"; + qCDebug(dcKeba()) << " - Current phase 2:" << reportThree.currentPhase2 << "[A]"; + qCDebug(dcKeba()) << " - Current phase 3:" << reportThree.currentPhase3 << "[A]"; + qCDebug(dcKeba()) << " - Voltage phase 1:" << reportThree.voltagePhase1 << "[V]"; + qCDebug(dcKeba()) << " - Voltage phase 2:" << reportThree.voltagePhase2 << "[V]"; + qCDebug(dcKeba()) << " - Voltage phase 3:" << reportThree.voltagePhase3 << "[V]"; + qCDebug(dcKeba()) << " - Power consumption:" << reportThree.power << "[kW]"; + qCDebug(dcKeba()) << " - Energy session" << reportThree.energySession << "[kWh]"; + qCDebug(dcKeba()) << " - Energy total" << reportThree.energyTotal << "[kWh]"; + qCDebug(dcKeba()) << " - Serial number" << reportThree.serialNumber; + qCDebug(dcKeba()) << " - Uptime" << reportThree.seconds/60 << "[min]"; if (reportThree.serialNumber == thing->stateValue(wallboxSerialnumberStateTypeId).toString()) { thing->setStateValue(wallboxCurrentPhase1EventTypeId, reportThree.currentPhase1); thing->setStateValue(wallboxCurrentPhase2EventTypeId, reportThree.currentPhase2); thing->setStateValue(wallboxCurrentPhase3EventTypeId, reportThree.currentPhase3); + thing->setStateValue(wallboxCurrentStateTypeId, reportThree.currentPhase1 + reportThree.currentPhase2 + reportThree.currentPhase3); thing->setStateValue(wallboxVoltagePhase1EventTypeId, reportThree.voltagePhase1); thing->setStateValue(wallboxVoltagePhase2EventTypeId, reportThree.voltagePhase2); thing->setStateValue(wallboxVoltagePhase3EventTypeId, reportThree.voltagePhase3); @@ -429,7 +472,7 @@ void IntegrationPluginKeba::onReportThreeReceived(const KeContact::ReportThree & thing->setStateValue(wallboxPowerFactorStateTypeId, reportThree.powerFactor); thing->setStateValue(wallboxTotalEnergyConsumedStateTypeId, reportThree.energyTotal); } else { - qCWarning(dcKebaKeContact()) << "Received report but the serial number didn't match"; + qCWarning(dcKeba()) << "Received report but the serial number didn't match"; } } @@ -440,18 +483,18 @@ void IntegrationPluginKeba::onReport1XXReceived(int reportNumber, const KeContac if (!thing) return; - qCDebug(dcKebaKeContact()) << "Report" << reportNumber << "received for" << thing->name() << "Serial number:" << thing->stateValue(wallboxSerialnumberStateTypeId).toString(); - qCDebug(dcKebaKeContact()) << " - Session Id" << report.sessionId; - qCDebug(dcKebaKeContact()) << " - Curr HW" << report.currHW; - qCDebug(dcKebaKeContact()) << " - Energy start" << report.startEnergy; - qCDebug(dcKebaKeContact()) << " - Energy present" << report.presentEnergy; - qCDebug(dcKebaKeContact()) << " - Start time" << report.startTime; - qCDebug(dcKebaKeContact()) << " - End time" << report.endTime; - qCDebug(dcKebaKeContact()) << " - Stop reason" << report.stopReason; - qCDebug(dcKebaKeContact()) << " - RFID Tag" << report.rfidTag; - qCDebug(dcKebaKeContact()) << " - RFID Class" << report.rfidClass; - qCDebug(dcKebaKeContact()) << " - Serial number" << report.serialNumber; - qCDebug(dcKebaKeContact()) << " - Uptime" << report.seconds; + qCDebug(dcKeba()) << "Report" << reportNumber << "received for" << thing->name() << "Serial number:" << thing->stateValue(wallboxSerialnumberStateTypeId).toString(); + qCDebug(dcKeba()) << " - Session Id" << report.sessionId; + qCDebug(dcKeba()) << " - Curr HW" << report.currHW; + qCDebug(dcKeba()) << " - Energy start" << report.startEnergy; + qCDebug(dcKeba()) << " - Energy present" << report.presentEnergy; + qCDebug(dcKeba()) << " - Start time" << report.startTime << QDateTime::fromMSecsSinceEpoch(report.startTime * 1000).toString(); + qCDebug(dcKeba()) << " - End time" << report.endTime; + qCDebug(dcKeba()) << " - Stop reason" << report.stopReason; + qCDebug(dcKeba()) << " - RFID Tag" << report.rfidTag; + qCDebug(dcKeba()) << " - RFID Class" << report.rfidClass; + qCDebug(dcKeba()) << " - Serial number" << report.serialNumber; + qCDebug(dcKeba()) << " - Uptime" << report.seconds; if (reportNumber == 100) { // Report 100 is the current charging session @@ -471,7 +514,7 @@ void IntegrationPluginKeba::onReport1XXReceived(int reportNumber, const KeContac m_lastSessionId.insert(thing->id(), report.sessionId); } else { if (m_lastSessionId.value(thing->id()) != report.sessionId) { - qCDebug(dcKebaKeContact()) << "New session id receivd"; + qCDebug(dcKeba()) << "New session id receivd"; Event event; event.setEventTypeId(wallboxChargingSessionFinishedEventTypeId); event.setThingId(thing->id()); @@ -484,10 +527,10 @@ void IntegrationPluginKeba::onReport1XXReceived(int reportNumber, const KeContac } } } else { - qCWarning(dcKebaKeContact()) << "Received report but the serial number didn't match"; + qCWarning(dcKeba()) << "Received report but the serial number didn't match"; } } else { - qCWarning(dcKebaKeContact()) << "Received unhandled report" << reportNumber; + qCWarning(dcKeba()) << "Received unhandled report" << reportNumber; } } @@ -498,7 +541,7 @@ void IntegrationPluginKeba::onBroadcastReceived(KeContact::BroadcastType type, c if (!thing) return; - qCDebug(dcKebaKeContact()) << "Broadcast received" << type << "value" << content; + qCDebug(dcKeba()) << "Broadcast received" << type << "value" << content; switch (type) { case KeContact::BroadcastTypePlug: @@ -508,7 +551,7 @@ void IntegrationPluginKeba::onBroadcastReceived(KeContact::BroadcastType type, c thing->setStateValue(wallboxInputStateTypeId, (content.toInt() == 1)); break; case KeContact::BroadcastTypeEPres: - thing->setStateValue(wallboxSessionEnergyStateTypeId, content.toInt()/10000.00); + thing->setStateValue(wallboxSessionEnergyStateTypeId, content.toInt() / 10000.00); break; case KeContact::BroadcastTypeState: setDeviceState(thing, KeContact::State(content.toInt())); @@ -530,38 +573,44 @@ void IntegrationPluginKeba::executeAction(ThingActionInfo *info) if (thing->thingClassId() == wallboxThingClassId) { KeContact *keba = m_kebaDevices.value(thing->id()); if (!keba) { - qCWarning(dcKebaKeContact()) << "Device not properly initialized, Keba object missing"; + qCWarning(dcKeba()) << "Device not properly initialized, Keba object missing"; return info->finish(Thing::ThingErrorHardwareNotAvailable); } QUuid requestId; - if(action.actionTypeId() == wallboxMaxChargingCurrentActionTypeId){ - int milliAmpere = action.param(wallboxMaxChargingCurrentActionMaxChargingCurrentParamTypeId).value().toDouble()*1000; + if (action.actionTypeId() == wallboxMaxChargingCurrentActionTypeId) { + int milliAmpere = action.param(wallboxMaxChargingCurrentActionMaxChargingCurrentParamTypeId).value().toDouble() * 1000; requestId = keba->setMaxAmpere(milliAmpere); - - } else if(action.actionTypeId() == wallboxPowerActionTypeId){ + } else if(action.actionTypeId() == wallboxMaxChargingCurrentGeneralActionTypeId) { + int milliAmpere = action.param(wallboxMaxChargingCurrentGeneralActionMaxChargingCurrentGeneralParamTypeId).value().toDouble() * 1000; + requestId = keba->setMaxAmpereGeneral(milliAmpere); + } else if(action.actionTypeId() == wallboxPowerActionTypeId) { requestId = keba->enableOutput(action.param(wallboxPowerActionTypeId).value().toBool()); - - } else if(action.actionTypeId() == wallboxDisplayActionTypeId){ + } else if(action.actionTypeId() == wallboxDisplayActionTypeId) { requestId = keba->displayMessage(action.param(wallboxDisplayActionMessageParamTypeId).value().toByteArray()); - } else if(action.actionTypeId() == wallboxOutputX2ActionTypeId) { requestId = keba->setOutputX2(action.param(wallboxOutputX2ActionOutputX2ParamTypeId).value().toBool()); - - } else if(action.actionTypeId() == wallboxFailsafeModeActionTypeId){ + } else if(action.actionTypeId() == wallboxFailsafeModeActionTypeId) { int timeout = 0; if (action.param(wallboxFailsafeModeActionFailsafeModeParamTypeId).value().toBool()) { timeout = 60; } requestId = keba->setFailsafe(timeout, 0, false); } else { - qCWarning(dcKebaKeContact()) << "Unhandled ActionTypeId:" << action.actionTypeId(); + qCWarning(dcKeba()) << "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(); + qCWarning(dcKeba()) << "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..4caaccca 100644 --- a/keba/integrationpluginkeba.json +++ b/keba/integrationpluginkeba.json @@ -1,6 +1,6 @@ { "displayName": "Keba KeContact", - "name": "KebaKeContact", + "name": "Keba", "id": "9142b09f-30a9-43d0-9ede-2f8debe075ac", "vendors": [ { @@ -92,7 +92,8 @@ "displayNameAction": "Set charging enabled", "type": "bool", "writable": true, - "defaultValue": false + "defaultValue": false, + "suggestLogging": true }, { "id": "e5631593-f486-47cb-9951-b7597d0b769b", @@ -133,7 +134,8 @@ "displayNameEvent": "Current changed", "type": "double", "unit": "Ampere", - "defaultValue": 0.00 + "defaultValue": 0.00, + "suggestLogging": true }, { "id": "593656f0-babf-4308-8767-68f34e10fb15", @@ -143,10 +145,25 @@ "displayNameAction": "Set maximal charging current", "type": "double", "unit": "Ampere", - "defaultValue": 6.00, - "minValue": 6.00, - "maxValue": 63.00, - "writable": true + "defaultValue": 6.0, + "minValue": 6.0, + "maxValue": 32.0, + "writable": true, + "suggestLogging": true + }, + { + "id": "da0cfb97-0b27-4d8f-bdf7-45b1ca727038", + "name": "maxChargingCurrentGeneral", + "displayName": "Maximal general charging current", + "displayNameEvent": "Maximal general charging current changed", + "displayNameAction": "Set maximal general charging current", + "type": "double", + "unit": "Ampere", + "defaultValue": 6.0, + "minValue": 6.0, + "maxValue": 32.0, + "writable": true, + "suggestLogging": true }, { "id": "3c7b83a0-0e42-47bf-9788-dde6aab5ceea", @@ -157,16 +174,8 @@ "unit": "Percentage", "defaultValue": 100, "minValue": 0, - "maxValue": 100 - }, - { - "id": "08bb9872-8d63-49b0-a8ce-7a449341f13b", - "name": "maxPossibleChargingCurrent", - "displayName": "Maximum possible charging current", - "displayNameEvent": "Maximum possible charging current changed", - "type": "double", - "unit": "Ampere", - "defaultValue": 6.00 + "maxValue": 100, + "suggestLogging": true }, { "id": "4a2d75d8-a3a0-4b40-9ca7-e8b6f11d0ef9", @@ -202,7 +211,8 @@ "displayNameEvent": "Current phase 1 changed", "type": "double", "unit": "Ampere", - "defaultValue": 0.00 + "defaultValue": 0.00, + "suggestLogging": true }, { "id": "cdc7e10a-0d0a-4e93-ad2c-d34ffca45c97", @@ -211,7 +221,8 @@ "displayNameEvent": "Current phase 2 changed", "type": "double", "unit": "Ampere", - "defaultValue": 0.00 + "defaultValue": 0.00, + "suggestLogging": true }, { "id": "da838dc8-85f0-4e55-b4b5-cb93a43b373d", @@ -220,7 +231,8 @@ "displayNameEvent": "Current phase 3 changed", "type": "double", "unit": "Ampere", - "defaultValue": 0.00 + "defaultValue": 0.00, + "suggestLogging": true }, { "id": "7af9e93b-099d-4d9d-a480-9c0f66aecd8b", @@ -229,7 +241,8 @@ "displayNameEvent": "Power consumtion changed", "type": "double", "unit": "Watt", - "defaultValue": 0.00 + "defaultValue": 0.00, + "suggestLogging": true }, { "id": "889c3c9a-96b4-4408-bd9a-d79e36ed9296", @@ -264,7 +277,8 @@ "displayNameEvent": "Session energy changed", "type": "double", "unit": "KiloWattHour", - "defaultValue": 0 + "defaultValue": 0, + "suggestLogging": true }, { "id": "41e179b3-29a2-43ec-b537-023a527081e8", @@ -273,7 +287,8 @@ "displayNameEvent": "Total energy consumption changed", "type": "double", "unit": "KiloWattHour", - "defaultValue": 0 + "defaultValue": 0, + "suggestLogging": true }, { "id": "96b2d176-6460-4109-8824-3af4679c6573", diff --git a/keba/kecontact.cpp b/keba/kecontact.cpp index ec02fac0..1f3ca12b 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,21 +33,33 @@ #include - KeContact::KeContact(const QHostAddress &address, KeContactDataLayer *dataLayer, QObject *parent) : QObject(parent), m_dataLayer(dataLayer), m_address(address) { - qCDebug(dcKebaKeContact()) << "Creating KeContact connection for address" << m_address; + qCDebug(dcKeba()) << "Creating KeContact connection for address" << m_address; 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); - //Try to send the next command - handleNextCommandInQueue(); - m_deviceBlocked = false; + 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 + setReachable(false); + + if (m_currentRequest.isValid()) { + // Schedule pause timer to send next request + qCWarning(dcKeba()) << "Command timeouted" << m_currentRequest.command(); + emit commandExecuted(m_currentRequest.requestId(), false); + } + + // Timeout...send the next request right the way since at least 5 seconds passed since tha last command + m_currentRequest = KeContactRequest(); + sendNextCommand(); + }); + + m_pauseTimer = new QTimer(this); + m_pauseTimer->setSingleShot(true); + connect(m_pauseTimer, &QTimer::timeout, this, [this](){ + sendNextCommand(); }); connect(m_dataLayer, &KeContactDataLayer::datagramReceived, this, &KeContact::onReceivedDatagram); @@ -55,180 +67,250 @@ KeContact::KeContact(const QHostAddress &address, KeContactDataLayer *dataLayer, KeContact::~KeContact() { - qCDebug(dcKebaKeContact()) << "Deleting KeContact connection for address" << m_address; + qCDebug(dcKeba()) << "Deleting KeContact connection for address" << m_address.toString(); } -QHostAddress KeContact::address() +QHostAddress KeContact::address() const { return m_address; } QUuid KeContact::start(const QByteArray &rfidToken, const QByteArray &rfidClassifier) { - QUuid requestId = QUuid::createUuid(); - m_pendingRequests.append(requestId); - QByteArray datagram = "start "+rfidToken + " " + rfidClassifier; - qCDebug(dcKebaKeContact()) << "Datagram : " << datagram; - sendCommand(datagram, requestId);; - return requestId; + if (!m_dataLayer) { + qCWarning(dcKeba()) << "UDP socket not initialized"; + setReachable(false); + return QUuid(); + } + + QByteArray datagram = "start " + rfidToken + " " + rfidClassifier; + KeContactRequest request(QUuid::createUuid(), datagram); + qCDebug(dcKeba()) << "Start: Datagram:" << datagram; + m_requestQueue.enqueue(request); + sendNextCommand(); + return request.requestId(); } QUuid KeContact::stop(const QByteArray &rfidToken) { - QUuid requestId = QUuid::createUuid(); - m_pendingRequests.append(requestId); - QByteArray datagram = "stop "+rfidToken; - qCDebug(dcKebaKeContact()) << "Datagram : " << datagram; - sendCommand(datagram, requestId); - return requestId; + if (!m_dataLayer) { + qCWarning(dcKeba()) << "UDP socket not initialized"; + setReachable(false); + return QUuid(); + } + + QByteArray datagram = "stop " + rfidToken; + KeContactRequest request(QUuid::createUuid(), datagram); + qCDebug(dcKeba()) << "Stop: Datagram:" << datagram; + m_requestQueue.enqueue(request); + sendNextCommand(); + return request.requestId(); } void KeContact::setAddress(const QHostAddress &address) { - qCDebug(dcKebaKeContact()) << "Updating Keba connection address" << address.toString(); + if (m_address == address) + return; + + qCDebug(dcKeba()) << "Updating Keba connection address from" << m_address.toString() << "to" << address.toString(); m_address = address; } - -void KeContact::sendCommand(const QByteArray &command, const QUuid &requestId) +bool KeContact::reachable() const { - QTimer::singleShot(5000, this, [requestId, this] { - if (m_pendingRequests.contains(requestId)) { - m_pendingRequests.removeOne(requestId); - emit commandExecuted(requestId, false); - } - }); - sendCommand(command); + return m_reachable; } void KeContact::sendCommand(const QByteArray &command) { if (!m_dataLayer) { - qCWarning(dcKebaKeContact()) << "UDP socket not initialized"; - emit reachableChanged(false); + qCWarning(dcKeba()) << "UDP socket not initialized"; + setReachable(false); return; } - 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_requestTimeoutTimer->start(5000); - m_deviceBlocked = true; - } + qCDebug(dcKeba()) << "--> Writing datagram to" << m_address.toString() << command; + m_dataLayer->write(m_address, command); + m_requestTimeoutTimer->start(5000); } -void KeContact::handleNextCommandInQueue() +void KeContact::sendNextCommand() { - if (!m_dataLayer) { - qCWarning(dcKebaKeContact()) << "Data layer not initialized"; - if (m_reachable == true) { - m_reachable = false; - emit reachableChanged(false); - } + // No message left, we are done + if (m_requestQueue.isEmpty()) return; - } - 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; - m_dataLayer->write( m_address, command); - m_requestTimeoutTimer->start(5000); - } + + // Still a request pending + if (m_currentRequest.isValid()) + return; + + m_currentRequest = m_requestQueue.dequeue(); + sendCommand(m_currentRequest.command()); } +void KeContact::setReachable(bool reachable) +{ + if (m_reachable == reachable) + return; + + if (reachable) { + qCDebug(dcKeba()) << "The keba wallbox on" << m_address.toString() << "is now reachable again."; + } else { + qCWarning(dcKeba()) << "The keba wallbox on" << m_address.toString() << "is not reachable any more."; + } + + m_reachable = reachable; + emit reachableChanged(m_reachable); +} QUuid KeContact::enableOutput(bool state) { - QUuid requestId = QUuid::createUuid(); - m_pendingRequests.append(requestId); + if (!m_dataLayer) { + qCWarning(dcKeba()) << "UDP socket not initialized"; + setReachable(false); + return QUuid(); + } + // 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; + + KeContactRequest request(QUuid::createUuid(), datagram); + request.setDelayUntilNextCommand(2000); + qCDebug(dcKeba()) << "Enable output: Datagram:" << datagram; + m_requestQueue.enqueue(request); + sendNextCommand(); + return request.requestId(); } QUuid KeContact::setMaxAmpere(int milliAmpere) { - if (milliAmpere < 6000 || milliAmpere > 63000) { - qCWarning(dcKebaKeContact()) << "KeContact: Set max ampere, mA out of range [6000, 63000]" << milliAmpere; - return ""; + if (!m_dataLayer) { + qCWarning(dcKeba()) << "UDP socket not initialized"; + setReachable(false); + return QUuid(); } - QUuid requestId = QUuid::createUuid(); - m_pendingRequests.append(requestId); + + if (milliAmpere < 6000 || milliAmpere > 63000) { + qCWarning(dcKeba()) << "KeContact: Set max ampere, currtime mA out of range [6000, 63000]" << milliAmpere; + return QUuid(); + } + // 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()); - qCDebug(dcKebaKeContact()) << "Set max. ampere, command: " << data; - sendCommand(data, requestId); - return requestId; + qCDebug(dcKeba()) << "Update max current to : " << milliAmpere; + QString commandLine = QString("currtime %1 1").arg(milliAmpere); + QByteArray datagram = commandLine.toUtf8(); + KeContactRequest request(QUuid::createUuid(), datagram); + request.setDelayUntilNextCommand(1200); + qCDebug(dcKeba()) << "Set max charging amps: Datagram:" << datagram; + m_requestQueue.enqueue(request); + sendNextCommand(); + return request.requestId(); +} + +QUuid KeContact::setMaxAmpereGeneral(int milliAmpere) +{ + if (!m_dataLayer) { + qCWarning(dcKeba()) << "UDP socket not initialized"; + setReachable(false); + return QUuid(); + } + + if (milliAmpere < 6000 || milliAmpere > 63000) { + qCWarning(dcKeba()) << "KeContact: Set max ampere curr, mA out of range [6000, 63000]" << milliAmpere; + return QUuid(); + } + + // Print information that we are executing now the update action + qCDebug(dcKeba()) << "Update general max current to: " << milliAmpere; + QString commandLine = QString("curr %1").arg(milliAmpere); + QByteArray datagram = commandLine.toUtf8(); + KeContactRequest request(QUuid::createUuid(), datagram); + request.setDelayUntilNextCommand(1200); + qCDebug(dcKeba()) << "Set max general charging amps: Datagram:" << datagram; + m_requestQueue.enqueue(request); + sendNextCommand(); + return request.requestId(); } QUuid KeContact::displayMessage(const QByteArray &message) { + if (!m_dataLayer) { + qCWarning(dcKeba()) << "UDP socket not initialized"; + setReachable(false); + return QUuid(); + } + /* Text shown on the display. Maximum 23 ASCII characters can be used. 0 .. 23 characters ~ == Σ $ == blank , == comma */ - QUuid requestId = QUuid::createUuid(); - m_pendingRequests.append(requestId); - qCDebug(dcKebaKeContact()) << "Set display message: " << message; - QByteArray data; + + qCDebug(dcKeba()) << "Set display message: " << message; + QByteArray datagram; QByteArray modifiedMessage = message; modifiedMessage.replace(" ", "$"); if (modifiedMessage.size() > 23) { modifiedMessage.resize(23); } - data.append("display 0 0 0 0 " + modifiedMessage); - qCDebug(dcKebaKeContact()) << "Display message, command: " << data; - sendCommand(data, requestId); - return requestId; + datagram.append("display 0 0 0 0 " + modifiedMessage); + KeContactRequest request(QUuid::createUuid(), datagram); + qCDebug(dcKeba()) << "Display message: Datagram:" << datagram; + m_requestQueue.enqueue(request); + sendNextCommand(); + return request.requestId(); } QUuid KeContact::chargeWithEnergyLimit(double energy) { - QUuid requestId = QUuid::createUuid(); - m_pendingRequests.append(requestId); + if (!m_dataLayer) { + qCWarning(dcKeba()) << "UDP socket not initialized"; + setReachable(false); + return QUuid(); + } - QByteArray data; - data.append("setenergy " + QVariant(static_cast(energy*10000)).toByteArray()); - qCDebug(dcKebaKeContact()) << "Charge with energy limit, command: " << data; - sendCommand(data, requestId); - return requestId; + QByteArray datagram; + datagram.append("setenergy " + QVariant(static_cast(energy*10000)).toByteArray()); + KeContactRequest request(QUuid::createUuid(), datagram); + qCDebug(dcKeba()) << "Charge with energy limit: Datagram: " << datagram; + m_requestQueue.enqueue(request); + sendNextCommand(); + return request.requestId(); } QUuid KeContact::setFailsafe(int timeout, int current, bool save) { - QUuid requestId = QUuid::createUuid(); - m_pendingRequests.append(requestId); + if (!m_dataLayer) { + qCWarning(dcKeba()) << "UDP socket not initialized"; + setReachable(false); + return QUuid(); + } QByteArray data; data.append("failsave"); data.append(" "+QVariant(timeout).toByteArray()); data.append(" "+QVariant(current).toByteArray()); data.append((save ? " 1":" 0")); - qCDebug(dcKebaKeContact()) << "Set failsafe mode, command: " << data; - sendCommand(data, requestId); - return requestId; + KeContactRequest request(QUuid::createUuid(), data); + qCDebug(dcKeba()) << "Set failsafe mode: Datagram: " << data; + m_requestQueue.enqueue(request); + sendNextCommand(); + return request.requestId(); } - void KeContact::getDeviceInformation() { QByteArray data; data.append("i"); - qCDebug(dcKebaKeContact()) << "Get device information, command: " << data; - sendCommand(data); + KeContactRequest request(QUuid::createUuid(), data); + qCDebug(dcKeba()) << "Get device information: Datagram: " << data; + m_requestQueue.enqueue(request); + sendNextCommand(); } void KeContact::getReport1() @@ -253,90 +335,134 @@ void KeContact::getReport1XX(int reportNumber) QUuid KeContact::setOutputX2(bool state) { - QUuid requestId = QUuid::createUuid(); - m_pendingRequests.append(requestId); - QByteArray data; - data.append("output "+QVariant((state ? 1 : 0)).toByteArray()); - qCDebug(dcKebaKeContact()) << "Set Output X2, state:" << state << "Command:" << data; - sendCommand(data, requestId); - return requestId; + if (!m_dataLayer) { + qCWarning(dcKeba()) << "UDP socket not initialized"; + setReachable(false); + return QUuid(); + } + + + QByteArray datagram; + datagram.append("output " + QVariant((state ? 1 : 0)).toByteArray()); + + KeContactRequest request(QUuid::createUuid(), datagram); + qCDebug(dcKeba()) << "Set Output X2, state:" << state << "Datagram:" << datagram; + m_requestQueue.enqueue(request); + sendNextCommand(); + return request.requestId(); } void KeContact::getReport(int reportNumber) { - QByteArray data; - data.append("report "+QVariant(reportNumber).toByteArray()); - qCDebug(dcKebaKeContact()) << "Get report" << reportNumber << "Command:" << data; - sendCommand(data); + if (!m_dataLayer) { + qCWarning(dcKeba()) << "UDP socket not initialized"; + setReachable(false); + return; + } + + QByteArray datagram; + datagram.append("report " + QVariant(reportNumber).toByteArray()); + + KeContactRequest request(QUuid::createUuid(), datagram); + qCDebug(dcKeba()) << "Get report" << reportNumber << "Datagram:" << datagram; + m_requestQueue.enqueue(request); + sendNextCommand(); } QUuid KeContact::unlockCharger() { - QUuid requestId = QUuid::createUuid(); - m_pendingRequests.append(requestId); - QByteArray data; - data.append("unlock"); - qCDebug(dcKebaKeContact()) << "Unlock charger, command: " << data; - sendCommand(data); - return requestId; + if (!m_dataLayer) { + qCWarning(dcKeba()) << "UDP socket not initialized"; + setReachable(false); + return QUuid(); + } + + QByteArray datagram; + datagram.append("unlock"); + + KeContactRequest request(QUuid::createUuid(), datagram); + qCDebug(dcKeba()) << "Unlock charger: Datagram:" << datagram; + m_requestQueue.enqueue(request); + sendNextCommand(); + return request.requestId(); } 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")){ + qCDebug(dcKeba()) << "<--" << qUtf8Printable(datagram); + + 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; m_requestTimeoutTimer->stop(); - handleNextCommandInQueue(); - if (!m_pendingRequests.isEmpty()) { - QUuid requestId = m_pendingRequests.takeFirst(); + if (m_currentRequest.isValid()) { if (datagram.contains("done")) { - emit commandExecuted(requestId, true); + qCDebug(dcKeba()) << "Command" << m_currentRequest.command() << "finished successfully"; + emit commandExecuted(m_currentRequest.requestId(), true); } else { - emit commandExecuted(requestId, false); + qCWarning(dcKeba()) << "Command" << m_currentRequest.command() << "finished with error" << datagram; + emit commandExecuted(m_currentRequest.requestId(), false); } + + // Schedule pause timer to send next request + m_pauseTimer->start(m_currentRequest.delayUntilNextCommand()); + m_currentRequest = KeContactRequest(); } else { //Probably the response has taken too long and the requestId has been already removed + qCWarning(dcKeba()) << "Received command OK response without pending request." << datagram; } - } 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; + // Command response has been received, now send the next command m_requestTimeoutTimer->stop(); - handleNextCommandInQueue(); + if (m_currentRequest.isValid()) { + // Schedule pause timer to send next request + m_pauseTimer->start(m_currentRequest.delayUntilNextCommand()); + m_currentRequest = KeContactRequest(); + } - qCDebug(dcKebaKeContact()) << "Firmware information received"; + qCDebug(dcKeba()) << "Firmware information received"; QByteArrayList firmware = datagram.split(':'); if (firmware.length() >= 2) { emit deviceInformationReceived(firmware[1]); } } else { - //Command response has been received, now send the next command - m_deviceBlocked = false; m_requestTimeoutTimer->stop(); - handleNextCommandInQueue(); + if (m_currentRequest.isValid()) { + // Schedule pause timer to send next request + m_pauseTimer->start(m_currentRequest.delayUntilNextCommand()); + m_currentRequest = KeContactRequest(); + } // Convert the rawdata to a json document QJsonParseError error; QJsonDocument jsonDoc = QJsonDocument::fromJson(datagram, &error); if (error.error != QJsonParseError::NoError) { - qCWarning(dcKebaKeContact()) << "Failed to parse JSON data" << datagram << ":" << error.errorString(); + qCWarning(dcKeba()) << "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"; + qCDebug(dcKeba()) << "Report 1 received"; reportOne.product = data.value("Product").toString(); reportOne.firmware = data.value("Firmware").toString(); reportOne.serialNumber = data.value("Serial").toString(); @@ -357,23 +483,27 @@ 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"; + qCDebug(dcKeba()) << "Report 2 received"; int state = data.value("State").toInt(); reportTwo.state = State(state); reportTwo.error1 = data.value("Error1").toInt(); reportTwo.error2 = data.value("Error2").toInt(); reportTwo.plugState = PlugState(data.value("Plug").toInt()); - reportTwo.enableUser = data.value("Enable user").toBool(); - reportTwo.enableSys = data.value("Enable sys").toBool(); - reportTwo.maxCurrent = data.value("Max curr").toInt()/1000.00; - reportTwo.maxCurrentPercentage = data.value("Max curr %").toInt()/10.00; - reportTwo.currentHardwareLimitation = data.value("Curr HW").toInt()/1000.00; - reportTwo.currentUser = data.value("Curr user").toInt()/1000.00; - reportTwo.currentFailsafe = data.value("Curr FS").toInt()/1000.00; + reportTwo.enableUser = data.value("Enable user").toBool(); + reportTwo.enableSys = data.value("Enable sys").toBool(); + reportTwo.maxCurrent = data.value("Max curr").toInt() / 1000.00; + reportTwo.maxCurrentPercentage = data.value("Max curr %").toInt() / 10.00; + reportTwo.currentHardwareLimitation = data.value("Curr HW").toInt() / 1000.00; + reportTwo.currentUser = data.value("Curr user").toInt() / 1000.00; + reportTwo.currTimer = data.value("Curr timer").toInt() / 1000.00; + reportTwo.timeoutCt = data.value("Tmo CT").toInt(); + reportTwo.currentFailsafe = data.value("Curr FS").toInt() / 1000.00; reportTwo.timeoutFailsafe = data.value("Tmo FS").toInt(); - reportTwo.setEnergy = data.value("Setenergy").toInt()/10000.00; + reportTwo.setEnergy = data.value("Setenergy").toInt() / 10000.00; reportTwo.output = data.value("Output").toInt(); reportTwo.input= data.value("Input").toInt(); reportTwo.serialNumber = data.value("Serial").toString(); @@ -384,9 +514,11 @@ 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"; + qCDebug(dcKeba()) << "Report 3 received"; reportThree.currentPhase1 = data.value("I1").toInt()/1000.00; reportThree.currentPhase2 = data.value("I2").toInt()/1000.00; reportThree.currentPhase3 = data.value("I3").toInt()/1000.00; @@ -401,16 +533,18 @@ 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"; + qCDebug(dcKeba()) << "Report" << id << "received"; report.sessionId = data.value("Session ID").toInt(); report.currHW = data.value("Curr HW").toInt(); - report.startTime = data.value("E Start ").toInt()/10000.00; - report.presentEnergy = data.value("E Pres ").toInt()/10000.00; + report.startEnergy = data.value("E start").toInt() / 10000.00; + report.presentEnergy = data.value("E pres").toInt() / 10000.00; report.startTime = data.value("started[s]").toInt(); - report.endTime = data.value("ended[s] ").toInt(); - report.stopReason = data.value("reason ").toInt(); + report.endTime = data.value("ended[s]").toInt(); + report.stopReason = data.value("reason").toInt(); report.rfidTag = data.value("RFID tag").toByteArray(); report.rfidClass = data.value("RFID class").toByteArray(); report.serialNumber = data.value("Serial").toString(); @@ -419,21 +553,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..70c3748b 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. @@ -37,17 +37,36 @@ #include #include #include +#include #include "kecontactdatalayer.h" +class KeContactRequest +{ +public: + KeContactRequest() = default; + KeContactRequest(const QUuid &requestId, const QByteArray &command) : m_requestId(requestId), m_command(command) { } + + QUuid requestId() const { return m_requestId; } + QByteArray command() const { return m_command; } + + uint delayUntilNextCommand() const { return m_delayUntilNextCommand; } + void setDelayUntilNextCommand(uint delayUntilNextCommand) { m_delayUntilNextCommand = delayUntilNextCommand; } + + bool isValid() { return !m_requestId.isNull() && !m_command.isEmpty(); } + +private: + QUuid m_requestId; + QByteArray m_command; + uint m_delayUntilNextCommand = 200; +}; + + + 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,16 +155,20 @@ 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” QUuid enableOutput(bool state); // Command “ena” - QUuid setMaxAmpere(int milliAmpere); // Command “curr” + QUuid setMaxAmpere(int milliAmpere); // Command "currtime" + QUuid setMaxAmpereGeneral(int milliAmpere); // Command "curr" QUuid unlockCharger(); // Command “unlock" QUuid displayMessage(const QByteArray &message); // Command “display” QUuid chargeWithEnergyLimit(double energy); // Command “setenergy” @@ -161,21 +184,23 @@ public: QUuid setOutputX2(bool state); // Command “output” private: - KeContactDataLayer *m_dataLayer; + KeContactDataLayer *m_dataLayer = nullptr; bool m_reachable = false; QHostAddress m_address; - QByteArrayList m_commandList; - bool m_deviceBlocked = false; QTimer *m_requestTimeoutTimer = nullptr; - int m_serialNumber; - QList m_pendingRequests; + QTimer *m_pauseTimer = nullptr; + int m_serialNumber = 0; + + KeContactRequest m_currentRequest; + QQueue m_requestQueue; void getReport(int reportNumber); - void sendCommand(const QByteArray &command, const QUuid &requestId); + void sendCommand(const QByteArray &command); - void handleNextCommandInQueue(); + void sendNextCommand(); + void setReachable(bool reachable); signals: void reachableChanged(bool status); @@ -189,6 +214,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..c0772647 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. @@ -33,7 +33,7 @@ KeContactDataLayer::KeContactDataLayer(QObject *parent) : QObject(parent) { - qCDebug(dcKebaKeContact()) << "KeContactDataLayer: Creating UDP socket"; + qCDebug(dcKeba()) << "KeContactDataLayer: Creating UDP socket"; m_udpSocket = new QUdpSocket(this); connect(m_udpSocket, &QUdpSocket::readyRead, this, &KeContactDataLayer::readPendingDatagrams); connect(m_udpSocket, &QUdpSocket::stateChanged, this, &KeContactDataLayer::onSocketStateChanged); @@ -42,18 +42,28 @@ KeContactDataLayer::KeContactDataLayer(QObject *parent) : QObject(parent) KeContactDataLayer::~KeContactDataLayer() { - qCDebug(dcKebaKeContact()) << "KeContactDataLayer: Deleting UDP socket"; + qCDebug(dcKeba()) << "KeContactDataLayer: Deleting UDP socket"; } 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; + qCWarning(dcKeba()) << "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,20 +78,19 @@ 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(dcKeba()) << "KeContactDataLayer: Data received from" << senderAddress.toString() << datagram ; emit datagramReceived(senderAddress, datagram); } } void KeContactDataLayer::onSocketError(QAbstractSocket::SocketError error) { - qCDebug(dcKebaKeContact()) << "KeContactDataLayer: Socket error" << error; + qCDebug(dcKeba()) << "KeContactDataLayer: Socket error" << error; } void KeContactDataLayer::onSocketStateChanged(QAbstractSocket::SocketState socketState) { - qCDebug(dcKebaKeContact()) << "KeContactDataLayer: Socket state changed" << socketState; + qCDebug(dcKeba()) << "KeContactDataLayer: Socket state changed" << socketState; } 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 diff --git a/keba/translations/9142b09f-30a9-43d0-9ede-2f8debe075ac-de.ts b/keba/translations/9142b09f-30a9-43d0-9ede-2f8debe075ac-de.ts index 0a35a6c2..14ec0e16 100644 --- a/keba/translations/9142b09f-30a9-43d0-9ede-2f8debe075ac-de.ts +++ b/keba/translations/9142b09f-30a9-43d0-9ede-2f8debe075ac-de.ts @@ -10,7 +10,7 @@ - KebaKeContact + Keba @@ -266,7 +266,7 @@ The name of the StateType ({ba600276-8b36-4404-b8ec-415245e5bc15}) of ThingClass Keba KeContact The name of the ThingClass ({900dacec-cae7-4a37-95ba-501846368ea2}) ---------- -The name of the plugin KebaKeContact ({9142b09f-30a9-43d0-9ede-2f8debe075ac}) +The name of the plugin Keba ({9142b09f-30a9-43d0-9ede-2f8debe075ac}) Keba KeContact diff --git a/keba/translations/9142b09f-30a9-43d0-9ede-2f8debe075ac-en_US.ts b/keba/translations/9142b09f-30a9-43d0-9ede-2f8debe075ac-en_US.ts index 3748d67f..23c4bbf3 100644 --- a/keba/translations/9142b09f-30a9-43d0-9ede-2f8debe075ac-en_US.ts +++ b/keba/translations/9142b09f-30a9-43d0-9ede-2f8debe075ac-en_US.ts @@ -10,7 +10,7 @@ - KebaKeContact + Keba @@ -266,7 +266,7 @@ The name of the StateType ({ba600276-8b36-4404-b8ec-415245e5bc15}) of ThingClass Keba KeContact The name of the ThingClass ({900dacec-cae7-4a37-95ba-501846368ea2}) ---------- -The name of the plugin KebaKeContact ({9142b09f-30a9-43d0-9ede-2f8debe075ac}) +The name of the plugin Keba ({9142b09f-30a9-43d0-9ede-2f8debe075ac})