77 lines
2.3 KiB
C++
77 lines
2.3 KiB
C++
#include "UndefinedTask.hpp"
|
|
#include "../types.hpp"
|
|
|
|
#include <chrono>
|
|
#include <cstring>
|
|
#include <iostream>
|
|
#include <sys/socket.h>
|
|
|
|
#include "../../events/types.hpp"
|
|
#include "../../packets/base/GenericPacket.hpp"
|
|
|
|
|
|
namespace drp::task {
|
|
|
|
|
|
void UndefinedTask::handle() {
|
|
// TODO(Faraphel): If .status is UNDEFINED, look for a server.
|
|
// if alone, become a server (if can emit).
|
|
// if everyone is UNKNOWN, elect a server (easiest to join / highest mac address, etc...)
|
|
// if a server is found, become a client.
|
|
|
|
// check if no more peers have been found.
|
|
if (
|
|
std::chrono::high_resolution_clock::now() - this->peers.getModificationTime() >
|
|
std::chrono::milliseconds(5000)
|
|
) {
|
|
// verify if there are peers
|
|
if (this->peers.empty()) {
|
|
// if we are alone in the network
|
|
|
|
// check if we are capable of being a server
|
|
if (!canEmit())
|
|
return;
|
|
|
|
// set ourselves as the server
|
|
this->status = TaskType::SERVER;
|
|
return;
|
|
}
|
|
|
|
// search for a server among the peers
|
|
const auto& server = std::find_if(
|
|
this->peers.begin(),
|
|
this->peers.end(),
|
|
[&](const Peer& peer) { return peer.status == TaskType::SERVER; }
|
|
);
|
|
if (server != this->peers.end()) {
|
|
// if a server have been found, use it
|
|
this->server = *server;
|
|
this->status = TaskType::CLIENT;
|
|
return;
|
|
}
|
|
|
|
// TODO(Faraphel): elect a server among those capable of emitting.
|
|
// send the average ping of all the machine in the information packet ?
|
|
// add an additionnal random value if equals ?
|
|
}
|
|
|
|
// prepare a search message
|
|
packet::GenericPacket packet {};
|
|
packet.channel = 0;
|
|
packet.securityMode = static_cast<std::uint8_t>(packet::SecurityMode::PLAIN);
|
|
packet._content.eventType = static_cast<std::uint8_t>(event::EventType::SEARCH);
|
|
|
|
// send the search message
|
|
if (sendto(
|
|
this->eventSocket,
|
|
&packet,
|
|
sizeof(packet),
|
|
0,
|
|
destinationInfo->ai_addr,
|
|
destinationInfo->ai_addrlen
|
|
) == -1)
|
|
std::cerr << "[Sender] Could not send search event: " << strerror(errno) << std::endl;
|
|
}
|
|
|
|
|
|
}
|