Skip to content

Commit

Permalink
sensor: broadcast the correct ip for each network interface
Browse files Browse the repository at this point in the history
  • Loading branch information
Williangalvani authored and patrickelectric committed Jun 30, 2023
1 parent e447b2c commit b129811
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 3 deletions.
6 changes: 6 additions & 0 deletions src/sensor/ping360asciiprotocol.h
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,12 @@ class Ping360AsciiProtocol : public QObject {
*/
static Ping360DiscoveryResponse decodeDiscoveryResponse(const QString& response);

/**
* @brief removes leading zeros from IP address
*
* @param line IP address as returned by the Ping360, e.g: 192.168.002.004"
* @return QString
*/
static QString removeLeadingZerosFromIP(const QString& line);

/**
Expand Down
30 changes: 27 additions & 3 deletions src/sensor/ping360helperservice.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -51,9 +51,33 @@ void Ping360HelperService::doBroadcast()
{
const QByteArray datagram = Ping360AsciiProtocol::discoveryMessage();

// Send discovery message as broadcast and for companion ip subnet
for (const QHostAddress& address : {QHostAddress {QHostAddress::Broadcast}, QHostAddress {"192.168.2.255"}}) {
_broadcastSocket.writeDatagram(datagram, address, Ping360AsciiProtocol::udpPort());
// Retrieve the IP addresses and their associated broadcast addresses
QList<QPair<QHostAddress, QHostAddress>> ipBroadcastAddresses;
QList<QNetworkInterface> interfaces = QNetworkInterface::allInterfaces();
for (const QNetworkInterface& interface : interfaces) {
if (interface.flags().testFlag(QNetworkInterface::IsUp)
&& !interface.flags().testFlag(QNetworkInterface::IsLoopBack)) {
QList<QNetworkAddressEntry> entries = interface.addressEntries();
for (const QNetworkAddressEntry& entry : entries) {
if (entry.ip().protocol() == QAbstractSocket::IPv4Protocol) {
ipBroadcastAddresses.append(qMakePair(entry.ip(), entry.broadcast()));
}
}
}
}

// Send discovery message as broadcast for each interface's associated broadcast address
for (const QPair<QHostAddress, QHostAddress>& addressPair : ipBroadcastAddresses) {
const QHostAddress& ipAddress = addressPair.first;
const QHostAddress& broadcastAddress = addressPair.second;

if (_broadcastSocket.writeDatagram(datagram, broadcastAddress, Ping360AsciiProtocol::udpPort()) == -1) {
qDebug() << "Failed to send datagram to broadcast address:" << broadcastAddress.toString()
<< "for IP address:" << ipAddress.toString();
} else {
qDebug() << "Datagram sent successfully to broadcast address:" << broadcastAddress.toString()
<< "for IP address:" << ipAddress.toString();
}
}
}

Expand Down

0 comments on commit b129811

Please sign in to comment.