Files
pip/utils/cloud_dispatcher/dispatcherserver.cpp
2020-08-27 19:40:11 +03:00

66 lines
1.6 KiB
C++

#include "dispatcherserver.h"
DispatcherServer::DispatcherServer(PIEthernet::Address addr) : eth(PIEthernet::TCP_Server) {
eth.setParameter(PIEthernet::ReuseAddress);
CONNECTU(&eth, newConnection, this, newConnection);
eth.listen(addr, true);
piCoutObj << "server started" << addr;
CONNECTU(&status_timer, tickEvent, this, printStatus);
status_timer.start(1000);
}
DispatcherServer::~DispatcherServer() {
eth.close();
piCoutObj << "server stoped";
}
void DispatcherServer::printStatus() {
map_mutex.lock();
piCout << PICoutManipulators::NewLine;
piCout << "Connections:";
for (auto c: clients) {
piCout << " " << c->address();
}
piCout << "Servers:";
auto it = c_servers.makeIterator();
while(it.next()){
piCout << " " << it.key();
it.value()->printStatus();
}
map_mutex.unlock();
}
void DispatcherServer::disconnectClient(DispatcherClient *client) {
piCoutObj << "remove client" << client;
map_mutex.lock();
clients.removeOne(client);
map_mutex.unlock();
delete client;
}
void DispatcherServer::newConnection(PIEthernet *cl) {
DispatcherClient * client = new DispatcherClient(cl);
CONNECTU(client, disconnectEvent, this, disconnectClient);
CONNECTL(client, registerServer, [this](PIString sname, DispatcherClient * c){
map_mutex.lock();
c_servers.insert(sname, new CloudServer(c));
map_mutex.unlock();
});
CONNECTL(client, registerClient, [this](PIString sname, DispatcherClient * c){
map_mutex.lock();
if (c_servers.contains(sname)) {
c_servers[sname]->addClient(c);
}
map_mutex.unlock();
});
piCoutObj << "add client" << client;
map_mutex.lock();
clients.push_back(client);
map_mutex.unlock();
}