RoboidControl-cpp/Arduino/Participant.cpp
2025-02-25 17:42:27 +01:00

108 lines
3.0 KiB
C++

#include "Participant.h"
#if defined(ARDUINO)
#if defined(ARDUINO_ARCH_ESP8266)
#include <ESP8266WiFi.h>
#elif defined(ESP32)
#include <WiFi.h>
#endif
#endif
namespace RoboidControl {
namespace Arduino {
void Participant::Setup(int localPort, const char* remoteIpAddress, int remotePort) {
#if defined(ARDUINO)
this->remoteIpAddress = remoteIpAddress;
this->remotePort = remotePort;
GetBroadcastAddress();
if (WiFi.isConnected() == false) {
std::cout << "No network available!\n";
return;
}
udp.begin(this->localPort);
std::cout << "Wifi sync started to port " << this->remotePort << "\n";
#endif
}
void Participant::GetBroadcastAddress() {
#if defined(ARDUINO)
IPAddress broadcastAddress = WiFi.localIP();
broadcastAddress[3] = 255;
String broadcastIpString = broadcastAddress.toString();
this->broadcastIpAddress = new char[broadcastIpString.length() + 1];
broadcastIpString.toCharArray(this->broadcastIpAddress, broadcastIpString.length() + 1);
std::cout << "Broadcast address: " << broadcastIpAddress << "\n";
#endif
}
void Participant::Receive() {
#if defined(ARDUINO)
int packetSize = udp.parsePacket();
while (packetSize > 0) {
udp.read(buffer, packetSize);
String senderAddress = udp.remoteIP().toString();
char sender_ipAddress[16];
senderAddress.toCharArray(sender_ipAddress, 16);
int sender_port = udp.remotePort();
RemoteParticipant* remoteParticipant = this->GetParticipant(sender_ipAddress, sender_port);
if (remoteParticipant == nullptr) {
remoteParticipant = this->AddParticipant(sender_ipAddress, sender_port);
// std::cout << "New sender " << sender_ipAddress << ":" << sender_port
// << "\n";
// std::cout << "New remote participant " << remoteParticipant->ipAddress
// << ":" << remoteParticipant->port << " "
// << (int)remoteParticipant->networkId << "\n";
}
ReceiveData(packetSize, remoteParticipant);
packetSize = udp.parsePacket();
}
#endif
}
bool Participant::Send(RemoteParticipant* remoteParticipant, int bufferSize) {
#if defined(ARDUINO)
// std::cout << "Sending to:\n " << remoteParticipant->ipAddress << ":"
// << remoteParticipant->port << "\n";
int n = 0;
do {
if (n > 0) {
std::cout << "Retry sending\n";
delay(10);
}
n++;
udp.beginPacket(remoteParticipant->ipAddress, remoteParticipant->port);
udp.write((unsigned char*)buffer, bufferSize);
} while (udp.endPacket() == 0 && n < 10);
#endif
return true;
}
bool Participant::Publish(IMessage* msg) {
#ifdef ARDUINO
int bufferSize = msg->Serialize((char*)this->buffer);
if (bufferSize <= 0)
return true;
udp.beginPacket(this->broadcastIpAddress, this->remotePort);
udp.write((unsigned char*)buffer, bufferSize);
udp.endPacket();
// std::cout << "Publish to " << this->broadcastIpAddress << ":"
// << this->remotePort << "\n";
#endif
return true;
};
} // namespace Arduino
} // namespace RoboidControl