Merge PR #26: Update plugins to make use of the nymea internal network discovery

This commit is contained in:
Jenkins nymea 2021-06-30 12:44:12 +02:00
commit 2cfaf28bb7
27 changed files with 342 additions and 1228 deletions

View File

@ -1,272 +0,0 @@
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*
* Copyright 2013 - 2020, nymea GmbH
* Contact: contact@nymea.io
*
* This file is part of nymea.
* This project including source code and documentation is protected by
* copyright law, and remains the property of nymea GmbH. All rights, including
* reproduction, publication, editing and translation, are reserved. The use of
* this project is subject to the terms of a license agreement to be concluded
* with nymea GmbH in accordance with the terms of use of nymea GmbH, available
* under https://nymea.io/license
*
* GNU Lesser General Public License Usage
* Alternatively, this project may be redistributed and/or modified under the
* terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; version 3. This project is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this project. If not, see <https://www.gnu.org/licenses/>.
*
* For any further details and any questions please contact us under
* contact@nymea.io or see our FAQ/Licensing Information on
* https://nymea.io/license/faq
*
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
#include "discovery.h"
#include <QDebug>
#include <QXmlStreamReader>
#include <QNetworkInterface>
#include <QHostInfo>
#include <QTimer>
#include <loggingcategories.h>
NYMEA_LOGGING_CATEGORY(dcDiscovery, "Discovery")
Discovery::Discovery(QObject *parent) : QObject(parent)
{
connect(&m_timeoutTimer, &QTimer::timeout, this, &Discovery::onTimeout);
}
void Discovery::discoverHosts(int timeout)
{
if (isRunning()) {
qCWarning(dcDiscovery()) << "Discovery already running. Cannot start twice.";
return;
}
m_timeoutTimer.start(timeout * 1000);
foreach (const QString &target, getDefaultTargets()) {
QProcess *discoveryProcess = new QProcess(this);
m_discoveryProcesses.append(discoveryProcess);
connect(discoveryProcess, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(discoveryFinished(int,QProcess::ExitStatus)));
QStringList arguments;
arguments << "-oX" << "-" << "-n" << "-sn";
arguments << target;
qCDebug(dcDiscovery()) << "Scanning network:" << "nmap" << arguments.join(" ");
discoveryProcess->start(QStringLiteral("nmap"), arguments);
}
}
void Discovery::abort()
{
foreach (QProcess *discoveryProcess, m_discoveryProcesses) {
if (discoveryProcess->state() == QProcess::Running) {
qCDebug(dcDiscovery()) << "Kill running discovery process";
discoveryProcess->terminate();
discoveryProcess->waitForFinished(5000);
}
}
foreach (QProcess *p, m_pendingArpLookups.keys()) {
p->terminate();
delete p;
}
m_pendingArpLookups.clear();
m_pendingNameLookups.clear();
qDeleteAll(m_scanResults);
m_scanResults.clear();
}
bool Discovery::isRunning() const
{
return !m_discoveryProcesses.isEmpty() || !m_pendingArpLookups.isEmpty() || !m_pendingNameLookups.isEmpty();
}
void Discovery::discoveryFinished(int exitCode, QProcess::ExitStatus exitStatus)
{
QProcess *discoveryProcess = static_cast<QProcess*>(sender());
if (exitCode != 0 || exitStatus != QProcess::NormalExit) {
qCWarning(dcDiscovery()) << "Nmap error failed. Is nmap installed correctly?";
m_discoveryProcesses.removeAll(discoveryProcess);
discoveryProcess->deleteLater();
discoveryProcess = nullptr;
finishDiscovery();
return;
}
QByteArray data = discoveryProcess->readAll();
m_discoveryProcesses.removeAll(discoveryProcess);
discoveryProcess->deleteLater();
discoveryProcess = nullptr;
QXmlStreamReader reader(data);
int foundHosts = 0;
qCDebug(dcDiscovery()) << "nmap finished network discovery:";
while (!reader.atEnd() && !reader.hasError()) {
QXmlStreamReader::TokenType token = reader.readNext();
if(token == QXmlStreamReader::StartDocument)
continue;
if(token == QXmlStreamReader::StartElement && reader.name() == "host") {
bool isUp = false;
QString address;
QString macAddress;
QString vendor;
while (!reader.atEnd() && !reader.hasError() && !(token == QXmlStreamReader::EndElement && reader.name() == "host")) {
token = reader.readNext();
if (reader.name() == "address") {
QString addr = reader.attributes().value("addr").toString();
QString type = reader.attributes().value("addrtype").toString();
if (type == "ipv4" && !addr.isEmpty()) {
address = addr;
} else if (type == "mac") {
macAddress = addr;
vendor = reader.attributes().value("vendor").toString();
}
}
if (reader.name() == "status") {
QString state = reader.attributes().value("state").toString();
if (!state.isEmpty())
isUp = state == "up";
}
}
if (isUp) {
foundHosts++;
qCDebug(dcDiscovery()) << " - host:" << address;
Host *host = new Host();
host->setAddress(address);
if (!macAddress.isEmpty()) {
host->setMacAddress(macAddress);
} else {
QProcess *arpLookup = new QProcess(this);
m_pendingArpLookups.insert(arpLookup, host);
connect(arpLookup, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(arpLookupDone(int,QProcess::ExitStatus)));
arpLookup->start("arp", {"-vn"});
}
host->setHostName(vendor);
QHostInfo::lookupHost(address, this, SLOT(hostLookupDone(QHostInfo)));
m_pendingNameLookups.insert(address, host);
m_scanResults.append(host);
}
}
}
if (foundHosts == 0 && m_discoveryProcesses.isEmpty()) {
qCDebug(dcDiscovery()) << "Network scan successful but no hosts found in this network";
finishDiscovery();
}
}
void Discovery::hostLookupDone(const QHostInfo &info)
{
Host *host = m_pendingNameLookups.take(info.addresses().first().toString());
if (!host) {
// Probably aborted...
return;
}
if (info.error() != QHostInfo::NoError) {
qWarning(dcDiscovery()) << "Host lookup failed:" << info.errorString();
}
if (host->hostName().isEmpty() || info.hostName() != host->address()) {
host->setHostName(info.hostName());
}
finishDiscovery();
}
void Discovery::arpLookupDone(int exitCode, QProcess::ExitStatus exitStatus)
{
QProcess *p = static_cast<QProcess*>(sender());
p->deleteLater();
Host *host = m_pendingArpLookups.take(p);
if (exitCode != 0 || exitStatus != QProcess::NormalExit) {
qCWarning(dcDiscovery()) << "ARP lookup process failed for host" << host->address();
finishDiscovery();
return;
}
QString data = QString::fromLatin1(p->readAll());
foreach (QString line, data.split('\n')) {
line.replace(QRegExp("[ ]{1,}"), " ");
QStringList parts = line.split(" ");
if (parts.count() >= 3 && parts.first() == host->address() && parts.at(1) == "ether") {
host->setMacAddress(parts.at(2));
break;
}
}
finishDiscovery();
}
void Discovery::onTimeout()
{
qWarning(dcDiscovery()) << "Timeout hit. Stopping discovery";
while (!m_discoveryProcesses.isEmpty()) {
QProcess *discoveryProcess = m_discoveryProcesses.takeFirst();
disconnect(this, SLOT(discoveryFinished(int,QProcess::ExitStatus)));
discoveryProcess->terminate();
delete discoveryProcess;
}
foreach (QProcess *p, m_pendingArpLookups.keys()) {
p->terminate();
m_scanResults.removeAll(m_pendingArpLookups.value(p));
delete p;
}
m_pendingArpLookups.clear();
m_pendingNameLookups.clear();
finishDiscovery();
}
QStringList Discovery::getDefaultTargets()
{
QStringList targets;
foreach (const QHostAddress &interface, QNetworkInterface::allAddresses()) {
if (!interface.isLoopback() && interface.scopeId().isEmpty() && interface.protocol() == QAbstractSocket::IPv4Protocol) {
QPair<QHostAddress, int> pair = QHostAddress::parseSubnet(interface.toString() + "/24");
QString newTarget = QString("%1/%2").arg(pair.first.toString()).arg(pair.second);
if (!targets.contains(newTarget)) {
targets.append(newTarget);
}
}
}
return targets;
}
void Discovery::finishDiscovery()
{
if (m_discoveryProcesses.count() > 0 || m_pendingNameLookups.count() > 0 || m_pendingArpLookups.count() > 0) {
// Still busy...
return;
}
QList<Host> hosts;
foreach (Host *host, m_scanResults) {
if (!host->macAddress().isEmpty()) {
hosts.append(*host);
}
}
qDeleteAll(m_scanResults);
m_scanResults.clear();
qCDebug(dcDiscovery()) << "Found" << hosts.count() << "network devices";
m_timeoutTimer.stop();
emit finished(hosts);
}

View File

@ -1,75 +0,0 @@
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*
* Copyright 2013 - 2020, nymea GmbH
* Contact: contact@nymea.io
*
* This file is part of nymea.
* This project including source code and documentation is protected by
* copyright law, and remains the property of nymea GmbH. All rights, including
* reproduction, publication, editing and translation, are reserved. The use of
* this project is subject to the terms of a license agreement to be concluded
* with nymea GmbH in accordance with the terms of use of nymea GmbH, available
* under https://nymea.io/license
*
* GNU Lesser General Public License Usage
* Alternatively, this project may be redistributed and/or modified under the
* terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; version 3. This project is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this project. If not, see <https://www.gnu.org/licenses/>.
*
* For any further details and any questions please contact us under
* contact@nymea.io or see our FAQ/Licensing Information on
* https://nymea.io/license/faq
*
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
#ifndef DISCOVERY_H
#define DISCOVERY_H
#include <QObject>
#include <QProcess>
#include <QHostInfo>
#include <QTimer>
#include "host.h"
class Discovery : public QObject
{
Q_OBJECT
public:
explicit Discovery(QObject *parent = nullptr);
void discoverHosts(int timeout);
void abort();
bool isRunning() const;
signals:
void finished(const QList<Host> &hosts);
private:
QStringList getDefaultTargets();
void finishDiscovery();
private slots:
void discoveryFinished(int exitCode, QProcess::ExitStatus exitStatus);
void hostLookupDone(const QHostInfo &info);
void arpLookupDone(int exitCode, QProcess::ExitStatus exitStatus);
void onTimeout();
private:
QList<QProcess*> m_discoveryProcesses;
QTimer m_timeoutTimer;
QHash<QProcess*, Host*> m_pendingArpLookups;
QHash<QString, Host*> m_pendingNameLookups;
QList<Host*> m_scanResults;
};
#endif // DISCOVERY_H

View File

@ -1,94 +0,0 @@
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*
* Copyright 2013 - 2020, nymea GmbH
* Contact: contact@nymea.io
*
* This file is part of nymea.
* This project including source code and documentation is protected by
* copyright law, and remains the property of nymea GmbH. All rights, including
* reproduction, publication, editing and translation, are reserved. The use of
* this project is subject to the terms of a license agreement to be concluded
* with nymea GmbH in accordance with the terms of use of nymea GmbH, available
* under https://nymea.io/license
*
* GNU Lesser General Public License Usage
* Alternatively, this project may be redistributed and/or modified under the
* terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; version 3. This project is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this project. If not, see <https://www.gnu.org/licenses/>.
*
* For any further details and any questions please contact us under
* contact@nymea.io or see our FAQ/Licensing Information on
* https://nymea.io/license/faq
*
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
#include "host.h"
Host::Host()
{
qRegisterMetaType<Host>();
qRegisterMetaType<QList<Host> >();
}
QString Host::macAddress() const
{
return m_macAddress;
}
void Host::setMacAddress(const QString &macAddress)
{
m_macAddress = macAddress;
}
QString Host::hostName() const
{
return m_hostName;
}
void Host::setHostName(const QString &hostName)
{
m_hostName = hostName;
}
QString Host::address() const
{
return m_address;
}
void Host::setAddress(const QString &address)
{
m_address = address;
}
void Host::seen()
{
m_lastSeenTime = QDateTime::currentDateTime();
}
QDateTime Host::lastSeenTime() const
{
return m_lastSeenTime;
}
bool Host::reachable() const
{
return m_reachable;
}
void Host::setReachable(bool reachable)
{
m_reachable = reachable;
}
QDebug operator<<(QDebug dbg, const Host &host)
{
dbg.nospace() << "Host(" << host.macAddress() << "," << host.hostName() << ", " << host.address() << ", " << (host.reachable() ? "up" : "down") << ")";
return dbg.space();
}

View File

@ -1,70 +0,0 @@
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*
* Copyright 2013 - 2020, nymea GmbH
* Contact: contact@nymea.io
*
* This file is part of nymea.
* This project including source code and documentation is protected by
* copyright law, and remains the property of nymea GmbH. All rights, including
* reproduction, publication, editing and translation, are reserved. The use of
* this project is subject to the terms of a license agreement to be concluded
* with nymea GmbH in accordance with the terms of use of nymea GmbH, available
* under https://nymea.io/license
*
* GNU Lesser General Public License Usage
* Alternatively, this project may be redistributed and/or modified under the
* terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; version 3. This project is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this project. If not, see <https://www.gnu.org/licenses/>.
*
* For any further details and any questions please contact us under
* contact@nymea.io or see our FAQ/Licensing Information on
* https://nymea.io/license/faq
*
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
#ifndef HOST_H
#define HOST_H
#include <QString>
#include <QDebug>
#include <QDateTime>
class Host
{
public:
Host();
QString macAddress() const;
void setMacAddress(const QString &macAddress);
QString hostName() const;
void setHostName(const QString &hostName);
QString address() const;
void setAddress(const QString &address);
void seen();
QDateTime lastSeenTime() const;
bool reachable() const;
void setReachable(bool reachable);
private:
QString m_macAddress;
QString m_hostName;
QString m_address;
QDateTime m_lastSeenTime;
bool m_reachable;
};
Q_DECLARE_METATYPE(Host)
QDebug operator<<(QDebug dbg, const Host &host);
#endif // HOST_H

View File

@ -40,14 +40,10 @@ Idm::Idm(const QHostAddress &address, QObject *parent) :
{ {
qCDebug(dcIdm()) << "iDM: Creating iDM connection" << m_hostAddress.toString(); qCDebug(dcIdm()) << "iDM: Creating iDM connection" << m_hostAddress.toString();
m_modbusMaster = new ModbusTCPMaster(address, 502, this); m_modbusMaster = new ModbusTCPMaster(address, 502, this);
connect(m_modbusMaster, &ModbusTCPMaster::receivedHoldingRegister, this, &Idm::onReceivedHoldingRegister);
if (m_modbusMaster) { connect(m_modbusMaster, &ModbusTCPMaster::readRequestError, this, &Idm::onModbusError);
qCDebug(dcIdm()) << "iDM: Created ModbusTCPMaster"; connect(m_modbusMaster, &ModbusTCPMaster::writeRequestError, this, &Idm::onModbusError);
connect(m_modbusMaster, &ModbusTCPMaster::receivedHoldingRegister, this, &Idm::onReceivedHoldingRegister); connect(m_modbusMaster, &ModbusTCPMaster::writeRequestExecuted, this, &Idm::writeRequestExecuted);
connect(m_modbusMaster, &ModbusTCPMaster::readRequestError, this, &Idm::onModbusError);
connect(m_modbusMaster, &ModbusTCPMaster::writeRequestError, this, &Idm::onModbusError);
connect(m_modbusMaster, &ModbusTCPMaster::writeRequestExecuted, this, &Idm::writeRequestExecuted);
}
} }
Idm::~Idm() Idm::~Idm()
@ -61,21 +57,21 @@ bool Idm::connectDevice()
return m_modbusMaster->connectDevice(); return m_modbusMaster->connectDevice();
} }
QHostAddress Idm::getIdmAddress() const QHostAddress Idm::address() const
{ {
return m_hostAddress; return m_hostAddress;
} }
void Idm::getStatus() void Idm::getStatus()
{ {
//this request starts an update cycle // This request starts an update cycle
m_modbusMaster->readHoldingRegister(Idm::modbusUnitID, Idm::OutsideTemperature, 2); m_modbusMaster->readHoldingRegister(Idm::modbusUnitID, Idm::OutsideTemperature, 2);
} }
QUuid Idm::setTargetTemperature(double targetTemperature) QUuid Idm::setTargetTemperature(double targetTemperature)
{ {
QVector<uint16_t> value = ModbusHelpers::convertFloatToRegister(targetTemperature); QVector<uint16_t> value = ModbusHelpers::convertFloatToRegister(targetTemperature);
return m_modbusMaster->writeHoldingRegisters(Idm::modbusUnitID, Idm::RegisterList::RoomTemperatureTargetHeatingEcoHKA, value); return m_modbusMaster->writeHoldingRegisters(Idm::modbusUnitID, Idm::RegisterList::RoomTemperatureTargetHeatingEcoHKA, value);
} }
void Idm::onReceivedHoldingRegister(int slaveAddress, int modbusRegister, const QVector<quint16> &value) void Idm::onReceivedHoldingRegister(int slaveAddress, int modbusRegister, const QVector<quint16> &value)

View File

@ -72,7 +72,7 @@ public:
~Idm(); ~Idm();
bool connectDevice(); bool connectDevice();
QHostAddress getIdmAddress() const; QHostAddress address() const;
QUuid setTargetTemperature(double targetTemperature); QUuid setTargetTemperature(double targetTemperature);
void getStatus(); void getStatus();

View File

@ -28,6 +28,7 @@
* *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
#include "network/networkdevicediscovery.h"
#include "integrationpluginidm.h" #include "integrationpluginidm.h"
#include "plugininfo.h" #include "plugininfo.h"
@ -36,6 +37,54 @@ IntegrationPluginIdm::IntegrationPluginIdm()
} }
void IntegrationPluginIdm::discoverThings(ThingDiscoveryInfo *info)
{
if (!hardwareManager()->networkDeviceDiscovery()->available()) {
qCWarning(dcIdm()) << "Failed to discover network devices. The network device discovery is not available.";
info->finish(Thing::ThingErrorHardwareNotAvailable, QT_TR_NOOP("The discovery is not available."));
return;
}
qCDebug(dcIdm()) << "Discovering network...";
NetworkDeviceDiscoveryReply *discoveryReply = hardwareManager()->networkDeviceDiscovery()->discover();
connect(discoveryReply, &NetworkDeviceDiscoveryReply::finished, this, [=](){
ThingDescriptors descriptors;
qCDebug(dcIdm()) << "Discovery finished. Found" << discoveryReply->networkDeviceInfos().count() << "devices";
foreach (const NetworkDeviceInfo &networkDeviceInfo, discoveryReply->networkDeviceInfos()) {
qCDebug(dcIdm()) << networkDeviceInfo;
QString title;
if (networkDeviceInfo.hostName().isEmpty()) {
title += networkDeviceInfo.address().toString();
} else {
title += networkDeviceInfo.address().toString() + " (" + networkDeviceInfo.hostName() + ")";
}
QString description;
if (networkDeviceInfo.macAddressManufacturer().isEmpty()) {
description = networkDeviceInfo.macAddress();
} else {
description = networkDeviceInfo.macAddress() + " (" + networkDeviceInfo.macAddressManufacturer() + ")";
}
ThingDescriptor descriptor(navigator2ThingClassId, title, description);
// Check if we already have set up this device
Things existingThings = myThings().filterByParam(navigator2ThingMacAddressParamTypeId, networkDeviceInfo.macAddress());
if (existingThings.count() == 1) {
qCDebug(dcIdm()) << "This thing already exists in the system." << existingThings.first() << networkDeviceInfo;
descriptor.setThingId(existingThings.first()->id());
}
ParamList params;
params << Param(navigator2ThingMacAddressParamTypeId, networkDeviceInfo.macAddress());
params << Param(navigator2ThingIpAddressParamTypeId, networkDeviceInfo.address().toString());
descriptor.setParams(params);
info->addThingDescriptor(descriptor);
}
info->finish(Thing::ThingErrorNoError);
});
}
void IntegrationPluginIdm::setupThing(ThingSetupInfo *info) void IntegrationPluginIdm::setupThing(ThingSetupInfo *info)
{ {
Thing *thing = info->thing(); Thing *thing = info->thing();
@ -57,8 +106,8 @@ void IntegrationPluginIdm::setupThing(ThingSetupInfo *info)
qCDebug(dcIdm()) << "User entered address: " << hostAddress.toString(); qCDebug(dcIdm()) << "User entered address: " << hostAddress.toString();
/* Check, if address is already in use for another device */ /* Check, if address is already in use for another device */
Q_FOREACH (Idm *idm, m_idmConnections) { foreach (Idm *idm, m_idmConnections) {
if (hostAddress.isEqual(idm->getIdmAddress())) { if (hostAddress.isEqual(idm->address())) {
qCWarning(dcIdm()) << "Address already in use"; qCWarning(dcIdm()) << "Address already in use";
info->finish(Thing::ThingErrorSetupFailed, QT_TR_NOOP("IP address already in use")); info->finish(Thing::ThingErrorSetupFailed, QT_TR_NOOP("IP address already in use"));
return; return;
@ -144,8 +193,7 @@ void IntegrationPluginIdm::executeAction(ThingActionInfo *info)
double targetTemperature = thing->stateValue(navigator2TargetTemperatureStateTypeId).toDouble(); double targetTemperature = thing->stateValue(navigator2TargetTemperatureStateTypeId).toDouble();
QUuid requestId = idm->setTargetTemperature(targetTemperature); QUuid requestId = idm->setTargetTemperature(targetTemperature);
m_asyncActions.insert(requestId, info); m_asyncActions.insert(requestId, info);
connect(info, &ThingActionInfo::aborted, [requestId, this] {m_asyncActions.remove(requestId);}); connect(info, &ThingActionInfo::aborted, [requestId, this] (){ m_asyncActions.remove(requestId); });
} else { } else {
Q_ASSERT_X(false, "executeAction", QString("Unhandled action: %1").arg(action.actionTypeId().toString()).toUtf8()); Q_ASSERT_X(false, "executeAction", QString("Unhandled action: %1").arg(action.actionTypeId().toString()).toUtf8());
} }
@ -158,11 +206,8 @@ void IntegrationPluginIdm::update(Thing *thing)
{ {
if (thing->thingClassId() == navigator2ThingClassId) { if (thing->thingClassId() == navigator2ThingClassId) {
qCDebug(dcIdm()) << "Updating thing" << thing->name(); qCDebug(dcIdm()) << "Updating thing" << thing->name();
Idm *idm = m_idmConnections.value(thing); Idm *idm = m_idmConnections.value(thing);
if (!idm) { if (!idm) { return; };
return;
}
idm->getStatus(); idm->getStatus();
} }
} }
@ -170,7 +215,6 @@ void IntegrationPluginIdm::update(Thing *thing)
void IntegrationPluginIdm::onStatusUpdated(const IdmInfo &info) void IntegrationPluginIdm::onStatusUpdated(const IdmInfo &info)
{ {
qCDebug(dcIdm()) << "Received status from heat pump"; qCDebug(dcIdm()) << "Received status from heat pump";
Idm *idm = qobject_cast<Idm *>(sender()); Idm *idm = qobject_cast<Idm *>(sender());
Thing *thing = m_idmConnections.key(idm); Thing *thing = m_idmConnections.key(idm);
@ -205,8 +249,6 @@ void IntegrationPluginIdm::onWriteRequestExecuted(const QUuid &requestId, bool s
void IntegrationPluginIdm::onRefreshTimer() void IntegrationPluginIdm::onRefreshTimer()
{ {
qCDebug(dcIdm()) << "onRefreshTimer called";
foreach (Thing *thing, myThings().filterByThingClassId(navigator2ThingClassId)) { foreach (Thing *thing, myThings().filterByThingClassId(navigator2ThingClassId)) {
update(thing); update(thing);
} }

View File

@ -33,7 +33,6 @@
#include "integrations/integrationplugin.h" #include "integrations/integrationplugin.h"
#include "plugintimer.h" #include "plugintimer.h"
#include "idm.h" #include "idm.h"
#include <QUuid> #include <QUuid>
@ -48,6 +47,7 @@ class IntegrationPluginIdm: public IntegrationPlugin
public: public:
explicit IntegrationPluginIdm(); explicit IntegrationPluginIdm();
void discoverThings(ThingDiscoveryInfo *info) override;
void setupThing(ThingSetupInfo *info) override; void setupThing(ThingSetupInfo *info) override;
void postSetupThing(Thing *thing) override; void postSetupThing(Thing *thing) override;
void thingRemoved(Thing *thing) override; void thingRemoved(Thing *thing) override;

View File

@ -1,5 +1,5 @@
{ {
"name": "Idm", "name": "idm",
"displayName": "iDM", "displayName": "iDM",
"id": "3968d86d-d51a-4ad1-a185-91faa017e38f", "id": "3968d86d-d51a-4ad1-a185-91faa017e38f",
"vendors": [ "vendors": [
@ -12,14 +12,23 @@
"name": "navigator2", "name": "navigator2",
"displayName": "Navigator 2.0", "displayName": "Navigator 2.0",
"id": "1c95ac91-4eca-4cbf-b0f4-d60d35d069ed", "id": "1c95ac91-4eca-4cbf-b0f4-d60d35d069ed",
"createMethods": ["user"], "createMethods": ["user", "discovery"],
"interfaces": ["thermostat", "connectable"], "interfaces": ["thermostat", "connectable"],
"paramTypes": [ "paramTypes": [
{ {
"id": "05714e5c-d66a-4095-bbff-a0eb96fb035b", "id": "05714e5c-d66a-4095-bbff-a0eb96fb035b",
"name":"ipAddress", "name":"ipAddress",
"displayName": "IP address", "displayName": "IP address",
"type": "QString" "inputType": "IPv4Address",
"type": "QString",
"defaultValue": "0.0.0.0"
},
{
"id": "d178ca29-41a1-4f56-82ec-76a833c1de50",
"name": "macAddress",
"displayName": "MAC address",
"type": "QString",
"defaultValue": ""
} }
], ],
"stateTypes":[ "stateTypes":[

View File

@ -57,14 +57,6 @@ ModbusTCPMaster::~ModbusTCPMaster()
{ {
if (m_reconnectTimer) { if (m_reconnectTimer) {
m_reconnectTimer->stop(); m_reconnectTimer->stop();
delete m_reconnectTimer;
m_reconnectTimer = nullptr;
}
if (m_modbusTcpClient) {
m_modbusTcpClient->disconnectDevice();
delete m_modbusTcpClient;
m_modbusTcpClient = nullptr;
} }
if (m_modbusTcpClient) { if (m_modbusTcpClient) {
@ -92,40 +84,27 @@ void ModbusTCPMaster::setHostAddress(const QHostAddress &hostAddress)
m_hostAddress = hostAddress; m_hostAddress = hostAddress;
} }
QHostAddress ModbusTCPMaster::hostAddress() const
{
return m_hostAddress;
}
uint ModbusTCPMaster::port() const
{
return m_port;
}
bool ModbusTCPMaster::setPort(uint port)
{
m_port = port;
return connectDevice();
}
bool ModbusTCPMaster::setHostAddress(const QHostAddress &hostAddress)
{
m_hostAddress = hostAddress;
return connectDevice();
}
bool ModbusTCPMaster::connectDevice() { bool ModbusTCPMaster::connectDevice() {
// TCP connection to target device // TCP connection to target device
qCDebug(dcModbusTCP()) << "Setting up TCP connecion" << QString("%1:%2").arg(m_hostAddress.toString()).arg(m_port);
if (!m_modbusTcpClient) if (!m_modbusTcpClient)
return false; return false;
m_modbusTcpClient->setConnectionParameter(QModbusDevice::NetworkPortParameter, m_port); // Only connect if we are in the unconnected state
m_modbusTcpClient->setConnectionParameter(QModbusDevice::NetworkAddressParameter, m_hostAddress.toString()); if (m_modbusTcpClient->state() == QModbusDevice::UnconnectedState) {
m_modbusTcpClient->setTimeout(m_timeout); qCDebug(dcModbusTCP()) << "Connecting modbus TCP client to" << QString("%1:%2").arg(m_hostAddress.toString()).arg(m_port);
m_modbusTcpClient->setNumberOfRetries(m_numberOfRetries); m_modbusTcpClient->setConnectionParameter(QModbusDevice::NetworkPortParameter, m_port);
m_modbusTcpClient->setConnectionParameter(QModbusDevice::NetworkAddressParameter, m_hostAddress.toString());
m_modbusTcpClient->setTimeout(m_timeout);
m_modbusTcpClient->setNumberOfRetries(m_numberOfRetries);
return m_modbusTcpClient->connectDevice();
} else if (m_modbusTcpClient->state() != QModbusDevice::ConnectedState) {
// Restart the timer in case of connecting not finished yet or closing
m_reconnectTimer->start();
} else {
qCWarning(dcModbusTCP()) << "Connect modbus TCP device" << QString("%1:%2").arg(m_hostAddress.toString()).arg(m_port) << "called, but the socket is currently in the" << m_modbusTcpClient->state();
}
return m_modbusTcpClient->connectDevice(); return false;
} }
void ModbusTCPMaster::disconnectDevice() void ModbusTCPMaster::disconnectDevice()
@ -133,9 +112,21 @@ void ModbusTCPMaster::disconnectDevice()
if (!m_modbusTcpClient) if (!m_modbusTcpClient)
return; return;
// Stop the reconnect timer since disconnect was explicitly called
m_reconnectTimer->stop();
m_modbusTcpClient->disconnectDevice(); m_modbusTcpClient->disconnectDevice();
} }
bool ModbusTCPMaster::reconnectDevice()
{
qCWarning(dcModbusTCP()) << "Reconnecting modbus TCP device" << QString("%1:%2").arg(m_hostAddress.toString()).arg(m_port);
if (!m_modbusTcpClient)
return false;
disconnectDevice();
return connectDevice();
}
bool ModbusTCPMaster::connected() const bool ModbusTCPMaster::connected() const
{ {
return m_connected; return m_connected;
@ -173,16 +164,6 @@ QModbusDevice::Error ModbusTCPMaster::error() const
return m_modbusTcpClient->error(); return m_modbusTcpClient->error();
} }
QString ModbusTCPMaster::errorString() const
{
return m_modbusTcpClient->errorString();
}
QModbusDevice::Error ModbusTCPMaster::error() const
{
return m_modbusTcpClient->error();
}
QUuid ModbusTCPMaster::readCoil(uint slaveAddress, uint registerAddress, uint size) QUuid ModbusTCPMaster::readCoil(uint slaveAddress, uint registerAddress, uint size)
{ {
if (!m_modbusTcpClient) { if (!m_modbusTcpClient) {
@ -499,6 +480,4 @@ void ModbusTCPMaster::onModbusStateChanged(QModbusDevice::State state)
} else if (state == QModbusDevice::UnconnectedState) { } else if (state == QModbusDevice::UnconnectedState) {
m_reconnectTimer->start(); m_reconnectTimer->start();
} }
emit connectionStateChanged(connected);
} }

View File

@ -59,7 +59,6 @@ public:
int timeout() const; int timeout() const;
void setTimeout(int timeout); void setTimeout(int timeout);
int timeout();
QString errorString() const; QString errorString() const;
QModbusDevice::Error error() const; QModbusDevice::Error error() const;
@ -105,9 +104,9 @@ signals:
void writeRequestExecuted(const QUuid &requestId, bool success); void writeRequestExecuted(const QUuid &requestId, bool success);
void writeRequestError(const QUuid &requestId, const QString &error); void writeRequestError(const QUuid &requestId, const QString &error);
void readRequestError(const QUuid &requestId, const QString &error);
void readRequestExecuted(const QUuid &requestId, bool success); void readRequestExecuted(const QUuid &requestId, bool success);
void readRequestError(const QUuid &requestId, const QString &error);
void receivedCoil(uint slaveAddress, uint modbusRegister, const QVector<quint16> &values); void receivedCoil(uint slaveAddress, uint modbusRegister, const QVector<quint16> &values);
void receivedDiscreteInput(uint slaveAddress, uint modbusRegister, const QVector<quint16> &values); void receivedDiscreteInput(uint slaveAddress, uint modbusRegister, const QVector<quint16> &values);

View File

@ -32,6 +32,7 @@
#include "plugininfo.h" #include "plugininfo.h"
#include "hardwaremanager.h" #include "hardwaremanager.h"
#include "network/networkdevicediscovery.h"
#include "hardware/modbus/modbusrtumaster.h" #include "hardware/modbus/modbusrtumaster.h"
#include "hardware/modbus/modbusrtuhardwareresource.h" #include "hardware/modbus/modbusrtuhardwareresource.h"
@ -109,6 +110,50 @@ void IntegrationPluginModbusCommander::discoverThings(ThingDiscoveryInfo *info)
info->finish(Thing::ThingErrorNoError); info->finish(Thing::ThingErrorNoError);
return; return;
} else if (thingClassId == modbusTCPClientThingClassId) {
if (!hardwareManager()->networkDeviceDiscovery()->available()) {
qCWarning(dcModbusCommander()) << "Failed to discover network devices. The network device discovery is not available.";
info->finish(Thing::ThingErrorHardwareNotAvailable, QT_TR_NOOP("The discovery is not available."));
return;
}
NetworkDeviceDiscoveryReply *discoveryReply = hardwareManager()->networkDeviceDiscovery()->discover();
connect(discoveryReply, &NetworkDeviceDiscoveryReply::finished, this, [=](){
ThingDescriptors descriptors;
qCDebug(dcModbusCommander()) << "Discovery finished. Found" << discoveryReply->networkDeviceInfos().count() << "devices";
foreach (const NetworkDeviceInfo &networkDeviceInfo, discoveryReply->networkDeviceInfos()) {
qCDebug(dcModbusCommander()) << networkDeviceInfo;
QString title;
if (networkDeviceInfo.hostName().isEmpty()) {
title += networkDeviceInfo.address().toString();
} else {
title += networkDeviceInfo.address().toString() + " (" + networkDeviceInfo.hostName() + ")";
}
QString description;
if (networkDeviceInfo.macAddressManufacturer().isEmpty()) {
description = networkDeviceInfo.macAddress();
} else {
description = networkDeviceInfo.macAddress() + " (" + networkDeviceInfo.macAddressManufacturer() + ")";
}
ThingDescriptor descriptor(modbusTCPClientThingClassId, title, description);
// Check if we already have set up this device
Things existingThings = myThings().filterByParam(modbusTCPClientThingIpAddressParamTypeId, networkDeviceInfo.address().toString());
if (existingThings.count() == 1) {
qCDebug(dcModbusCommander()) << "This thing already exists in the system." << existingThings.first() << networkDeviceInfo;
descriptor.setThingId(existingThings.first()->id());
}
ParamList params;
params << Param(modbusTCPClientThingIpAddressParamTypeId, networkDeviceInfo.address().toString());
descriptor.setParams(params);
info->addThingDescriptor(descriptor);
}
info->finish(Thing::ThingErrorNoError);
});
return;
} else if (thingClassId == discreteInputThingClassId) { } else if (thingClassId == discreteInputThingClassId) {
Q_FOREACH(Thing *clientThing, myThings()){ Q_FOREACH(Thing *clientThing, myThings()){
if (clientThing->thingClassId() == modbusTCPClientThingClassId) { if (clientThing->thingClassId() == modbusTCPClientThingClassId) {

View File

@ -22,7 +22,7 @@
"id": "35d3e7dc-1f33-4b8c-baa3-eb10b4f157a7", "id": "35d3e7dc-1f33-4b8c-baa3-eb10b4f157a7",
"name": "modbusTCPClient", "name": "modbusTCPClient",
"displayName": "Modbus TCP client", "displayName": "Modbus TCP client",
"createMethods": ["user"], "createMethods": ["user", "discovery"],
"interfaces": ["connectable"], "interfaces": ["connectable"],
"settingsTypes": [ "settingsTypes": [
{ {

View File

@ -30,6 +30,7 @@
#include "plugininfo.h" #include "plugininfo.h"
#include "integrationpluginsunspec.h" #include "integrationpluginsunspec.h"
#include "network/networkdevicediscovery.h"
#include <QHostAddress> #include <QHostAddress>
@ -98,6 +99,52 @@ void IntegrationPluginSunSpec::init()
m_frequencyStateTypeIds.insert(sunspecThreePhaseMeterThingClassId, sunspecThreePhaseMeterFrequencyStateTypeId); m_frequencyStateTypeIds.insert(sunspecThreePhaseMeterThingClassId, sunspecThreePhaseMeterFrequencyStateTypeId);
} }
void IntegrationPluginSunSpec::discoverThings(ThingDiscoveryInfo *info)
{
if (!hardwareManager()->networkDeviceDiscovery()->available()) {
qCWarning(dcSunSpec()) << "Failed to discover network devices. The network device discovery is not available.";
info->finish(Thing::ThingErrorHardwareNotAvailable, QT_TR_NOOP("The discovery is not available."));
return;
}
NetworkDeviceDiscoveryReply *discoveryReply = hardwareManager()->networkDeviceDiscovery()->discover();
connect(discoveryReply, &NetworkDeviceDiscoveryReply::finished, this, [=](){
ThingDescriptors descriptors;
qCDebug(dcSunSpec()) << "Discovery finished. Found" << discoveryReply->networkDeviceInfos().count() << "devices";
foreach (const NetworkDeviceInfo &networkDeviceInfo, discoveryReply->networkDeviceInfos()) {
qCDebug(dcSunSpec()) << networkDeviceInfo;
QString title;
if (networkDeviceInfo.hostName().isEmpty()) {
title += networkDeviceInfo.address().toString();
} else {
title += networkDeviceInfo.address().toString() + " (" + networkDeviceInfo.hostName() + ")";
}
QString description;
if (networkDeviceInfo.macAddressManufacturer().isEmpty()) {
description = networkDeviceInfo.macAddress();
} else {
description = networkDeviceInfo.macAddress() + " (" + networkDeviceInfo.macAddressManufacturer() + ")";
}
ThingDescriptor descriptor(sunspecConnectionThingClassId, title, description);
// Check if we already have set up this device
Things existingThings = myThings().filterByParam(sunspecConnectionThingIpAddressParamTypeId, networkDeviceInfo.address().toString());
if (existingThings.count() == 1) {
qCDebug(dcSunSpec()) << "This thing already exists in the system." << existingThings.first() << networkDeviceInfo;
descriptor.setThingId(existingThings.first()->id());
}
ParamList params;
params << Param(sunspecConnectionThingIpAddressParamTypeId, networkDeviceInfo.address().toString());
descriptor.setParams(params);
info->addThingDescriptor(descriptor);
}
info->finish(Thing::ThingErrorNoError);
});
}
void IntegrationPluginSunSpec::setupThing(ThingSetupInfo *info) void IntegrationPluginSunSpec::setupThing(ThingSetupInfo *info)
{ {
Thing *thing = info->thing(); Thing *thing = info->thing();
@ -132,7 +179,7 @@ void IntegrationPluginSunSpec::setupThing(ThingSetupInfo *info)
}); });
connect(info, &ThingSetupInfo::aborted, sunSpec, &SunSpec::deleteLater); connect(info, &ThingSetupInfo::aborted, sunSpec, &SunSpec::deleteLater);
connect(sunSpec, &SunSpec::destroyed, [this, thing] { connect(sunSpec, &SunSpec::destroyed, thing, [this, thing] {
m_sunSpecConnections.remove(thing->id()); m_sunSpecConnections.remove(thing->id());
}); });
connect(sunSpec, &SunSpec::foundSunSpecModel, this, &IntegrationPluginSunSpec::onFoundSunSpecModel); connect(sunSpec, &SunSpec::foundSunSpecModel, this, &IntegrationPluginSunSpec::onFoundSunSpecModel);

View File

@ -52,6 +52,7 @@ class IntegrationPluginSunSpec: public IntegrationPlugin
public: public:
explicit IntegrationPluginSunSpec(); explicit IntegrationPluginSunSpec();
void init() override; void init() override;
void discoverThings(ThingDiscoveryInfo *info) override;
void setupThing(ThingSetupInfo *info) override; void setupThing(ThingSetupInfo *info) override;
void postSetupThing(Thing *thing) override; void postSetupThing(Thing *thing) override;
void thingRemoved(Thing *thing) override; void thingRemoved(Thing *thing) override;

View File

@ -39,7 +39,7 @@
"name": "sunspecConnection", "name": "sunspecConnection",
"displayName": "SunSpec connection", "displayName": "SunSpec connection",
"id": "f51853f3-8815-4cf3-b337-45cda1f3e6d5", "id": "f51853f3-8815-4cf3-b337-45cda1f3e6d5",
"createMethods": [ "User" ], "createMethods": [ "User", "Discovery" ],
"interfaces": ["gateway"], "interfaces": ["gateway"],
"paramTypes": [ "paramTypes": [
{ {

View File

@ -1,271 +0,0 @@
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*
* Copyright 2013 - 2020, nymea GmbH
* Contact: contact@nymea.io
*
* This file is part of nymea.
* This project including source code and documentation is protected by
* copyright law, and remains the property of nymea GmbH. All rights, including
* reproduction, publication, editing and translation, are reserved. The use of
* this project is subject to the terms of a license agreement to be concluded
* with nymea GmbH in accordance with the terms of use of nymea GmbH, available
* under https://nymea.io/license
*
* GNU Lesser General Public License Usage
* Alternatively, this project may be redistributed and/or modified under the
* terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; version 3. This project is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this project. If not, see <https://www.gnu.org/licenses/>.
*
* For any further details and any questions please contact us under
* contact@nymea.io or see our FAQ/Licensing Information on
* https://nymea.io/license/faq
*
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
#include "discovery.h"
#include "extern-plugininfo.h"
#include <QDebug>
#include <QXmlStreamReader>
#include <QNetworkInterface>
#include <QHostInfo>
#include <QTimer>
Discovery::Discovery(QObject *parent) : QObject(parent)
{
connect(&m_timeoutTimer, &QTimer::timeout, this, &Discovery::onTimeout);
}
void Discovery::discoverHosts(int timeout)
{
if (isRunning()) {
qCWarning(dcWallbe()) << "Discovery already running. Cannot start twice.";
return;
}
m_timeoutTimer.start(timeout * 1000);
foreach (const QString &target, getDefaultTargets()) {
QProcess *discoveryProcess = new QProcess(this);
m_discoveryProcesses.append(discoveryProcess);
connect(discoveryProcess, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(discoveryFinished(int,QProcess::ExitStatus)));
QStringList arguments;
arguments << "-oX" << "-" << "-n" << "-sn";
arguments << target;
qCDebug(dcWallbe()) << "Scanning network:" << "nmap" << arguments.join(" ");
discoveryProcess->start(QStringLiteral("nmap"), arguments);
}
}
void Discovery::abort()
{
foreach (QProcess *discoveryProcess, m_discoveryProcesses) {
if (discoveryProcess->state() == QProcess::Running) {
qCDebug(dcWallbe()) << "Kill running discovery process";
discoveryProcess->terminate();
discoveryProcess->waitForFinished(5000);
}
}
foreach (QProcess *p, m_pendingArpLookups.keys()) {
p->terminate();
delete p;
}
m_pendingArpLookups.clear();
m_pendingNameLookups.clear();
qDeleteAll(m_scanResults);
m_scanResults.clear();
}
bool Discovery::isRunning() const
{
return !m_discoveryProcesses.isEmpty() || !m_pendingArpLookups.isEmpty() || !m_pendingNameLookups.isEmpty();
}
void Discovery::discoveryFinished(int exitCode, QProcess::ExitStatus exitStatus)
{
QProcess *discoveryProcess = static_cast<QProcess*>(sender());
if (exitCode != 0 || exitStatus != QProcess::NormalExit) {
qCWarning(dcWallbe()) << "Nmap error failed. Is nmap installed correctly?";
m_discoveryProcesses.removeAll(discoveryProcess);
discoveryProcess->deleteLater();
discoveryProcess = nullptr;
finishDiscovery();
return;
}
QByteArray data = discoveryProcess->readAll();
m_discoveryProcesses.removeAll(discoveryProcess);
discoveryProcess->deleteLater();
discoveryProcess = nullptr;
QXmlStreamReader reader(data);
int foundHosts = 0;
qCDebug(dcWallbe()) << "nmap finished network discovery:";
while (!reader.atEnd() && !reader.hasError()) {
QXmlStreamReader::TokenType token = reader.readNext();
if(token == QXmlStreamReader::StartDocument)
continue;
if(token == QXmlStreamReader::StartElement && reader.name() == "host") {
bool isUp = false;
QString address;
QString macAddress;
QString vendor;
while (!reader.atEnd() && !reader.hasError() && !(token == QXmlStreamReader::EndElement && reader.name() == "host")) {
token = reader.readNext();
if (reader.name() == "address") {
QString addr = reader.attributes().value("addr").toString();
QString type = reader.attributes().value("addrtype").toString();
if (type == "ipv4" && !addr.isEmpty()) {
address = addr;
} else if (type == "mac") {
macAddress = addr;
vendor = reader.attributes().value("vendor").toString();
}
}
if (reader.name() == "status") {
QString state = reader.attributes().value("state").toString();
if (!state.isEmpty())
isUp = state == "up";
}
}
if (isUp) {
foundHosts++;
qCDebug(dcWallbe()) << " - host:" << vendor << address << macAddress;
Host *host = new Host();
host->setAddress(address);
if (!macAddress.isEmpty()) {
host->setMacAddress(macAddress);
} else {
QProcess *arpLookup = new QProcess(this);
m_pendingArpLookups.insert(arpLookup, host);
connect(arpLookup, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(arpLookupDone(int,QProcess::ExitStatus)));
arpLookup->start("arp", {"-vn"});
}
host->setVendor(vendor);
QHostInfo::lookupHost(address, this, SLOT(hostLookupDone(QHostInfo)));
m_pendingNameLookups.insert(address, host);
m_scanResults.append(host);
}
}
}
if (foundHosts == 0 && m_discoveryProcesses.isEmpty()) {
qCDebug(dcWallbe()) << "Network scan successful but no hosts found in this network";
finishDiscovery();
}
}
void Discovery::hostLookupDone(const QHostInfo &info)
{
Host *host = m_pendingNameLookups.take(info.addresses().first().toString());
if (!host) {
// Probably aborted...
return;
}
if (info.error() != QHostInfo::NoError) {
qWarning(dcWallbe()) << "Host lookup failed:" << info.errorString();
}
if (host->hostName().isEmpty() || info.hostName() != host->address()) {
host->setHostName(info.hostName());
}
finishDiscovery();
}
void Discovery::arpLookupDone(int exitCode, QProcess::ExitStatus exitStatus)
{
QProcess *p = static_cast<QProcess*>(sender());
p->deleteLater();
Host *host = m_pendingArpLookups.take(p);
if (exitCode != 0 || exitStatus != QProcess::NormalExit) {
qCWarning(dcWallbe()) << "ARP lookup process failed for host" << host->address();
finishDiscovery();
return;
}
QString data = QString::fromLatin1(p->readAll());
foreach (QString line, data.split('\n')) {
line.replace(QRegExp("[ ]{1,}"), " ");
QStringList parts = line.split(" ");
if (parts.count() >= 3 && parts.first() == host->address() && parts.at(1) == "ether") {
host->setMacAddress(parts.at(2));
break;
}
}
finishDiscovery();
}
void Discovery::onTimeout()
{
qWarning(dcWallbe()) << "Timeout hit. Stopping discovery";
while (!m_discoveryProcesses.isEmpty()) {
QProcess *discoveryProcess = m_discoveryProcesses.takeFirst();
disconnect(this, SLOT(discoveryFinished(int,QProcess::ExitStatus)));
discoveryProcess->terminate();
delete discoveryProcess;
}
foreach (QProcess *p, m_pendingArpLookups.keys()) {
p->terminate();
m_scanResults.removeAll(m_pendingArpLookups.value(p));
delete p;
}
m_pendingArpLookups.clear();
m_pendingNameLookups.clear();
finishDiscovery();
}
QStringList Discovery::getDefaultTargets()
{
QStringList targets;
foreach (const QHostAddress &interface, QNetworkInterface::allAddresses()) {
if (!interface.isLoopback() && interface.scopeId().isEmpty() && interface.protocol() == QAbstractSocket::IPv4Protocol) {
QPair<QHostAddress, int> pair = QHostAddress::parseSubnet(interface.toString() + "/24");
QString newTarget = QString("%1/%2").arg(pair.first.toString()).arg(pair.second);
if (!targets.contains(newTarget)) {
targets.append(newTarget);
}
}
}
return targets;
}
void Discovery::finishDiscovery()
{
if (m_discoveryProcesses.count() > 0 || m_pendingNameLookups.count() > 0 || m_pendingArpLookups.count() > 0) {
// Still busy...
return;
}
QList<Host> hosts;
foreach (Host *host, m_scanResults) {
if (!host->macAddress().isEmpty()) {
hosts.append(*host);
}
}
qDeleteAll(m_scanResults);
m_scanResults.clear();
qCDebug(dcWallbe()) << "Found" << hosts.count() << "network devices";
m_timeoutTimer.stop();
emit finished(hosts);
}

View File

@ -1,75 +0,0 @@
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*
* Copyright 2013 - 2020, nymea GmbH
* Contact: contact@nymea.io
*
* This file is part of nymea.
* This project including source code and documentation is protected by
* copyright law, and remains the property of nymea GmbH. All rights, including
* reproduction, publication, editing and translation, are reserved. The use of
* this project is subject to the terms of a license agreement to be concluded
* with nymea GmbH in accordance with the terms of use of nymea GmbH, available
* under https://nymea.io/license
*
* GNU Lesser General Public License Usage
* Alternatively, this project may be redistributed and/or modified under the
* terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; version 3. This project is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this project. If not, see <https://www.gnu.org/licenses/>.
*
* For any further details and any questions please contact us under
* contact@nymea.io or see our FAQ/Licensing Information on
* https://nymea.io/license/faq
*
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
#ifndef DISCOVERY_H
#define DISCOVERY_H
#include <QObject>
#include <QProcess>
#include <QHostInfo>
#include <QTimer>
#include "host.h"
class Discovery : public QObject
{
Q_OBJECT
public:
explicit Discovery(QObject *parent = nullptr);
void discoverHosts(int timeout);
void abort();
bool isRunning() const;
signals:
void finished(const QList<Host> &hosts);
private:
QStringList getDefaultTargets();
void finishDiscovery();
private slots:
void discoveryFinished(int exitCode, QProcess::ExitStatus exitStatus);
void hostLookupDone(const QHostInfo &info);
void arpLookupDone(int exitCode, QProcess::ExitStatus exitStatus);
void onTimeout();
private:
QList<QProcess*> m_discoveryProcesses;
QTimer m_timeoutTimer;
QHash<QProcess*, Host*> m_pendingArpLookups;
QHash<QString, Host*> m_pendingNameLookups;
QList<Host*> m_scanResults;
};
#endif // DISCOVERY_H

View File

@ -1,104 +0,0 @@
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*
* Copyright 2013 - 2020, nymea GmbH
* Contact: contact@nymea.io
*
* This file is part of nymea.
* This project including source code and documentation is protected by
* copyright law, and remains the property of nymea GmbH. All rights, including
* reproduction, publication, editing and translation, are reserved. The use of
* this project is subject to the terms of a license agreement to be concluded
* with nymea GmbH in accordance with the terms of use of nymea GmbH, available
* under https://nymea.io/license
*
* GNU Lesser General Public License Usage
* Alternatively, this project may be redistributed and/or modified under the
* terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; version 3. This project is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this project. If not, see <https://www.gnu.org/licenses/>.
*
* For any further details and any questions please contact us under
* contact@nymea.io or see our FAQ/Licensing Information on
* https://nymea.io/license/faq
*
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
#include "host.h"
Host::Host()
{
qRegisterMetaType<Host>();
qRegisterMetaType<QList<Host> >();
}
QString Host::macAddress() const
{
return m_macAddress;
}
void Host::setMacAddress(const QString &macAddress)
{
m_macAddress = macAddress;
}
QString Host::hostName() const
{
return m_hostName;
}
void Host::setHostName(const QString &hostName)
{
m_hostName = hostName;
}
QString Host::vendor() const
{
return m_vendor;
}
void Host::setVendor(const QString &vendor)
{
m_vendor = vendor;
}
QString Host::address() const
{
return m_address;
}
void Host::setAddress(const QString &address)
{
m_address = address;
}
void Host::seen()
{
m_lastSeenTime = QDateTime::currentDateTime();
}
QDateTime Host::lastSeenTime() const
{
return m_lastSeenTime;
}
bool Host::reachable() const
{
return m_reachable;
}
void Host::setReachable(bool reachable)
{
m_reachable = reachable;
}
QDebug operator<<(QDebug dbg, const Host &host)
{
dbg.nospace() << "Host(" << host.macAddress() << "," << host.hostName() << ", " << host.address() << ", " << (host.reachable() ? "up" : "down") << ")";
return dbg.space();
}

View File

@ -1,74 +0,0 @@
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*
* Copyright 2013 - 2020, nymea GmbH
* Contact: contact@nymea.io
*
* This file is part of nymea.
* This project including source code and documentation is protected by
* copyright law, and remains the property of nymea GmbH. All rights, including
* reproduction, publication, editing and translation, are reserved. The use of
* this project is subject to the terms of a license agreement to be concluded
* with nymea GmbH in accordance with the terms of use of nymea GmbH, available
* under https://nymea.io/license
*
* GNU Lesser General Public License Usage
* Alternatively, this project may be redistributed and/or modified under the
* terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; version 3. This project is distributed in the hope that
* it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this project. If not, see <https://www.gnu.org/licenses/>.
*
* For any further details and any questions please contact us under
* contact@nymea.io or see our FAQ/Licensing Information on
* https://nymea.io/license/faq
*
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
#ifndef HOST_H
#define HOST_H
#include <QString>
#include <QDebug>
#include <QDateTime>
class Host
{
public:
Host();
QString macAddress() const;
void setMacAddress(const QString &macAddress);
QString hostName() const;
void setHostName(const QString &hostName);
QString vendor() const;
void setVendor(const QString &vendor);
QString address() const;
void setAddress(const QString &address);
void seen();
QDateTime lastSeenTime() const;
bool reachable() const;
void setReachable(bool reachable);
private:
QString m_macAddress;
QString m_hostName;
QString m_address;
QString m_vendor;
QDateTime m_lastSeenTime;
bool m_reachable;
};
Q_DECLARE_METATYPE(Host)
QDebug operator<<(QDebug dbg, const Host &host);
#endif // HOST_H

View File

@ -30,7 +30,7 @@
#include "integrationpluginwallbe.h" #include "integrationpluginwallbe.h"
#include "plugininfo.h" #include "plugininfo.h"
#include "network/networkdevicediscovery.h"
#include "types/param.h" #include "types/param.h"
#include <QDebug> #include <QDebug>
@ -41,66 +41,89 @@
IntegrationPluginWallbe::IntegrationPluginWallbe() IntegrationPluginWallbe::IntegrationPluginWallbe()
{ {
} }
void IntegrationPluginWallbe::init() { void IntegrationPluginWallbe::init()
{
// FIXME: make use of the internal network discovery if the device gets unavailable. For now, commented out since it has not been used
// at the moment of changing this.
m_discovery = new Discovery(); // m_discovery = new Discovery();
connect(m_discovery, &Discovery::finished, this, [this](const QList<Host> &hosts) { // connect(m_discovery, &Discovery::finished, this, [this](const QList<Host> &hosts) {
foreach (const Host &host, hosts) { // foreach (const Host &host, hosts) {
if (!host.vendor().contains("Phoenix", Qt::CaseSensitivity::CaseInsensitive)) // if (!host.vendor().contains("Phoenix", Qt::CaseSensitivity::CaseInsensitive))
continue; // continue;
Q_FOREACH(Thing *existingThing, myThings()) { // Q_FOREACH(Thing *existingThing, myThings()) {
if (existingThing->paramValue(wallbeEcoThingMacParamTypeId).toString().isEmpty()) { // if (existingThing->paramValue(wallbeEcoThingMacParamTypeId).toString().isEmpty()) {
//This device got probably manually setup, to enable auto rediscovery the MAC address needs to setup // //This device got probably manually setup, to enable auto rediscovery the MAC address needs to setup
if (existingThing->paramValue(wallbeEcoThingIpParamTypeId).toString() == host.address()) { // if (existingThing->paramValue(wallbeEcoThingIpParamTypeId).toString() == host.address()) {
qCDebug(dcWallbe()) << "Wallbe Wallbox MAC Address has been discovered" << existingThing->name() << host.macAddress(); // qCDebug(dcWallbe()) << "Wallbe Wallbox MAC Address has been discovered" << existingThing->name() << host.macAddress();
existingThing->setParamValue(wallbeEcoThingMacParamTypeId, host.macAddress()); // existingThing->setParamValue(wallbeEcoThingMacParamTypeId, host.macAddress());
} // }
} else if (existingThing->paramValue(wallbeEcoThingMacParamTypeId).toString() == host.macAddress()) { // } else if (existingThing->paramValue(wallbeEcoThingMacParamTypeId).toString() == host.macAddress()) {
if (existingThing->paramValue(wallbeEcoThingIpParamTypeId).toString() != host.address()) { // if (existingThing->paramValue(wallbeEcoThingIpParamTypeId).toString() != host.address()) {
qCDebug(dcWallbe()) << "Wallbe Wallbox IP Address has changed, from" << existingThing->paramValue(wallbeEcoThingIpParamTypeId).toString() << "to" << host.address(); // qCDebug(dcWallbe()) << "Wallbe Wallbox IP Address has changed, from" << existingThing->paramValue(wallbeEcoThingIpParamTypeId).toString() << "to" << host.address();
existingThing->setParamValue(wallbeEcoThingIpParamTypeId, host.address()); // existingThing->setParamValue(wallbeEcoThingIpParamTypeId, host.address());
} else { // } else {
qCDebug(dcWallbe()) << "Wallbe Wallbox" << existingThing->name() << "IP address has not changed" << host.address(); // qCDebug(dcWallbe()) << "Wallbe Wallbox" << existingThing->name() << "IP address has not changed" << host.address();
} // }
break; // break;
} // }
} // }
} // }
}); // });
} }
void IntegrationPluginWallbe::discoverThings(ThingDiscoveryInfo *info) void IntegrationPluginWallbe::discoverThings(ThingDiscoveryInfo *info)
{ {
if (info->thingClassId() == wallbeEcoThingClassId){ if (info->thingClassId() == wallbeEcoThingClassId) {
qCDebug(dcWallbe) << "Start Wallbe eco discovery"; if (!hardwareManager()->networkDeviceDiscovery()->available()) {
qCWarning(dcWallbe()) << "Failed to discover network devices. The network device discovery is not available.";
info->finish(Thing::ThingErrorHardwareNotAvailable, QT_TR_NOOP("The discovery is not available."));
return;
}
m_discovery->discoverHosts(50); qCDebug(dcWallbe()) << "Start Wallbe eco discovery";
connect(m_discovery, &Discovery::finished, info, [this, info] (const QList<Host> &hosts) { NetworkDeviceDiscoveryReply *discoveryReply = hardwareManager()->networkDeviceDiscovery()->discover();
connect(discoveryReply, &NetworkDeviceDiscoveryReply::finished, this, [=](){
foreach (const Host &host, hosts) { ThingDescriptors descriptors;
if (!host.vendor().contains("Phoenix", Qt::CaseSensitivity::CaseInsensitive)) qCDebug(dcWallbe()) << "Discovery finished. Found" << discoveryReply->networkDeviceInfos().count() << "devices";
foreach (const NetworkDeviceInfo &networkDeviceInfo, discoveryReply->networkDeviceInfos()) {
qCDebug(dcWallbe()) << networkDeviceInfo;
if (!networkDeviceInfo.macAddressManufacturer().contains("Phoenix", Qt::CaseSensitivity::CaseInsensitive))
continue; continue;
ThingDescriptor descriptor(wallbeEcoThingClassId); QString title;
// Rediscovery if (networkDeviceInfo.hostName().isEmpty()) {
foreach (Thing *existingThing, myThings()) { title += networkDeviceInfo.address().toString();
if (existingThing->paramValue(wallbeEcoThingMacParamTypeId).toString() == host.macAddress()) { } else {
qCDebug(dcWallbe()) << " - Device is already added"; title += networkDeviceInfo.address().toString() + " (" + networkDeviceInfo.hostName() + ")";
descriptor.setThingId(existingThing->id());
break;
}
} }
descriptor.setTitle(host.hostName().remove(".localdomain"));
descriptor.setDescription(host.address()); QString description;
if (networkDeviceInfo.macAddressManufacturer().isEmpty()) {
description = networkDeviceInfo.macAddress();
} else {
description = networkDeviceInfo.macAddress() + " (" + networkDeviceInfo.macAddressManufacturer() + ")";
}
ThingDescriptor descriptor(wallbeEcoThingClassId, title, description);
// Check if we already have set up this device
Things existingThings = myThings().filterByParam(wallbeEcoThingIpParamTypeId, networkDeviceInfo.address().toString());
if (existingThings.count() == 1) {
qCDebug(dcWallbe()) << "This thing already exists in the system." << existingThings.first() << networkDeviceInfo;
descriptor.setThingId(existingThings.first()->id());
}
ParamList params; ParamList params;
params.append(Param(wallbeEcoThingIpParamTypeId, host.address())); params << Param(wallbeEcoThingIpParamTypeId, networkDeviceInfo.address().toString());
params.append(Param(wallbeEcoThingMacParamTypeId, host.macAddress())); params << Param(wallbeEcoThingMacParamTypeId, networkDeviceInfo.macAddress());
descriptor.setParams(params); descriptor.setParams(params);
info->addThingDescriptor(descriptor); info->addThingDescriptor(descriptor);
} }
@ -297,8 +320,8 @@ void IntegrationPluginWallbe::onReceivedInputRegister(int slaveAddress, int modb
} else if (WallbeRegisterAddress(modbusRegister) == WallbeRegisterAddress::FirmwareVersion) { } else if (WallbeRegisterAddress(modbusRegister) == WallbeRegisterAddress::FirmwareVersion) {
int firmware = (uint32_t)(value[1]<<16)|(uint32_t)(value[0]); int firmware = (uint32_t)(value[1]<<16)|(uint32_t)(value[0]);
uint major = firmware/10000; uint major = firmware/10000;
uint minor = (firmware%10000)/100; uint minor = (firmware%10000)/100;
uint patch = firmware%100; uint patch = firmware%100;
QString firmwarestring = QString::number(major)+'.'+QString::number(minor)+'.'+QString::number(patch); QString firmwarestring = QString::number(major)+'.'+QString::number(minor)+'.'+QString::number(patch);
thing->setStateValue(wallbeEcoFirmwareVersionStateTypeId, firmwarestring); thing->setStateValue(wallbeEcoFirmwareVersionStateTypeId, firmwarestring);
} }

View File

@ -34,8 +34,6 @@
#include "integrations/integrationplugin.h" #include "integrations/integrationplugin.h"
#include "plugintimer.h" #include "plugintimer.h"
#include "host.h"
#include "discovery.h"
#include "../modbus/modbustcpmaster.h" #include "../modbus/modbustcpmaster.h"
#include <QObject> #include <QObject>
@ -72,7 +70,6 @@ public:
void thingRemoved(Thing *thing) override; void thingRemoved(Thing *thing) override;
private: private:
Discovery *m_discovery = nullptr;
QHash<Thing *, ModbusTCPMaster *> m_connections; QHash<Thing *, ModbusTCPMaster *> m_connections;
PluginTimer *m_pluginTimer = nullptr; PluginTimer *m_pluginTimer = nullptr;
QHash<QUuid, ThingActionInfo *> m_asyncActions; QHash<QUuid, ThingActionInfo *> m_asyncActions;
@ -82,8 +79,8 @@ private:
private slots: private slots:
void onConnectionStateChanged(bool status); void onConnectionStateChanged(bool status);
void onReceivedInputRegister(int slaveAddress, int modbusRegister, const QVector<quint16> &value); void onReceivedInputRegister(int slaveAddress, int modbusRegister, const QVector<quint16> &value);
void onReceivedCoil(int slaveAddress, int modbusRegister, const QVector<quint16> &value); void onReceivedCoil(int slaveAddress, int modbusRegister, const QVector<quint16> &value);
void onReceivedHoldingRegister(int slaveAddress, int modbusRegister, const QVector<quint16> &value); void onReceivedHoldingRegister(int slaveAddress, int modbusRegister, const QVector<quint16> &value);
void onWriteRequestExecuted(const QUuid &requestId, bool success); void onWriteRequestExecuted(const QUuid &requestId, bool success);

View File

@ -6,12 +6,8 @@ QT += \
SOURCES += \ SOURCES += \
integrationpluginwallbe.cpp \ integrationpluginwallbe.cpp \
../modbus/modbustcpmaster.cpp \ ../modbus/modbustcpmaster.cpp
discovery.cpp \
host.cpp
HEADERS += \ HEADERS += \
integrationpluginwallbe.h \ integrationpluginwallbe.h \
../modbus/modbustcpmaster.h \ ../modbus/modbustcpmaster.h
discovery.h \
host.h

View File

@ -28,6 +28,7 @@
* *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
#include "network/networkdevicediscovery.h"
#include "integrationpluginwebasto.h" #include "integrationpluginwebasto.h"
#include "plugininfo.h" #include "plugininfo.h"
@ -45,61 +46,84 @@ IntegrationPluginWebasto::IntegrationPluginWebasto()
void IntegrationPluginWebasto::init() void IntegrationPluginWebasto::init()
{ {
m_discovery = new Discovery(this); // FIXME: make use of the internal network discovery if the device gets unavailable. For now, commented out since it has not been used
connect(m_discovery, &Discovery::finished, this, [this](const QList<Host> &hosts) { // at the moment of changing this.
foreach (const Host &host, hosts) { // m_discovery = new Discovery(this);
if (!host.hostName().contains("webasto", Qt::CaseSensitivity::CaseInsensitive)) // connect(m_discovery, &Discovery::finished, this, [this](const QList<Host> &hosts) {
continue;
foreach (Thing *existingThing, myThings()) { // foreach (const Host &host, hosts) {
if (existingThing->paramValue(liveWallboxThingMacAddressParamTypeId).toString().isEmpty()) { // if (!host.hostName().contains("webasto", Qt::CaseSensitivity::CaseInsensitive))
//This device got probably manually setup, to enable auto rediscovery the MAC address needs to setup // continue;
if (existingThing->paramValue(liveWallboxThingIpAddressParamTypeId).toString() == host.address()) {
qCDebug(dcWebasto()) << "Wallbox MAC Address has been discovered" << existingThing->name() << host.macAddress();
existingThing->setParamValue(liveWallboxThingMacAddressParamTypeId, host.macAddress());
} // foreach (Thing *existingThing, myThings()) {
} else if (existingThing->paramValue(liveWallboxThingMacAddressParamTypeId).toString() == host.macAddress()) { // if (existingThing->paramValue(liveWallboxThingMacAddressParamTypeId).toString().isEmpty()) {
if (existingThing->paramValue(liveWallboxThingIpAddressParamTypeId).toString() != host.address()) { // //This device got probably manually setup, to enable auto rediscovery the MAC address needs to setup
qCDebug(dcWebasto()) << "Wallbox IP Address has changed, from" << existingThing->paramValue(liveWallboxThingIpAddressParamTypeId).toString() << "to" << host.address(); // if (existingThing->paramValue(liveWallboxThingIpAddressParamTypeId).toString() == host.address()) {
existingThing->setParamValue(liveWallboxThingIpAddressParamTypeId, host.address()); // qCDebug(dcWebasto()) << "Wallbox MAC Address has been discovered" << existingThing->name() << host.macAddress();
// existingThing->setParamValue(liveWallboxThingMacAddressParamTypeId, host.macAddress());
} else { // }
qCDebug(dcWebasto()) << "Wallbox" << existingThing->name() << "IP address has not changed" << host.address(); // } else if (existingThing->paramValue(liveWallboxThingMacAddressParamTypeId).toString() == host.macAddress()) {
} // if (existingThing->paramValue(liveWallboxThingIpAddressParamTypeId).toString() != host.address()) {
break; // qCDebug(dcWebasto()) << "Wallbox IP Address has changed, from" << existingThing->paramValue(liveWallboxThingIpAddressParamTypeId).toString() << "to" << host.address();
} // existingThing->setParamValue(liveWallboxThingIpAddressParamTypeId, host.address());
}
} // } else {
}); // qCDebug(dcWebasto()) << "Wallbox" << existingThing->name() << "IP address has not changed" << host.address();
// }
// break;
// }
// }
// }
// });
} }
void IntegrationPluginWebasto::discoverThings(ThingDiscoveryInfo *info) void IntegrationPluginWebasto::discoverThings(ThingDiscoveryInfo *info)
{ {
qCDebug(dcWebasto()) << "Discover things";
if (info->thingClassId() == liveWallboxThingClassId) { if (info->thingClassId() == liveWallboxThingClassId) {
m_discovery->discoverHosts(25); if (!hardwareManager()->networkDeviceDiscovery()->available()) {
connect(m_discovery, &Discovery::finished, info, [this, info] (const QList<Host> &hosts) { qCWarning(dcWebasto()) << "Failed to discover network devices. The network device discovery is not available.";
info->finish(Thing::ThingErrorHardwareNotAvailable, QT_TR_NOOP("The discovery is not available."));
return;
}
foreach (const Host &host, hosts) { qCDebug(dcWebasto()) << "Discover things";
if (!host.hostName().contains("webasto", Qt::CaseSensitivity::CaseInsensitive)) NetworkDeviceDiscoveryReply *discoveryReply = hardwareManager()->networkDeviceDiscovery()->discover();
connect(discoveryReply, &NetworkDeviceDiscoveryReply::finished, this, [=](){
ThingDescriptors descriptors;
qCDebug(dcWebasto()) << "Discovery finished. Found" << discoveryReply->networkDeviceInfos().count() << "devices";
foreach (const NetworkDeviceInfo &networkDeviceInfo, discoveryReply->networkDeviceInfos()) {
qCDebug(dcWebasto()) << networkDeviceInfo;
if (!networkDeviceInfo.hostName().contains("webasto", Qt::CaseSensitivity::CaseInsensitive))
continue; continue;
qCDebug(dcWebasto()) << " - " << host.hostName() << host.address() << host.macAddress(); QString title = "Wallbox ";
ThingDescriptor descriptor(liveWallboxThingClassId, "Wallbox", host.address() + " (" + host.macAddress() + ")"); if (networkDeviceInfo.hostName().isEmpty()) {
title += networkDeviceInfo.address().toString();
// Rediscovery } else {
foreach (Thing *existingThing, myThings()) { title += networkDeviceInfo.address().toString() + " (" + networkDeviceInfo.hostName() + ")";
if (existingThing->paramValue(liveWallboxThingMacAddressParamTypeId).toString() == host.macAddress()) {
qCDebug(dcWebasto()) << " - Device is already added";
descriptor.setThingId(existingThing->id());
break;
}
} }
QString description;
if (networkDeviceInfo.macAddressManufacturer().isEmpty()) {
description = networkDeviceInfo.macAddress();
} else {
description = networkDeviceInfo.macAddress() + " (" + networkDeviceInfo.macAddressManufacturer() + ")";
}
ThingDescriptor descriptor(liveWallboxThingClassId, title, description);
// Check if we already have set up this device
Things existingThings = myThings().filterByParam(liveWallboxThingIpAddressParamTypeId, networkDeviceInfo.address().toString());
if (existingThings.count() == 1) {
qCDebug(dcWebasto()) << "This thing already exists in the system." << existingThings.first() << networkDeviceInfo;
descriptor.setThingId(existingThings.first()->id());
}
ParamList params; ParamList params;
params << Param(liveWallboxThingMacAddressParamTypeId, host.macAddress()); params << Param(liveWallboxThingIpAddressParamTypeId, networkDeviceInfo.address().toString());
params << Param(liveWallboxThingIpAddressParamTypeId, host.address()); params << Param(liveWallboxThingMacAddressParamTypeId, networkDeviceInfo.macAddress());
descriptor.setParams(params); descriptor.setParams(params);
info->addThingDescriptor(descriptor); info->addThingDescriptor(descriptor);
} }

View File

@ -34,8 +34,6 @@
#include "integrations/integrationplugin.h" #include "integrations/integrationplugin.h"
#include "plugintimer.h" #include "plugintimer.h"
#include "webasto.h" #include "webasto.h"
#include "../discovery/discovery.h"
#include "../discovery/host.h"
#include "../modbus/modbustcpmaster.h" #include "../modbus/modbustcpmaster.h"
#include <QObject> #include <QObject>
@ -59,7 +57,6 @@ public:
void thingRemoved(Thing *thing) override; void thingRemoved(Thing *thing) override;
private: private:
Discovery *m_discovery = nullptr;
PluginTimer *m_pluginTimer = nullptr; PluginTimer *m_pluginTimer = nullptr;
QHash<Thing *, Webasto *> m_webastoConnections; QHash<Thing *, Webasto *> m_webastoConnections;
QHash<QUuid, ThingActionInfo *> m_asyncActions; QHash<QUuid, ThingActionInfo *> m_asyncActions;

View File

@ -80,7 +80,7 @@ void Webasto::setLivebitInterval(uint seconds)
void Webasto::getRegister(Webasto::TqModbusRegister modbusRegister, uint length) void Webasto::getRegister(Webasto::TqModbusRegister modbusRegister, uint length)
{ {
qCDebug(dcWebasto()) << "Webasto: Get register" << modbusRegister << length; qCDebug(dcWebasto()) << "Webasto: Get register" << modbusRegister << length;
if (length < 1 && length > 10) { if (length < 1 || length > 10) {
qCWarning(dcWebasto()) << "Invalide register length, allowed values [1,10]"; qCWarning(dcWebasto()) << "Invalide register length, allowed values [1,10]";
return; return;
} }

View File

@ -1,19 +1,13 @@
include(../plugins.pri) include(../plugins.pri)
QT += \ QT += serialbus network
serialbus \
network
SOURCES += \ SOURCES += \
integrationpluginwebasto.cpp \ integrationpluginwebasto.cpp \
webasto.cpp \ webasto.cpp \
../modbus/modbustcpmaster.cpp \ ../modbus/modbustcpmaster.cpp
../discovery/discovery.cpp \
../discovery/host.cpp
HEADERS += \ HEADERS += \
integrationpluginwebasto.h \ integrationpluginwebasto.h \
webasto.h \ webasto.h \
../modbus/modbustcpmaster.h \ ../modbus/modbustcpmaster.h
../discovery/discovery.h \
../discovery/host.h