RoboidControl-cpp/Participant.cpp
2025-02-28 17:55:25 +01:00

79 lines
2.6 KiB
C++

#include "Participant.h"
#include <string.h>
namespace RoboidControl {
Participant::Participant() {}
Participant::Participant(const char* ipAddress, int port) {
// make a copy of the ip address string
int addressLength = strlen(ipAddress);
int stringLength = addressLength + 1;
char* addressString = new char[stringLength];
#if defined(_WIN32) || defined(_WIN64)
strncpy_s(addressString, stringLength, ipAddress, addressLength); // Leave space for null terminator
#else
strncpy(addressString, ipAddress, addressLength);
#endif
addressString[addressLength] = '\0';
this->ipAddress = addressString;
this->port = port;
}
Participant::~Participant() {
delete[] this->ipAddress;
}
Thing* Participant::Get(unsigned char networkId, unsigned char thingId) {
for (Thing* thing : this->things) {
// if (thing->networkId == networkId && thing->id == thingId)
if (thing->id == thingId)
return thing;
}
// std::cout << "Could not find thing " << this->ipAddress << ":" << this->port
// << "[" << (int)networkId << "/" << (int)thingId << "]\n";
return nullptr;
}
void Participant::Add(Thing* thing, bool checkId) {
if (checkId && thing->id == 0) {
// allocate a new thing ID
thing->id = (unsigned char)this->things.size() + 1;
this->things.push_back(thing);
// std::cout << "Add thing with generated ID " << this->ipAddress << ":" << this->port << "[" <<
// (int)thing->networkId << "/"
// << (int)thing->id << "]\n";
} else {
Thing* foundThing = Get(thing->networkId, thing->id);
if (foundThing == nullptr) {
this->things.push_back(thing);
// std::cout << "Add thing " << this->ipAddress << ":" << this->port << "[" << (int)thing->networkId << "/"
// << (int)thing->id << "]\n";
}
// else
// std::cout << "Did not add, existing thing " << this->ipAddress << ":" << this->port << "["
// << (int)thing->networkId << "/" << (int)thing->id << "]\n";
}
}
void Participant::Remove(Thing* thing) {
this->things.remove_if([thing](Thing* obj) { return obj == thing; });
std::cout << "Removing " << thing->networkId << "/" << thing->id << " list size = " << this->things.size() << "\n";
}
// void Participant::UpdateAll(unsigned long currentTimeMs) {
// // Not very efficient, but it works for now.
// for (Thing* thing : this->things) {
// if (thing != nullptr && thing->GetParent() == nullptr) { // update all root things
// // std::cout << " update " << (int)ix << " thingid " << (int)thing->id
// // << "\n";
// thing->Update(currentTimeMs);
// }
// }
// }
} // namespace RoboidControl