Rework Keba commands and connection status

This commit is contained in:
Simon Stürz 2021-09-28 12:21:58 +02:00
parent 7f6ceb4171
commit 3b0cd827fc
7 changed files with 226 additions and 73 deletions

View File

@ -49,7 +49,7 @@ void IntegrationPluginKeba::init()
void IntegrationPluginKeba::discoverThings(ThingDiscoveryInfo *info) void IntegrationPluginKeba::discoverThings(ThingDiscoveryInfo *info)
{ {
if (info->thingClassId() == wallboxThingClassId) { if (info->thingClassId() == wallboxThingClassId) {
qCDebug(dcKebaKeContact()) << "Discovering Keba Wallbox"; qCDebug(dcKebaKeContact()) << "Discovering Keba Wallbox...";
NetworkDeviceDiscoveryReply *discoveryReply = hardwareManager()->networkDeviceDiscovery()->discover(); NetworkDeviceDiscoveryReply *discoveryReply = hardwareManager()->networkDeviceDiscovery()->discover();
connect(discoveryReply, &NetworkDeviceDiscoveryReply::finished, this, [=](){ connect(discoveryReply, &NetworkDeviceDiscoveryReply::finished, this, [=](){
ThingDescriptors descriptors; ThingDescriptors descriptors;
@ -59,9 +59,9 @@ void IntegrationPluginKeba::discoverThings(ThingDiscoveryInfo *info)
continue; continue;
qCDebug(dcKebaKeContact()) << " - Keba Wallbox" << networkDeviceInfo; qCDebug(dcKebaKeContact()) << " - Keba Wallbox" << networkDeviceInfo;
QString title = "Wallbox "; QString title = "Keba Wallbox ";
if (networkDeviceInfo.hostName().isEmpty()) { if (networkDeviceInfo.hostName().isEmpty()) {
title += networkDeviceInfo.address().toString(); title += "(" + networkDeviceInfo.address().toString() + ")";
} else { } else {
title += networkDeviceInfo.hostName() + " (" + networkDeviceInfo.address().toString() + ")"; title += networkDeviceInfo.hostName() + " (" + networkDeviceInfo.address().toString() + ")";
} }
@ -92,7 +92,7 @@ void IntegrationPluginKeba::discoverThings(ThingDiscoveryInfo *info)
info->finish(Thing::ThingErrorNoError); info->finish(Thing::ThingErrorNoError);
}); });
} else { } 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); info->finish(Thing::ThingErrorThingClassNotFound);
} }
} }
@ -100,24 +100,23 @@ void IntegrationPluginKeba::discoverThings(ThingDiscoveryInfo *info)
void IntegrationPluginKeba::setupThing(ThingSetupInfo *info) void IntegrationPluginKeba::setupThing(ThingSetupInfo *info)
{ {
Thing *thing = info->thing(); Thing *thing = info->thing();
qCDebug(dcKebaKeContact()) << "Setting up" << thing->name() << thing->params();
qCDebug(dcKebaKeContact()) << "Setting up a new thing:" << thing->name() << thing->params();
if (thing->thingClassId() == wallboxThingClassId) { if (thing->thingClassId() == wallboxThingClassId) {
if (!m_kebaDataLayer){
if(!m_kebaData){ qCDebug(dcKebaKeContact()) << "Creating new Keba data layer...";
qCDebug(dcKebaKeContact()) << "Creating new Keba data layer"; m_kebaDataLayer= new KeContactDataLayer(this);
m_kebaData = new KeContactDataLayer(this); if (!m_kebaDataLayer->init()) {
if (!m_kebaData->init()) { m_kebaDataLayer->deleteLater();
m_kebaData->deleteLater(); m_kebaDataLayer = nullptr;
m_kebaData = nullptr; connect(info, &ThingSetupInfo::aborted, m_kebaDataLayer, &KeContactDataLayer::deleteLater); // Clean up if the setup fails
connect(info, &ThingSetupInfo::aborted, m_kebaData, &KeContactDataLayer::deleteLater); // Clean up if the setup fails
return info->finish(Thing::ThingErrorHardwareNotAvailable, QT_TR_NOOP("Error opening network port.")); return info->finish(Thing::ThingErrorHardwareNotAvailable, QT_TR_NOOP("Error opening network port."));
} }
} }
QHostAddress address = QHostAddress(thing->paramValue(wallboxThingIpAddressParamTypeId).toString()); 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::reachableChanged, this, &IntegrationPluginKeba::onConnectionChanged);
connect(keba, &KeContact::commandExecuted, this, &IntegrationPluginKeba::onCommandExecuted); connect(keba, &KeContact::commandExecuted, this, &IntegrationPluginKeba::onCommandExecuted);
connect(keba, &KeContact::reportTwoReceived, this, &IntegrationPluginKeba::onReportTwoReceived); 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::report1XXReceived, this, &IntegrationPluginKeba::onReport1XXReceived);
connect(keba, &KeContact::broadcastReceived, this, &IntegrationPluginKeba::onBroadcastReceived); connect(keba, &KeContact::broadcastReceived, this, &IntegrationPluginKeba::onBroadcastReceived);
keba->getReport1();
connect(keba, &KeContact::reportOneReceived, info, [info, this, keba] (const KeContact::ReportOne &report) { connect(keba, &KeContact::reportOneReceived, info, [info, this, keba] (const KeContact::ReportOne &report) {
Thing *thing = info->thing(); Thing *thing = info->thing();
@ -145,12 +143,16 @@ void IntegrationPluginKeba::setupThing(ThingSetupInfo *info)
m_kebaDevices.insert(thing->id(), keba); m_kebaDevices.insert(thing->id(), keba);
info->finish(Thing::ThingErrorNoError); info->finish(Thing::ThingErrorNoError);
}); });
keba->getReport1();
connect(info, &ThingSetupInfo::aborted, keba, &KeContact::deleteLater); // Clean up if the setup fails connect(info, &ThingSetupInfo::aborted, keba, &KeContact::deleteLater); // Clean up if the setup fails
connect(keba, &KeContact::destroyed, this, [thing, this]{ connect(keba, &KeContact::destroyed, this, [thing, this]{
m_kebaDevices.remove(thing->id()); m_kebaDevices.remove(thing->id());
}); });
} else { } else {
qCWarning(dcKebaKeContact()) << "setupDevice, unhandled device class" << thing->thingClass(); qCWarning(dcKebaKeContact()) << "Could not setup thing: unhandled device class" << thing->thingClass();
info->finish(Thing::ThingErrorThingClassNotFound); info->finish(Thing::ThingErrorThingClassNotFound);
} }
} }
@ -162,7 +164,7 @@ void IntegrationPluginKeba::postSetupThing(Thing *thing)
qCWarning(dcKebaKeContact()) << "Thing class id not supported" << thing->thingClassId(); qCWarning(dcKebaKeContact()) << "Thing class id not supported" << thing->thingClassId();
return; return;
} }
thing->setStateValue(wallboxConnectedStateTypeId, true);
KeContact *keba = m_kebaDevices.value(thing->id()); KeContact *keba = m_kebaDevices.value(thing->id());
if (!keba) { if (!keba) {
qCWarning(dcKebaKeContact()) << "No Keba connection found for this thing"; qCWarning(dcKebaKeContact()) << "No Keba connection found for this thing";
@ -172,14 +174,14 @@ void IntegrationPluginKeba::postSetupThing(Thing *thing)
keba->getReport3(); 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(); searchNetworkDevices();
} }
if (!m_updateTimer) { if (!m_updateTimer) {
m_updateTimer = hardwareManager()->pluginTimerManager()->registerTimer(60); 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)) { foreach (Thing *thing, myThings().filterByThingClassId(wallboxThingClassId)) {
KeContact *keba = m_kebaDevices.value(thing->id()); KeContact *keba = m_kebaDevices.value(thing->id());
if (!keba) { if (!keba) {
@ -193,13 +195,29 @@ void IntegrationPluginKeba::postSetupThing(Thing *thing)
} }
} }
}); });
m_updateTimer->start();
} }
if (!m_reconnectTimer) { if (!m_reconnectTimer) {
m_reconnectTimer = hardwareManager()->pluginTimerManager()->registerTimer(60*5); m_reconnectTimer = hardwareManager()->pluginTimerManager()->registerTimer(60*5);
connect(m_reconnectTimer, &PluginTimer::timeout, this, [this] { 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()) { if (myThings().empty()) {
qCDebug(dcKebaKeContact()) << "Closing UDP Ports"; qCDebug(dcKebaKeContact()) << "Closing UDP Ports";
m_kebaData->deleteLater(); m_kebaDataLayer->deleteLater();
m_kebaData = nullptr; m_kebaDataLayer= nullptr;
qCDebug(dcKebaKeContact()) << "Stopping plugin timers"; qCDebug(dcKebaKeContact()) << "Stopping plugin timers ...";
hardwareManager()->pluginTimerManager()->unregisterTimer(m_reconnectTimer); if (m_reconnectTimer) {
m_reconnectTimer = nullptr; hardwareManager()->pluginTimerManager()->unregisterTimer(m_reconnectTimer);
hardwareManager()->pluginTimerManager()->unregisterTimer(m_updateTimer); m_reconnectTimer = nullptr;
m_updateTimer = nullptr; }
if (m_updateTimer) {
hardwareManager()->pluginTimerManager()->unregisterTimer(m_updateTimer);
m_updateTimer = nullptr;
}
} }
} }
@ -294,6 +317,7 @@ void IntegrationPluginKeba::searchNetworkDevices()
existingThing->setParamValue(wallboxThingMacAddressParamTypeId, networkDeviceInfo.macAddress()); existingThing->setParamValue(wallboxThingMacAddressParamTypeId, networkDeviceInfo.macAddress());
} }
} else if (existingThing->paramValue(wallboxThingMacAddressParamTypeId).toString() == 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()) { 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(dcKebaKeContact()) << "Keba Wallbox IP Address has changed, from" << existingThing->paramValue(wallboxThingIpAddressParamTypeId).toString() << "to" << networkDeviceInfo.address().toString();
existingThing->setParamValue(wallboxThingIpAddressParamTypeId, 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"; qCWarning(dcKebaKeContact()) << "On connection changed: missing device object";
return; return;
} }
thing->setStateValue(wallboxConnectedStateTypeId, status); thing->setStateValue(wallboxConnectedStateTypeId, status);
if (!status) { if (!status) {
searchNetworkDevices(); searchNetworkDevices();
@ -339,6 +364,7 @@ void IntegrationPluginKeba::onCommandExecuted(QUuid requestId, bool success)
qCWarning(dcKebaKeContact()) << "On command executed: missing device object"; qCWarning(dcKebaKeContact()) << "On command executed: missing device object";
return; return;
} }
ThingActionInfo *info = m_asyncActions.take(requestId); ThingActionInfo *info = m_asyncActions.take(requestId);
if (success) { if (success) {
info->finish(Thing::ThingErrorNoError); info->finish(Thing::ThingErrorNoError);
@ -536,7 +562,7 @@ void IntegrationPluginKeba::executeAction(ThingActionInfo *info)
QUuid requestId; QUuid requestId;
if(action.actionTypeId() == wallboxMaxChargingCurrentActionTypeId){ if(action.actionTypeId() == wallboxMaxChargingCurrentActionTypeId){
int milliAmpere = action.param(wallboxMaxChargingCurrentActionMaxChargingCurrentParamTypeId).value().toDouble()*1000; int milliAmpere = action.param(wallboxMaxChargingCurrentActionMaxChargingCurrentParamTypeId).value().toDouble() * 1000;
requestId = keba->setMaxAmpere(milliAmpere); requestId = keba->setMaxAmpere(milliAmpere);
} else if(action.actionTypeId() == wallboxPowerActionTypeId){ } else if(action.actionTypeId() == wallboxPowerActionTypeId){
@ -558,8 +584,15 @@ void IntegrationPluginKeba::executeAction(ThingActionInfo *info)
qCWarning(dcKebaKeContact()) << "Unhandled ActionTypeId:" << action.actionTypeId(); qCWarning(dcKebaKeContact()) << "Unhandled ActionTypeId:" << action.actionTypeId();
return info->finish(Thing::ThingErrorActionTypeNotFound); 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); 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 { } else {
qCWarning(dcKebaKeContact()) << "Execute action, unhandled device class" << thing->thingClass(); qCWarning(dcKebaKeContact()) << "Execute action, unhandled device class" << thing->thingClass();
info->finish(Thing::ThingErrorThingClassNotFound); info->finish(Thing::ThingErrorThingClassNotFound);

View File

@ -52,6 +52,7 @@ public:
explicit IntegrationPluginKeba(); explicit IntegrationPluginKeba();
void init() override; void init() override;
void discoverThings(ThingDiscoveryInfo *info) override; void discoverThings(ThingDiscoveryInfo *info) override;
void setupThing(ThingSetupInfo *info) override; void setupThing(ThingSetupInfo *info) override;
@ -64,7 +65,7 @@ private:
PluginTimer *m_updateTimer = nullptr; PluginTimer *m_updateTimer = nullptr;
PluginTimer *m_reconnectTimer = nullptr; PluginTimer *m_reconnectTimer = nullptr;
KeContactDataLayer *m_kebaData = nullptr; KeContactDataLayer *m_kebaDataLayer = nullptr;
QHash<ThingId, KeContact *> m_kebaDevices; QHash<ThingId, KeContact *> m_kebaDevices;
QHash<ThingId, int> m_lastSessionId; QHash<ThingId, int> m_lastSessionId;

View File

@ -143,9 +143,9 @@
"displayNameAction": "Set maximal charging current", "displayNameAction": "Set maximal charging current",
"type": "double", "type": "double",
"unit": "Ampere", "unit": "Ampere",
"defaultValue": 6.00, "defaultValue": 6.0,
"minValue": 6.00, "minValue": 6.0,
"maxValue": 63.00, "maxValue": 32.0,
"writable": true "writable": true
}, },
{ {

View File

@ -1,6 +1,6 @@
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* *
* Copyright 2013 - 2020, nymea GmbH * Copyright 2013 - 2021, nymea GmbH
* Contact: contact@nymea.io * Contact: contact@nymea.io
* *
* This file is part of nymea. * This file is part of nymea.
@ -33,7 +33,6 @@
#include <QJsonDocument> #include <QJsonDocument>
KeContact::KeContact(const QHostAddress &address, KeContactDataLayer *dataLayer, QObject *parent) : KeContact::KeContact(const QHostAddress &address, KeContactDataLayer *dataLayer, QObject *parent) :
QObject(parent), QObject(parent),
m_dataLayer(dataLayer), m_dataLayer(dataLayer),
@ -43,8 +42,9 @@ KeContact::KeContact(const QHostAddress &address, KeContactDataLayer *dataLayer,
m_requestTimeoutTimer = new QTimer(this); m_requestTimeoutTimer = new QTimer(this);
m_requestTimeoutTimer->setSingleShot(true); m_requestTimeoutTimer->setSingleShot(true);
connect(m_requestTimeoutTimer, &QTimer::timeout, this, [this] { 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 // This timer will be started when a request is sent and stopped or resetted when a response has been received
emit reachableChanged(false); setReachable(false);
//Try to send the next command //Try to send the next command
handleNextCommandInQueue(); handleNextCommandInQueue();
m_deviceBlocked = false; m_deviceBlocked = false;
@ -58,16 +58,22 @@ KeContact::~KeContact()
qCDebug(dcKebaKeContact()) << "Deleting KeContact connection for address" << m_address; qCDebug(dcKebaKeContact()) << "Deleting KeContact connection for address" << m_address;
} }
QHostAddress KeContact::address() QHostAddress KeContact::address() const
{ {
return m_address; return m_address;
} }
QUuid KeContact::start(const QByteArray &rfidToken, const QByteArray &rfidClassifier) 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(); QUuid requestId = QUuid::createUuid();
m_pendingRequests.append(requestId); m_pendingRequests.append(requestId);
QByteArray datagram = "start "+rfidToken + " " + rfidClassifier; QByteArray datagram = "start " + rfidToken + " " + rfidClassifier;
qCDebug(dcKebaKeContact()) << "Datagram : " << datagram; qCDebug(dcKebaKeContact()) << "Datagram : " << datagram;
sendCommand(datagram, requestId);; sendCommand(datagram, requestId);;
return requestId; return requestId;
@ -75,9 +81,15 @@ QUuid KeContact::start(const QByteArray &rfidToken, const QByteArray &rfidClassi
QUuid KeContact::stop(const QByteArray &rfidToken) QUuid KeContact::stop(const QByteArray &rfidToken)
{ {
if (!m_dataLayer) {
qCWarning(dcKebaKeContact()) << "UDP socket not initialized";
setReachable(false);
return QUuid();
}
QUuid requestId = QUuid::createUuid(); QUuid requestId = QUuid::createUuid();
m_pendingRequests.append(requestId); m_pendingRequests.append(requestId);
QByteArray datagram = "stop "+rfidToken; QByteArray datagram = "stop " + rfidToken;
qCDebug(dcKebaKeContact()) << "Datagram : " << datagram; qCDebug(dcKebaKeContact()) << "Datagram : " << datagram;
sendCommand(datagram, requestId); sendCommand(datagram, requestId);
return requestId; return requestId;
@ -85,10 +97,17 @@ QUuid KeContact::stop(const QByteArray &rfidToken)
void KeContact::setAddress(const QHostAddress &address) 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; m_address = address;
} }
bool KeContact::reachable() const
{
return m_reachable;
}
void KeContact::sendCommand(const QByteArray &command, const QUuid &requestId) 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); emit commandExecuted(requestId, false);
} }
}); });
sendCommand(command); sendCommand(command);
} }
@ -105,16 +125,16 @@ void KeContact::sendCommand(const QByteArray &command)
{ {
if (!m_dataLayer) { if (!m_dataLayer) {
qCWarning(dcKebaKeContact()) << "UDP socket not initialized"; qCWarning(dcKebaKeContact()) << "UDP socket not initialized";
emit reachableChanged(false); setReachable(false);
return; return;
} }
if(m_deviceBlocked) { if (m_deviceBlocked) {
//add command to queue // Add command to queue
m_commandList.append(command); m_commandList.append(command);
} else { } else {
qCDebug(dcKebaKeContact()) << "Writing datagram" << command << m_address; qCDebug(dcKebaKeContact()) << "Writing datagram" << command << m_address;
m_dataLayer->write( m_address, command); m_dataLayer->write(m_address, command);
m_requestTimeoutTimer->start(5000); m_requestTimeoutTimer->start(5000);
m_deviceBlocked = true; m_deviceBlocked = true;
} }
@ -124,13 +144,11 @@ void KeContact::handleNextCommandInQueue()
{ {
if (!m_dataLayer) { if (!m_dataLayer) {
qCWarning(dcKebaKeContact()) << "Data layer not initialized"; qCWarning(dcKebaKeContact()) << "Data layer not initialized";
if (m_reachable == true) { setReachable(false);
m_reachable = false;
emit reachableChanged(false);
}
return; 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()) { if (!m_commandList.isEmpty()) {
QByteArray command = m_commandList.takeFirst(); QByteArray command = m_commandList.takeFirst();
qCDebug(dcKebaKeContact()) << "Writing datagram" << command << m_address; 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) QUuid KeContact::enableOutput(bool state)
{ {
if (!m_dataLayer) {
qCWarning(dcKebaKeContact()) << "UDP socket not initialized";
setReachable(false);
return QUuid();
}
QUuid requestId = QUuid::createUuid(); QUuid requestId = QUuid::createUuid();
m_pendingRequests.append(requestId); m_pendingRequests.append(requestId);
// Print information that we are executing now the update action; // Print information that we are executing now the update action;
QByteArray datagram; QByteArray datagram;
if(state){ if (state){
datagram.append("ena 1"); datagram.append("ena 1");
} else{ } else{
datagram.append("ena 0"); datagram.append("ena 0");
} }
qCDebug(dcKebaKeContact()) << "Enable output, command:" << datagram; qCDebug(dcKebaKeContact()) << "Enable output, command:" << datagram;
sendCommand(datagram, requestId); sendCommand(datagram, requestId);
return requestId; return requestId;
@ -158,16 +197,23 @@ QUuid KeContact::enableOutput(bool state)
QUuid KeContact::setMaxAmpere(int milliAmpere) QUuid KeContact::setMaxAmpere(int milliAmpere)
{ {
if (!m_dataLayer) {
qCWarning(dcKebaKeContact()) << "UDP socket not initialized";
setReachable(false);
return QUuid();
}
if (milliAmpere < 6000 || milliAmpere > 63000) { if (milliAmpere < 6000 || milliAmpere > 63000) {
qCWarning(dcKebaKeContact()) << "KeContact: Set max ampere, mA out of range [6000, 63000]" << milliAmpere; qCWarning(dcKebaKeContact()) << "KeContact: Set max ampere, mA out of range [6000, 63000]" << milliAmpere;
return ""; return QUuid();
} }
QUuid requestId = QUuid::createUuid(); QUuid requestId = QUuid::createUuid();
m_pendingRequests.append(requestId); m_pendingRequests.append(requestId);
// Print information that we are executing now the update action // Print information that we are executing now the update action
qCDebug(dcKebaKeContact()) << "Update max current to : " << milliAmpere; qCDebug(dcKebaKeContact()) << "Update max current to : " << milliAmpere;
QByteArray data; QString commandLine = QString("currtime %1 %2").arg(milliAmpere, 1);
data.append("curr " + QVariant(milliAmpere).toByteArray()); QByteArray data = commandLine.toUtf8();
qCDebug(dcKebaKeContact()) << "Set max. ampere, command: " << data; qCDebug(dcKebaKeContact()) << "Set max. ampere, command: " << data;
sendCommand(data, requestId); sendCommand(data, requestId);
return requestId; return requestId;
@ -175,6 +221,12 @@ QUuid KeContact::setMaxAmpere(int milliAmpere)
QUuid KeContact::displayMessage(const QByteArray &message) 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 /* Text shown on the display. Maximum 23 ASCII characters can be used. 0 .. 23 characters
~ == Σ ~ == Σ
$ == blank $ == blank
@ -197,6 +249,12 @@ QUuid KeContact::displayMessage(const QByteArray &message)
QUuid KeContact::chargeWithEnergyLimit(double energy) QUuid KeContact::chargeWithEnergyLimit(double energy)
{ {
if (!m_dataLayer) {
qCWarning(dcKebaKeContact()) << "UDP socket not initialized";
setReachable(false);
return QUuid();
}
QUuid requestId = QUuid::createUuid(); QUuid requestId = QUuid::createUuid();
m_pendingRequests.append(requestId); m_pendingRequests.append(requestId);
@ -209,6 +267,12 @@ QUuid KeContact::chargeWithEnergyLimit(double energy)
QUuid KeContact::setFailsafe(int timeout, int current, bool save) 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(); QUuid requestId = QUuid::createUuid();
m_pendingRequests.append(requestId); m_pendingRequests.append(requestId);
@ -222,7 +286,6 @@ QUuid KeContact::setFailsafe(int timeout, int current, bool save)
return requestId; return requestId;
} }
void KeContact::getDeviceInformation() void KeContact::getDeviceInformation()
{ {
QByteArray data; QByteArray data;
@ -253,6 +316,12 @@ void KeContact::getReport1XX(int reportNumber)
QUuid KeContact::setOutputX2(bool state) QUuid KeContact::setOutputX2(bool state)
{ {
if (!m_dataLayer) {
qCWarning(dcKebaKeContact()) << "UDP socket not initialized";
setReachable(false);
return QUuid();
}
QUuid requestId = QUuid::createUuid(); QUuid requestId = QUuid::createUuid();
m_pendingRequests.append(requestId); m_pendingRequests.append(requestId);
QByteArray data; QByteArray data;
@ -272,6 +341,12 @@ void KeContact::getReport(int reportNumber)
QUuid KeContact::unlockCharger() QUuid KeContact::unlockCharger()
{ {
if (!m_dataLayer) {
qCWarning(dcKebaKeContact()) << "UDP socket not initialized";
setReachable(false);
return QUuid();
}
QUuid requestId = QUuid::createUuid(); QUuid requestId = QUuid::createUuid();
m_pendingRequests.append(requestId); m_pendingRequests.append(requestId);
QByteArray data; QByteArray data;
@ -283,11 +358,14 @@ QUuid KeContact::unlockCharger()
void KeContact::onReceivedDatagram(const QHostAddress &address, const QByteArray &datagram) void KeContact::onReceivedDatagram(const QHostAddress &address, const QByteArray &datagram)
{ {
// Make sure the datagram is for this keba
if (address != m_address) { if (address != m_address) {
return; 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 //Command response has been received, now send the next command
m_deviceBlocked = false; m_deviceBlocked = false;
@ -304,7 +382,10 @@ void KeContact::onReceivedDatagram(const QHostAddress &address, const QByteArray
} else { } else {
//Probably the response has taken too long and the requestId has been already removed //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 //Command response has been received, now send the next command
m_deviceBlocked = false; m_deviceBlocked = false;
@ -328,13 +409,17 @@ void KeContact::onReceivedDatagram(const QHostAddress &address, const QByteArray
QJsonDocument jsonDoc = QJsonDocument::fromJson(datagram, &error); QJsonDocument jsonDoc = QJsonDocument::fromJson(datagram, &error);
if (error.error != QJsonParseError::NoError) { if (error.error != QJsonParseError::NoError) {
qCWarning(dcKebaKeContact()) << "Failed to parse JSON data" << datagram << ":" << error.errorString(); qCWarning(dcKebaKeContact()) << "Failed to parse JSON data" << datagram << ":" << error.errorString();
return;
} }
QVariantMap data = jsonDoc.toVariant().toMap(); QVariantMap data = jsonDoc.toVariant().toMap();
if(data.contains("ID")) { if (data.contains("ID")) {
int id = data.value("ID").toInt(); int id = data.value("ID").toInt();
if (id == 1) { if (id == 1) {
// We received valid data from the address over the data link, so the wallbox must be reachable
setReachable(true);
ReportOne reportOne; ReportOne reportOne;
qCDebug(dcKebaKeContact()) << "Report 1 received"; qCDebug(dcKebaKeContact()) << "Report 1 received";
reportOne.product = data.value("Product").toString(); reportOne.product = data.value("Product").toString();
@ -357,6 +442,8 @@ void KeContact::onReceivedDatagram(const QHostAddress &address, const QByteArray
emit reportOneReceived(reportOne); emit reportOneReceived(reportOne);
} else if (id == 2) { } 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; ReportTwo reportTwo;
qCDebug(dcKebaKeContact()) << "Report 2 received"; qCDebug(dcKebaKeContact()) << "Report 2 received";
@ -384,6 +471,8 @@ void KeContact::onReceivedDatagram(const QHostAddress &address, const QByteArray
emit reportTwoReceived(reportTwo); emit reportTwoReceived(reportTwo);
} else if (id == 3) { } 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; ReportThree reportThree;
qCDebug(dcKebaKeContact()) << "Report 3 received"; qCDebug(dcKebaKeContact()) << "Report 3 received";
@ -401,6 +490,8 @@ void KeContact::onReceivedDatagram(const QHostAddress &address, const QByteArray
reportThree.seconds = data.value("Sec").toInt(); reportThree.seconds = data.value("Sec").toInt();
emit reportThreeReceived(reportThree); emit reportThreeReceived(reportThree);
} else if (id >= 100) { } 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; Report1XX report;
qCDebug(dcKebaKeContact()) << "Report" << id << "received"; qCDebug(dcKebaKeContact()) << "Report" << id << "received";
@ -419,21 +510,33 @@ void KeContact::onReceivedDatagram(const QHostAddress &address, const QByteArray
} }
} else { } else {
if (data.contains("State")) { 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")); emit broadcastReceived(BroadcastType::BroadcastTypeState, data.value("State"));
} }
if (data.contains("Plug")) { 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")); emit broadcastReceived(BroadcastType::BroadcastTypePlug, data.value("Plug"));
} }
if (data.contains("Input")) { 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")); emit broadcastReceived(BroadcastType::BroadcastTypeInput, data.value("Input"));
} }
if (data.contains("Enable sys")) { 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")); emit broadcastReceived(BroadcastType::BroadcastTypeEnableSys, data.value("Enable sys"));
} }
if (data.contains("Max curr")) { 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")); emit broadcastReceived(BroadcastType::BroadcastTypeMaxCurr, data.value("Max curr"));
} }
if (data.contains("E pres")) { 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")); emit broadcastReceived(BroadcastType::BroadcastTypeEPres, data.value("E pres"));
} }
} }

View File

@ -1,6 +1,6 @@
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* *
* Copyright 2013 - 2020, nymea GmbH * Copyright 2013 - 2021, nymea GmbH
* Contact: contact@nymea.io * Contact: contact@nymea.io
* *
* This file is part of nymea. * This file is part of nymea.
@ -44,10 +44,6 @@ class KeContact : public QObject
{ {
Q_OBJECT Q_OBJECT
public: public:
explicit KeContact(const QHostAddress &address, KeContactDataLayer *dataLayer, QObject *parent = nullptr);
~KeContact();
bool init();
enum State { enum State {
StateStarting = 0, StateStarting = 0,
StateNotReady, StateNotReady,
@ -136,10 +132,14 @@ public:
int seconds; // current time when the report was generated 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); void setAddress(const QHostAddress &address);
bool reachable(); bool reachable() const;
QUuid start(const QByteArray &rfidToken, const QByteArray &rfidClassifier); // Command “start” QUuid start(const QByteArray &rfidToken, const QByteArray &rfidClassifier); // Command “start”
QUuid stop(const QByteArray &rfidToken); // Command “stop” QUuid stop(const QByteArray &rfidToken); // Command “stop”
@ -161,7 +161,7 @@ public:
QUuid setOutputX2(bool state); // Command “output” QUuid setOutputX2(bool state); // Command “output”
private: private:
KeContactDataLayer *m_dataLayer; KeContactDataLayer *m_dataLayer = nullptr;
bool m_reachable = false; bool m_reachable = false;
QHostAddress m_address; QHostAddress m_address;
@ -169,7 +169,7 @@ private:
bool m_deviceBlocked = false; bool m_deviceBlocked = false;
QTimer *m_requestTimeoutTimer = nullptr; QTimer *m_requestTimeoutTimer = nullptr;
int m_serialNumber; int m_serialNumber = 0;
QList<QUuid> m_pendingRequests; QList<QUuid> m_pendingRequests;
void getReport(int reportNumber); void getReport(int reportNumber);
@ -177,6 +177,8 @@ private:
void sendCommand(const QByteArray &command); void sendCommand(const QByteArray &command);
void handleNextCommandInQueue(); void handleNextCommandInQueue();
void setReachable(bool reachable);
signals: signals:
void reachableChanged(bool status); void reachableChanged(bool status);
void commandExecuted(QUuid requestId, bool success); void commandExecuted(QUuid requestId, bool success);
@ -189,6 +191,7 @@ signals:
private slots: private slots:
void onReceivedDatagram(const QHostAddress &address, const QByteArray &datagram); void onReceivedDatagram(const QHostAddress &address, const QByteArray &datagram);
}; };
#endif // KECONTACT_H #endif // KECONTACT_H

View File

@ -1,6 +1,6 @@
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* *
* Copyright 2013 - 2020, nymea GmbH * Copyright 2013 - 2021, nymea GmbH
* Contact: contact@nymea.io * Contact: contact@nymea.io
* *
* This file is part of nymea. * This file is part of nymea.
@ -47,13 +47,23 @@ KeContactDataLayer::~KeContactDataLayer()
bool KeContactDataLayer::init() bool KeContactDataLayer::init()
{ {
m_udpSocket->close();
m_initialized = false;
if (!m_udpSocket->bind(QHostAddress::AnyIPv4, m_port, QAbstractSocket::ShareAddress)) { if (!m_udpSocket->bind(QHostAddress::AnyIPv4, m_port, QAbstractSocket::ShareAddress)) {
qCWarning(dcKebaKeContact()) << "KeContactDataLayer: Cannot bind to port" << m_port; qCWarning(dcKebaKeContact()) << "KeContactDataLayer: Cannot bind to port" << m_port;
return false; return false;
} }
m_initialized = true;
return true; return true;
} }
bool KeContactDataLayer::initialized() const
{
return m_initialized;
}
void KeContactDataLayer::write(const QHostAddress &address, const QByteArray &data) void KeContactDataLayer::write(const QHostAddress &address, const QByteArray &data)
{ {
m_udpSocket->writeDatagram(data, address, m_port); m_udpSocket->writeDatagram(data, address, m_port);
@ -68,10 +78,9 @@ void KeContactDataLayer::readPendingDatagrams()
quint16 senderPort; quint16 senderPort;
while (socket->hasPendingDatagrams()) { while (socket->hasPendingDatagrams()) {
datagram.resize(socket->pendingDatagramSize()); datagram.resize(socket->pendingDatagramSize());
socket->readDatagram(datagram.data(), datagram.size(), &senderAddress, &senderPort); 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); emit datagramReceived(senderAddress, datagram);
} }
} }

View File

@ -1,6 +1,6 @@
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* *
* Copyright 2013 - 2020, nymea GmbH * Copyright 2013 - 2021, nymea GmbH
* Contact: contact@nymea.io * Contact: contact@nymea.io
* *
* This file is part of nymea. * This file is part of nymea.
@ -40,11 +40,14 @@ class KeContactDataLayer : public QObject
public: public:
explicit KeContactDataLayer(QObject *parent = nullptr); explicit KeContactDataLayer(QObject *parent = nullptr);
~KeContactDataLayer(); ~KeContactDataLayer();
bool init(); bool init();
bool initialized() const;
void write(const QHostAddress &address, const QByteArray &data); void write(const QHostAddress &address, const QByteArray &data);
private: private:
bool m_initialized = false;
int m_port = 7090; int m_port = 7090;
QUdpSocket *m_udpSocket = nullptr; QUdpSocket *m_udpSocket = nullptr;
@ -55,6 +58,7 @@ private slots:
void readPendingDatagrams(); void readPendingDatagrams();
void onSocketError(QAbstractSocket::SocketError error); void onSocketError(QAbstractSocket::SocketError error);
void onSocketStateChanged(QAbstractSocket::SocketState socketState); void onSocketStateChanged(QAbstractSocket::SocketState socketState);
}; };
#endif // KECONTACTDATALAYER_H #endif // KECONTACTDATALAYER_H