]> git.tdb.fi Git - r2c2.git/blob - source/network/client.cpp
Adapt to mspnet API changes
[r2c2.git] / source / network / client.cpp
1 #include <msp/core/maputils.h>
2 #include "client.h"
3
4 using namespace std;
5 using namespace Msp;
6
7 namespace R2C2 {
8
9 Client::Client(const Catalogue &c):
10         catalogue(c),
11         socket(0),
12         comm(0),
13         event_disp(0),
14         power(false),
15         halt(false)
16 { }
17
18 Client::~Client()
19 {
20         delete comm;
21         delete socket;
22         for(map<unsigned, NetTrain *>::iterator i=trains.begin(); i!=trains.end(); ++i)
23                 delete i->second;
24 }
25
26 void Client::use_event_dispatcher(Msp::IO::EventDispatcher &ed)
27 {
28         event_disp = &ed;
29         if(socket)
30                 event_disp->add(*socket);
31 }
32
33 void Client::connect(const Net::SockAddr &addr)
34 {
35         socket = new Net::StreamSocket(addr.get_family());
36         socket->connect(addr);
37         if(event_disp)
38                 event_disp->add(*socket);
39         comm = new Net::Communicator(*socket, proto, *this);
40 }
41
42 void Client::set_power(bool p)
43 {
44         DriverStatePacket pkt;
45         pkt.power = p;
46         pkt.halt = halt;
47         send(pkt);
48 }
49
50 void Client::set_halt(bool h)
51 {
52         DriverStatePacket pkt;
53         pkt.power = power;
54         pkt.halt = h;
55         send(pkt);
56 }
57
58 NetTrain &Client::get_train(unsigned addr) const
59 {
60         return *get_item(trains, addr);
61 }
62
63 void Client::receive(const DriverStatePacket &pkt)
64 {
65         if(pkt.power!=power)
66         {
67                 power = pkt.power;
68                 signal_power_changed.emit(power);
69         }
70         if(pkt.halt!=halt)
71         {
72                 halt = pkt.halt;
73                 signal_halt_changed.emit(halt);
74         }
75 }
76
77 void Client::receive(const EmergencyPacket &pkt)
78 {
79         signal_emergency.emit(pkt.message);
80 }
81
82 void Client::receive(const TrainInfoPacket &pkt)
83 {
84         NetTrain *train = new NetTrain(*this, pkt);
85         trains[pkt.address] = train;
86         signal_train_added.emit(*train);
87 }
88
89 void Client::receive(const TrainControlPacket &pkt)
90 {
91         get_train(pkt.address).process_packet(pkt);
92 }
93
94 void Client::receive(const TrainFunctionPacket &pkt)
95 {
96         get_train(pkt.address).process_packet(pkt);
97 }
98
99 void Client::receive(const TrainStatusPacket &pkt)
100 {
101         get_train(pkt.address).process_packet(pkt);
102 }
103
104 void Client::receive(const RouteInfoPacket &pkt)
105 {
106         routes.push_back(pkt.name);
107 }
108
109 void Client::receive(const TrainRoutePacket &pkt)
110 {
111         get_train(pkt.address).process_packet(pkt);
112 }
113
114 void Client::receive(const ErrorPacket &pkt)
115 {
116         signal_error.emit(pkt.message);
117 }
118
119 } // namespace R2C2